1 //===- Format.h - Efficient printf-style formatting for streams -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the format() function, which can be used with other
11 // LLVM subsystems to provide printf-style formatting. This gives all the power
12 // and risk of printf. This can be used like this (with raw_ostreams as an
15 // OS << "mynumber: " << format("%4.5f", 1234.412) << '\n';
19 // OS << format("mynumber: %4.5f\n", 1234.412);
21 //===----------------------------------------------------------------------===//
23 #ifndef LLVM_SUPPORT_FORMAT_H
24 #define LLVM_SUPPORT_FORMAT_H
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/Support/DataTypes.h"
36 /// This is a helper class used for handling formatted output. It is the
37 /// abstract base class of a templated derived class.
38 class format_object_base {
41 ~format_object_base() = default; // Disallow polymorphic deletion.
42 format_object_base(const format_object_base &) = default;
43 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;
49 format_object_base(const char *fmt) : Fmt(fmt) {}
51 /// Format the object into the specified buffer. On success, this returns
52 /// the length of the formatted string. If the buffer is too small, this
53 /// returns a length to retry with, which will be larger than BufferSize.
54 unsigned print(char *Buffer, unsigned BufferSize) const {
55 assert(BufferSize && "Invalid buffer size!");
57 // Print the string, leaving room for the terminating null.
58 int N = snprint(Buffer, BufferSize);
60 // VC++ and old GlibC return negative on overflow, just double the size.
62 return BufferSize * 2;
64 // Other implementations yield number of bytes needed, not including the
66 if (unsigned(N) >= BufferSize)
69 // Otherwise N is the length of output (not including the final '\0').
74 /// These are templated helper classes used by the format function that
75 /// capture the object to be formatted and the format string. When actually
76 /// printed, this synthesizes the string into a temporary buffer provided and
77 /// returns whether or not it is big enough.
79 // Helper to validate that format() parameters are scalars or pointers.
80 template <typename... Args> struct validate_format_parameters;
81 template <typename Arg, typename... Args>
82 struct validate_format_parameters<Arg, Args...> {
83 static_assert(std::is_scalar<Arg>::value,
84 "format can't be used with non fundamental / non pointer type");
85 validate_format_parameters() { validate_format_parameters<Args...>(); }
87 template <> struct validate_format_parameters<> {};
89 template <typename... Ts>
90 class format_object final : public format_object_base {
91 std::tuple<Ts...> Vals;
93 template <std::size_t... Is>
94 int snprint_tuple(char *Buffer, unsigned BufferSize,
95 index_sequence<Is...>) const {
97 return _snprintf(Buffer, BufferSize, Fmt, std::get<Is>(Vals)...);
99 return snprintf(Buffer, BufferSize, Fmt, std::get<Is>(Vals)...);
104 format_object(const char *fmt, const Ts &... vals)
105 : format_object_base(fmt), Vals(vals...) {
106 validate_format_parameters<Ts...>();
109 int snprint(char *Buffer, unsigned BufferSize) const override {
110 return snprint_tuple(Buffer, BufferSize, index_sequence_for<Ts...>());
114 /// These are helper functions used to produce formatted output. They use
115 /// template type deduction to construct the appropriate instance of the
116 /// format_object class to simplify their construction.
118 /// This is typically used like:
120 /// OS << format("%0.4f", myfloat) << '\n';
123 template <typename... Ts>
124 inline format_object<Ts...> format(const char *Fmt, const Ts &... Vals) {
125 return format_object<Ts...>(Fmt, Vals...);
128 /// This is a helper class used for left_justify() and right_justify().
129 class FormattedString {
133 friend class raw_ostream;
136 FormattedString(StringRef S, unsigned W, bool R)
137 : Str(S), Width(W), RightJustify(R) { }
140 /// left_justify - append spaces after string so total output is
141 /// \p Width characters. If \p Str is larger that \p Width, full string
142 /// is written with no padding.
143 inline FormattedString left_justify(StringRef Str, unsigned Width) {
144 return FormattedString(Str, Width, false);
147 /// right_justify - add spaces before string so total output is
148 /// \p Width characters. If \p Str is larger that \p Width, full string
149 /// is written with no padding.
150 inline FormattedString right_justify(StringRef Str, unsigned Width) {
151 return FormattedString(Str, Width, true);
154 /// This is a helper class used for format_hex() and format_decimal().
155 class FormattedNumber {
162 friend class raw_ostream;
165 FormattedNumber(uint64_t HV, int64_t DV, unsigned W, bool H, bool U,
167 : HexValue(HV), DecValue(DV), Width(W), Hex(H), Upper(U),
171 /// format_hex - Output \p N as a fixed width hexadecimal. If number will not
172 /// fit in width, full number is still printed. Examples:
173 /// OS << format_hex(255, 4) => 0xff
174 /// OS << format_hex(255, 4, true) => 0xFF
175 /// OS << format_hex(255, 6) => 0x00ff
176 /// OS << format_hex(255, 2) => 0xff
177 inline FormattedNumber format_hex(uint64_t N, unsigned Width,
178 bool Upper = false) {
179 assert(Width <= 18 && "hex width must be <= 18");
180 return FormattedNumber(N, 0, Width, true, Upper, true);
183 /// format_hex_no_prefix - Output \p N as a fixed width hexadecimal. Does not
184 /// prepend '0x' to the outputted string. If number will not fit in width,
185 /// full number is still printed. Examples:
186 /// OS << format_hex_no_prefix(255, 2) => ff
187 /// OS << format_hex_no_prefix(255, 2, true) => FF
188 /// OS << format_hex_no_prefix(255, 4) => 00ff
189 /// OS << format_hex_no_prefix(255, 1) => ff
190 inline FormattedNumber format_hex_no_prefix(uint64_t N, unsigned Width,
191 bool Upper = false) {
192 assert(Width <= 16 && "hex width must be <= 16");
193 return FormattedNumber(N, 0, Width, true, Upper, false);
196 /// format_decimal - Output \p N as a right justified, fixed-width decimal. If
197 /// number will not fit in width, full number is still printed. Examples:
198 /// OS << format_decimal(0, 5) => " 0"
199 /// OS << format_decimal(255, 5) => " 255"
200 /// OS << format_decimal(-1, 3) => " -1"
201 /// OS << format_decimal(12345, 3) => "12345"
202 inline FormattedNumber format_decimal(int64_t N, unsigned Width) {
203 return FormattedNumber(0, N, Width, false, false, false);
206 class FormattedBytes {
207 ArrayRef<uint8_t> Bytes;
209 // If not None, display offsets for each line relative to starting value.
210 Optional<uint64_t> FirstByteOffset;
211 uint32_t IndentLevel; // Number of characters to indent each line.
212 uint32_t NumPerLine; // Number of bytes to show per line.
213 uint8_t ByteGroupSize; // How many hex bytes are grouped without spaces
214 bool Upper; // Show offset and hex bytes as upper case.
215 bool ASCII; // Show the ASCII bytes for the hex bytes to the right.
216 friend class raw_ostream;
219 FormattedBytes(ArrayRef<uint8_t> B, uint32_t IL, Optional<uint64_t> O,
220 uint32_t NPL, uint8_t BGS, bool U, bool A)
221 : Bytes(B), FirstByteOffset(O), IndentLevel(IL), NumPerLine(NPL),
222 ByteGroupSize(BGS), Upper(U), ASCII(A) {
224 if (ByteGroupSize > NumPerLine)
225 ByteGroupSize = NumPerLine;
229 inline FormattedBytes
230 format_bytes(ArrayRef<uint8_t> Bytes, Optional<uint64_t> FirstByteOffset = None,
231 uint32_t NumPerLine = 16, uint8_t ByteGroupSize = 4,
232 uint32_t IndentLevel = 0, bool Upper = false) {
233 return FormattedBytes(Bytes, IndentLevel, FirstByteOffset, NumPerLine,
234 ByteGroupSize, Upper, false);
237 inline FormattedBytes
238 format_bytes_with_ascii(ArrayRef<uint8_t> Bytes,
239 Optional<uint64_t> FirstByteOffset = None,
240 uint32_t NumPerLine = 16, uint8_t ByteGroupSize = 4,
241 uint32_t IndentLevel = 0, bool Upper = false) {
242 return FormattedBytes(Bytes, IndentLevel, FirstByteOffset, NumPerLine,
243 ByteGroupSize, Upper, true);
246 } // end namespace llvm