FormatCommon.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- FormatCommon.h - Formatters for common LLVM types --------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_SUPPORT_FORMATCOMMON_H
  14. #define LLVM_SUPPORT_FORMATCOMMON_H
  15. #include "llvm/ADT/SmallString.h"
  16. #include "llvm/Support/FormatVariadicDetails.h"
  17. #include "llvm/Support/raw_ostream.h"
  18. namespace llvm {
  19. enum class AlignStyle { Left, Center, Right };
  20. struct FmtAlign {
  21. detail::format_adapter &Adapter;
  22. AlignStyle Where;
  23. size_t Amount;
  24. char Fill;
  25. FmtAlign(detail::format_adapter &Adapter, AlignStyle Where, size_t Amount,
  26. char Fill = ' ')
  27. : Adapter(Adapter), Where(Where), Amount(Amount), Fill(Fill) {}
  28. void format(raw_ostream &S, StringRef Options) {
  29. // If we don't need to align, we can format straight into the underlying
  30. // stream. Otherwise we have to go through an intermediate stream first
  31. // in order to calculate how long the output is so we can align it.
  32. // TODO: Make the format method return the number of bytes written, that
  33. // way we can also skip the intermediate stream for left-aligned output.
  34. if (Amount == 0) {
  35. Adapter.format(S, Options);
  36. return;
  37. }
  38. SmallString<64> Item;
  39. raw_svector_ostream Stream(Item);
  40. Adapter.format(Stream, Options);
  41. if (Amount <= Item.size()) {
  42. S << Item;
  43. return;
  44. }
  45. size_t PadAmount = Amount - Item.size();
  46. switch (Where) {
  47. case AlignStyle::Left:
  48. S << Item;
  49. fill(S, PadAmount);
  50. break;
  51. case AlignStyle::Center: {
  52. size_t X = PadAmount / 2;
  53. fill(S, X);
  54. S << Item;
  55. fill(S, PadAmount - X);
  56. break;
  57. }
  58. default:
  59. fill(S, PadAmount);
  60. S << Item;
  61. break;
  62. }
  63. }
  64. private:
  65. void fill(llvm::raw_ostream &S, uint32_t Count) {
  66. for (uint32_t I = 0; I < Count; ++I)
  67. S << Fill;
  68. }
  69. };
  70. }
  71. #endif
  72. #ifdef __GNUC__
  73. #pragma GCC diagnostic pop
  74. #endif