LLVM 17.0.0git
Format.h
Go to the documentation of this file.
1//===- Format.h - Efficient printf-style formatting for streams -*- 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//
9// This file implements the format() function, which can be used with other
10// LLVM subsystems to provide printf-style formatting. This gives all the power
11// and risk of printf. This can be used like this (with raw_ostreams as an
12// example):
13//
14// OS << "mynumber: " << format("%4.5f", 1234.412) << '\n';
15//
16// Or if you prefer:
17//
18// OS << format("mynumber: %4.5f\n", 1234.412);
19//
20//===----------------------------------------------------------------------===//
21
22#ifndef LLVM_SUPPORT_FORMAT_H
23#define LLVM_SUPPORT_FORMAT_H
24
25#include "llvm/ADT/ArrayRef.h"
26#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/StringRef.h"
29#include <cassert>
30#include <cstdio>
31#include <tuple>
32#include <utility>
33
34namespace llvm {
35
36/// This is a helper class used for handling formatted output. It is the
37/// abstract base class of a templated derived class.
39protected:
40 const char *Fmt;
41 ~format_object_base() = default; // Disallow polymorphic deletion.
43 virtual void home(); // Out of line virtual method.
44
45 /// Call snprintf() for this object, on the given buffer and size.
46 virtual int snprint(char *Buffer, unsigned BufferSize) const = 0;
47
48public:
49 format_object_base(const char *fmt) : Fmt(fmt) {}
50
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!");
56
57 // Print the string, leaving room for the terminating null.
58 int N = snprint(Buffer, BufferSize);
59
60 // VC++ and old GlibC return negative on overflow, just double the size.
61 if (N < 0)
62 return BufferSize * 2;
63
64 // Other implementations yield number of bytes needed, not including the
65 // final '\0'.
66 if (unsigned(N) >= BufferSize)
67 return N + 1;
68
69 // Otherwise N is the length of output (not including the final '\0').
70 return N;
71 }
72};
73
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.
78
79// Helper to validate that format() parameters are scalars or pointers.
80template <typename... Args> struct validate_format_parameters;
81template <typename Arg, typename... Args>
83 static_assert(std::is_scalar_v<Arg>,
84 "format can't be used with non fundamental / non pointer type");
86};
87template <> struct validate_format_parameters<> {};
88
89template <typename... Ts>
90class format_object final : public format_object_base {
91 std::tuple<Ts...> Vals;
92
93 template <std::size_t... Is>
94 int snprint_tuple(char *Buffer, unsigned BufferSize,
95 std::index_sequence<Is...>) const {
96#ifdef _MSC_VER
97 return _snprintf(Buffer, BufferSize, Fmt, std::get<Is>(Vals)...);
98#else
99 return snprintf(Buffer, BufferSize, Fmt, std::get<Is>(Vals)...);
100#endif
101 }
102
103public:
104 format_object(const char *fmt, const Ts &... vals)
105 : format_object_base(fmt), Vals(vals...) {
107 }
108
109 int snprint(char *Buffer, unsigned BufferSize) const override {
110 return snprint_tuple(Buffer, BufferSize, std::index_sequence_for<Ts...>());
111 }
112};
113
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.
117///
118/// This is typically used like:
119/// \code
120/// OS << format("%0.4f", myfloat) << '\n';
121/// \endcode
122
123template <typename... Ts>
124inline format_object<Ts...> format(const char *Fmt, const Ts &... Vals) {
125 return format_object<Ts...>(Fmt, Vals...);
126}
127
128/// This is a helper class for left_justify, right_justify, and center_justify.
130public:
133 : Str(S), Width(W), Justify(J) {}
134
135private:
136 StringRef Str;
137 unsigned Width;
138 Justification Justify;
139 friend class raw_ostream;
140};
141
142/// left_justify - append spaces after string so total output is
143/// \p Width characters. If \p Str is larger that \p Width, full string
144/// is written with no padding.
145inline FormattedString left_justify(StringRef Str, unsigned Width) {
147}
148
149/// right_justify - add spaces before string so total output is
150/// \p Width characters. If \p Str is larger that \p Width, full string
151/// is written with no padding.
152inline FormattedString right_justify(StringRef Str, unsigned Width) {
154}
155
156/// center_justify - add spaces before and after string so total output is
157/// \p Width characters. If \p Str is larger that \p Width, full string
158/// is written with no padding.
159inline FormattedString center_justify(StringRef Str, unsigned Width) {
161}
162
163/// This is a helper class used for format_hex() and format_decimal().
165 uint64_t HexValue;
166 int64_t DecValue;
167 unsigned Width;
168 bool Hex;
169 bool Upper;
170 bool HexPrefix;
171 friend class raw_ostream;
172
173public:
174 FormattedNumber(uint64_t HV, int64_t DV, unsigned W, bool H, bool U,
175 bool Prefix)
176 : HexValue(HV), DecValue(DV), Width(W), Hex(H), Upper(U),
177 HexPrefix(Prefix) {}
178};
179
180/// format_hex - Output \p N as a fixed width hexadecimal. If number will not
181/// fit in width, full number is still printed. Examples:
182/// OS << format_hex(255, 4) => 0xff
183/// OS << format_hex(255, 4, true) => 0xFF
184/// OS << format_hex(255, 6) => 0x00ff
185/// OS << format_hex(255, 2) => 0xff
186inline FormattedNumber format_hex(uint64_t N, unsigned Width,
187 bool Upper = false) {
188 assert(Width <= 18 && "hex width must be <= 18");
189 return FormattedNumber(N, 0, Width, true, Upper, true);
190}
191
192/// format_hex_no_prefix - Output \p N as a fixed width hexadecimal. Does not
193/// prepend '0x' to the outputted string. If number will not fit in width,
194/// full number is still printed. Examples:
195/// OS << format_hex_no_prefix(255, 2) => ff
196/// OS << format_hex_no_prefix(255, 2, true) => FF
197/// OS << format_hex_no_prefix(255, 4) => 00ff
198/// OS << format_hex_no_prefix(255, 1) => ff
200 bool Upper = false) {
201 assert(Width <= 16 && "hex width must be <= 16");
202 return FormattedNumber(N, 0, Width, true, Upper, false);
203}
204
205/// format_decimal - Output \p N as a right justified, fixed-width decimal. If
206/// number will not fit in width, full number is still printed. Examples:
207/// OS << format_decimal(0, 5) => " 0"
208/// OS << format_decimal(255, 5) => " 255"
209/// OS << format_decimal(-1, 3) => " -1"
210/// OS << format_decimal(12345, 3) => "12345"
211inline FormattedNumber format_decimal(int64_t N, unsigned Width) {
212 return FormattedNumber(0, N, Width, false, false, false);
213}
214
216 ArrayRef<uint8_t> Bytes;
217
218 // If not std::nullopt, display offsets for each line relative to starting
219 // value.
220 std::optional<uint64_t> FirstByteOffset;
221 uint32_t IndentLevel; // Number of characters to indent each line.
222 uint32_t NumPerLine; // Number of bytes to show per line.
223 uint8_t ByteGroupSize; // How many hex bytes are grouped without spaces
224 bool Upper; // Show offset and hex bytes as upper case.
225 bool ASCII; // Show the ASCII bytes for the hex bytes to the right.
226 friend class raw_ostream;
227
228public:
229 FormattedBytes(ArrayRef<uint8_t> B, uint32_t IL, std::optional<uint64_t> O,
230 uint32_t NPL, uint8_t BGS, bool U, bool A)
231 : Bytes(B), FirstByteOffset(O), IndentLevel(IL), NumPerLine(NPL),
232 ByteGroupSize(BGS), Upper(U), ASCII(A) {
233
234 if (ByteGroupSize > NumPerLine)
235 ByteGroupSize = NumPerLine;
236 }
237};
238
239inline FormattedBytes
241 std::optional<uint64_t> FirstByteOffset = std::nullopt,
242 uint32_t NumPerLine = 16, uint8_t ByteGroupSize = 4,
243 uint32_t IndentLevel = 0, bool Upper = false) {
244 return FormattedBytes(Bytes, IndentLevel, FirstByteOffset, NumPerLine,
245 ByteGroupSize, Upper, false);
246}
247
248inline FormattedBytes
250 std::optional<uint64_t> FirstByteOffset = std::nullopt,
251 uint32_t NumPerLine = 16, uint8_t ByteGroupSize = 4,
252 uint32_t IndentLevel = 0, bool Upper = false) {
253 return FormattedBytes(Bytes, IndentLevel, FirstByteOffset, NumPerLine,
254 ByteGroupSize, Upper, true);
255}
256
257} // end namespace llvm
258
259#endif
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define H(x, y, z)
Definition: MD5.cpp:57
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
FormattedBytes(ArrayRef< uint8_t > B, uint32_t IL, std::optional< uint64_t > O, uint32_t NPL, uint8_t BGS, bool U, bool A)
Definition: Format.h:229
This is a helper class used for format_hex() and format_decimal().
Definition: Format.h:164
FormattedNumber(uint64_t HV, int64_t DV, unsigned W, bool H, bool U, bool Prefix)
Definition: Format.h:174
This is a helper class for left_justify, right_justify, and center_justify.
Definition: Format.h:129
FormattedString(StringRef S, unsigned W, Justification J)
Definition: Format.h:132
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
This is a helper class used for handling formatted output.
Definition: Format.h:38
format_object_base(const char *fmt)
Definition: Format.h:49
unsigned print(char *Buffer, unsigned BufferSize) const
Format the object into the specified buffer.
Definition: Format.h:54
const char * Fmt
Definition: Format.h:40
virtual int snprint(char *Buffer, unsigned BufferSize) const =0
Call snprintf() for this object, on the given buffer and size.
format_object_base(const format_object_base &)=default
format_object(const char *fmt, const Ts &... vals)
Definition: Format.h:104
int snprint(char *Buffer, unsigned BufferSize) const override
Call snprintf() for this object, on the given buffer and size.
Definition: Format.h:109
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
FormattedNumber format_decimal(int64_t N, unsigned Width)
format_decimal - Output N as a right justified, fixed-width decimal.
Definition: Format.h:211
FormattedString right_justify(StringRef Str, unsigned Width)
right_justify - add spaces before string so total output is Width characters.
Definition: Format.h:152
FormattedString center_justify(StringRef Str, unsigned Width)
center_justify - add spaces before and after string so total output is Width characters.
Definition: Format.h:159
FormattedNumber format_hex(uint64_t N, unsigned Width, bool Upper=false)
format_hex - Output N as a fixed width hexadecimal.
Definition: Format.h:186
FormattedNumber format_hex_no_prefix(uint64_t N, unsigned Width, bool Upper=false)
format_hex_no_prefix - Output N as a fixed width hexadecimal.
Definition: Format.h:199
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:124
FormattedBytes format_bytes_with_ascii(ArrayRef< uint8_t > Bytes, std::optional< uint64_t > FirstByteOffset=std::nullopt, uint32_t NumPerLine=16, uint8_t ByteGroupSize=4, uint32_t IndentLevel=0, bool Upper=false)
Definition: Format.h:249
FormattedString left_justify(StringRef Str, unsigned Width)
left_justify - append spaces after string so total output is Width characters.
Definition: Format.h:145
FormattedBytes format_bytes(ArrayRef< uint8_t > Bytes, std::optional< uint64_t > FirstByteOffset=std::nullopt, uint32_t NumPerLine=16, uint8_t ByteGroupSize=4, uint32_t IndentLevel=0, bool Upper=false)
Definition: Format.h:240
#define N
These are templated helper classes used by the format function that capture the object to be formatte...
Definition: Format.h:80