Format.h 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- Format.h - Efficient printf-style formatting for streams -*- 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. //
  14. // This file implements the format() function, which can be used with other
  15. // LLVM subsystems to provide printf-style formatting. This gives all the power
  16. // and risk of printf. This can be used like this (with raw_ostreams as an
  17. // example):
  18. //
  19. // OS << "mynumber: " << format("%4.5f", 1234.412) << '\n';
  20. //
  21. // Or if you prefer:
  22. //
  23. // OS << format("mynumber: %4.5f\n", 1234.412);
  24. //
  25. //===----------------------------------------------------------------------===//
  26. #ifndef LLVM_SUPPORT_FORMAT_H
  27. #define LLVM_SUPPORT_FORMAT_H
  28. #include "llvm/ADT/ArrayRef.h"
  29. #include "llvm/ADT/STLExtras.h"
  30. #include "llvm/ADT/StringRef.h"
  31. #include "llvm/Support/DataTypes.h"
  32. #include <cassert>
  33. #include <cstdio>
  34. #include <tuple>
  35. #include <utility>
  36. namespace llvm {
  37. /// This is a helper class used for handling formatted output. It is the
  38. /// abstract base class of a templated derived class.
  39. class format_object_base {
  40. protected:
  41. const char *Fmt;
  42. ~format_object_base() = default; // Disallow polymorphic deletion.
  43. format_object_base(const format_object_base &) = default;
  44. virtual void home(); // Out of line virtual method.
  45. /// Call snprintf() for this object, on the given buffer and size.
  46. virtual int snprint(char *Buffer, unsigned BufferSize) const = 0;
  47. public:
  48. format_object_base(const char *fmt) : Fmt(fmt) {}
  49. /// Format the object into the specified buffer. On success, this returns
  50. /// the length of the formatted string. If the buffer is too small, this
  51. /// returns a length to retry with, which will be larger than BufferSize.
  52. unsigned print(char *Buffer, unsigned BufferSize) const {
  53. assert(BufferSize && "Invalid buffer size!");
  54. // Print the string, leaving room for the terminating null.
  55. int N = snprint(Buffer, BufferSize);
  56. // VC++ and old GlibC return negative on overflow, just double the size.
  57. if (N < 0)
  58. return BufferSize * 2;
  59. // Other implementations yield number of bytes needed, not including the
  60. // final '\0'.
  61. if (unsigned(N) >= BufferSize)
  62. return N + 1;
  63. // Otherwise N is the length of output (not including the final '\0').
  64. return N;
  65. }
  66. };
  67. /// These are templated helper classes used by the format function that
  68. /// capture the object to be formatted and the format string. When actually
  69. /// printed, this synthesizes the string into a temporary buffer provided and
  70. /// returns whether or not it is big enough.
  71. // Helper to validate that format() parameters are scalars or pointers.
  72. template <typename... Args> struct validate_format_parameters;
  73. template <typename Arg, typename... Args>
  74. struct validate_format_parameters<Arg, Args...> {
  75. static_assert(std::is_scalar<Arg>::value,
  76. "format can't be used with non fundamental / non pointer type");
  77. validate_format_parameters() { validate_format_parameters<Args...>(); }
  78. };
  79. template <> struct validate_format_parameters<> {};
  80. template <typename... Ts>
  81. class format_object final : public format_object_base {
  82. std::tuple<Ts...> Vals;
  83. template <std::size_t... Is>
  84. int snprint_tuple(char *Buffer, unsigned BufferSize,
  85. std::index_sequence<Is...>) const {
  86. #ifdef _MSC_VER
  87. return _snprintf(Buffer, BufferSize, Fmt, std::get<Is>(Vals)...);
  88. #else
  89. return snprintf(Buffer, BufferSize, Fmt, std::get<Is>(Vals)...);
  90. #endif
  91. }
  92. public:
  93. format_object(const char *fmt, const Ts &... vals)
  94. : format_object_base(fmt), Vals(vals...) {
  95. validate_format_parameters<Ts...>();
  96. }
  97. int snprint(char *Buffer, unsigned BufferSize) const override {
  98. return snprint_tuple(Buffer, BufferSize, std::index_sequence_for<Ts...>());
  99. }
  100. };
  101. /// These are helper functions used to produce formatted output. They use
  102. /// template type deduction to construct the appropriate instance of the
  103. /// format_object class to simplify their construction.
  104. ///
  105. /// This is typically used like:
  106. /// \code
  107. /// OS << format("%0.4f", myfloat) << '\n';
  108. /// \endcode
  109. template <typename... Ts>
  110. inline format_object<Ts...> format(const char *Fmt, const Ts &... Vals) {
  111. return format_object<Ts...>(Fmt, Vals...);
  112. }
  113. /// This is a helper class for left_justify, right_justify, and center_justify.
  114. class FormattedString {
  115. public:
  116. enum Justification { JustifyNone, JustifyLeft, JustifyRight, JustifyCenter };
  117. FormattedString(StringRef S, unsigned W, Justification J)
  118. : Str(S), Width(W), Justify(J) {}
  119. private:
  120. StringRef Str;
  121. unsigned Width;
  122. Justification Justify;
  123. friend class raw_ostream;
  124. };
  125. /// left_justify - append spaces after string so total output is
  126. /// \p Width characters. If \p Str is larger that \p Width, full string
  127. /// is written with no padding.
  128. inline FormattedString left_justify(StringRef Str, unsigned Width) {
  129. return FormattedString(Str, Width, FormattedString::JustifyLeft);
  130. }
  131. /// right_justify - add spaces before string so total output is
  132. /// \p Width characters. If \p Str is larger that \p Width, full string
  133. /// is written with no padding.
  134. inline FormattedString right_justify(StringRef Str, unsigned Width) {
  135. return FormattedString(Str, Width, FormattedString::JustifyRight);
  136. }
  137. /// center_justify - add spaces before and after string so total output is
  138. /// \p Width characters. If \p Str is larger that \p Width, full string
  139. /// is written with no padding.
  140. inline FormattedString center_justify(StringRef Str, unsigned Width) {
  141. return FormattedString(Str, Width, FormattedString::JustifyCenter);
  142. }
  143. /// This is a helper class used for format_hex() and format_decimal().
  144. class FormattedNumber {
  145. uint64_t HexValue;
  146. int64_t DecValue;
  147. unsigned Width;
  148. bool Hex;
  149. bool Upper;
  150. bool HexPrefix;
  151. friend class raw_ostream;
  152. public:
  153. FormattedNumber(uint64_t HV, int64_t DV, unsigned W, bool H, bool U,
  154. bool Prefix)
  155. : HexValue(HV), DecValue(DV), Width(W), Hex(H), Upper(U),
  156. HexPrefix(Prefix) {}
  157. };
  158. /// format_hex - Output \p N as a fixed width hexadecimal. If number will not
  159. /// fit in width, full number is still printed. Examples:
  160. /// OS << format_hex(255, 4) => 0xff
  161. /// OS << format_hex(255, 4, true) => 0xFF
  162. /// OS << format_hex(255, 6) => 0x00ff
  163. /// OS << format_hex(255, 2) => 0xff
  164. inline FormattedNumber format_hex(uint64_t N, unsigned Width,
  165. bool Upper = false) {
  166. assert(Width <= 18 && "hex width must be <= 18");
  167. return FormattedNumber(N, 0, Width, true, Upper, true);
  168. }
  169. /// format_hex_no_prefix - Output \p N as a fixed width hexadecimal. Does not
  170. /// prepend '0x' to the outputted string. If number will not fit in width,
  171. /// full number is still printed. Examples:
  172. /// OS << format_hex_no_prefix(255, 2) => ff
  173. /// OS << format_hex_no_prefix(255, 2, true) => FF
  174. /// OS << format_hex_no_prefix(255, 4) => 00ff
  175. /// OS << format_hex_no_prefix(255, 1) => ff
  176. inline FormattedNumber format_hex_no_prefix(uint64_t N, unsigned Width,
  177. bool Upper = false) {
  178. assert(Width <= 16 && "hex width must be <= 16");
  179. return FormattedNumber(N, 0, Width, true, Upper, false);
  180. }
  181. /// format_decimal - Output \p N as a right justified, fixed-width decimal. If
  182. /// number will not fit in width, full number is still printed. Examples:
  183. /// OS << format_decimal(0, 5) => " 0"
  184. /// OS << format_decimal(255, 5) => " 255"
  185. /// OS << format_decimal(-1, 3) => " -1"
  186. /// OS << format_decimal(12345, 3) => "12345"
  187. inline FormattedNumber format_decimal(int64_t N, unsigned Width) {
  188. return FormattedNumber(0, N, Width, false, false, false);
  189. }
  190. class FormattedBytes {
  191. ArrayRef<uint8_t> Bytes;
  192. // If not None, display offsets for each line relative to starting value.
  193. Optional<uint64_t> FirstByteOffset;
  194. uint32_t IndentLevel; // Number of characters to indent each line.
  195. uint32_t NumPerLine; // Number of bytes to show per line.
  196. uint8_t ByteGroupSize; // How many hex bytes are grouped without spaces
  197. bool Upper; // Show offset and hex bytes as upper case.
  198. bool ASCII; // Show the ASCII bytes for the hex bytes to the right.
  199. friend class raw_ostream;
  200. public:
  201. FormattedBytes(ArrayRef<uint8_t> B, uint32_t IL, Optional<uint64_t> O,
  202. uint32_t NPL, uint8_t BGS, bool U, bool A)
  203. : Bytes(B), FirstByteOffset(O), IndentLevel(IL), NumPerLine(NPL),
  204. ByteGroupSize(BGS), Upper(U), ASCII(A) {
  205. if (ByteGroupSize > NumPerLine)
  206. ByteGroupSize = NumPerLine;
  207. }
  208. };
  209. inline FormattedBytes
  210. format_bytes(ArrayRef<uint8_t> Bytes, Optional<uint64_t> FirstByteOffset = None,
  211. uint32_t NumPerLine = 16, uint8_t ByteGroupSize = 4,
  212. uint32_t IndentLevel = 0, bool Upper = false) {
  213. return FormattedBytes(Bytes, IndentLevel, FirstByteOffset, NumPerLine,
  214. ByteGroupSize, Upper, false);
  215. }
  216. inline FormattedBytes
  217. format_bytes_with_ascii(ArrayRef<uint8_t> Bytes,
  218. Optional<uint64_t> FirstByteOffset = None,
  219. uint32_t NumPerLine = 16, uint8_t ByteGroupSize = 4,
  220. uint32_t IndentLevel = 0, bool Upper = false) {
  221. return FormattedBytes(Bytes, IndentLevel, FirstByteOffset, NumPerLine,
  222. ByteGroupSize, Upper, true);
  223. }
  224. } // end namespace llvm
  225. #endif
  226. #ifdef __GNUC__
  227. #pragma GCC diagnostic pop
  228. #endif