FormatCommon.h 2.1 KB

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