WPILibC++  2020.3.2-60-g3011ebe
Format.h
1 //===- Format.h - Efficient printf-style formatting for streams -*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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
13 // example):
14 //
15 // OS << "mynumber: " << format("%4.5f", 1234.412) << '\n';
16 //
17 // Or if you prefer:
18 //
19 // OS << format("mynumber: %4.5f\n", 1234.412);
20 //
21 //===----------------------------------------------------------------------===//
22 
23 #ifndef WPIUTIL_WPI_FORMAT_H
24 #define WPIUTIL_WPI_FORMAT_H
25 
26 #include "wpi/ArrayRef.h"
27 #include "wpi/StringRef.h"
28 #include <cassert>
29 #include <cstdint>
30 #include <cstdio>
31 #include <optional>
32 #include <tuple>
33 #include <utility>
34 
35 namespace wpi {
36 
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 
47  virtual int snprint(char *Buffer, unsigned BufferSize) const = 0;
48 
49 public:
50  format_object_base(const char *fmt) : Fmt(fmt) {}
51 
55  unsigned print(char *Buffer, unsigned BufferSize) const {
56  assert(BufferSize && "Invalid buffer size!");
57 
58  // Print the string, leaving room for the terminating null.
59  int N = snprint(Buffer, BufferSize);
60 
61  // VC++ and old GlibC return negative on overflow, just double the size.
62  if (N < 0)
63  return BufferSize * 2;
64 
65  // Other implementations yield number of bytes needed, not including the
66  // final '\0'.
67  if (unsigned(N) >= BufferSize)
68  return N + 1;
69 
70  // Otherwise N is the length of output (not including the final '\0').
71  return N;
72  }
73 };
74 
79 
80 // Helper to validate that format() parameters are scalars or pointers.
81 template <typename... Args> struct validate_format_parameters;
82 template <typename Arg, typename... Args>
83 struct validate_format_parameters<Arg, Args...> {
84  static_assert(std::is_scalar<Arg>::value,
85  "format can't be used with non fundamental / non pointer type");
87 };
88 template <> struct validate_format_parameters<> {};
89 
90 template <typename... Ts>
91 class format_object final : public format_object_base {
92  std::tuple<Ts...> Vals;
93 
94  template <std::size_t... Is>
95  int snprint_tuple(char *Buffer, unsigned BufferSize,
96  std::index_sequence<Is...>) const {
97 #ifdef _MSC_VER
98  return _snprintf_s(Buffer, BufferSize, BufferSize, Fmt, std::get<Is>(Vals)...);
99 #else
100 #ifdef __GNUC__
101 #pragma GCC diagnostic push
102 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
103 #endif
104  return snprintf(Buffer, BufferSize, Fmt, std::get<Is>(Vals)...);
105 #ifdef __GNUC__
106 #pragma GCC diagnostic pop
107 #endif
108 #endif
109  }
110 
111 public:
112  format_object(const char *fmt, const Ts &... vals)
113  : format_object_base(fmt), Vals(vals...) {
115  }
116 
117  int snprint(char *Buffer, unsigned BufferSize) const override {
118  return snprint_tuple(Buffer, BufferSize, std::index_sequence_for<Ts...>());
119  }
120 };
121 
130 
131 template <typename... Ts>
132 inline format_object<Ts...> format(const char *Fmt, const Ts &... Vals) {
133  return format_object<Ts...>(Fmt, Vals...);
134 }
135 
138 public:
139  enum Justification { JustifyNone, JustifyLeft, JustifyRight, JustifyCenter };
140  FormattedString(StringRef S, unsigned W, Justification J)
141  : Str(S), Width(W), Justify(J) {}
142 
143 private:
144  StringRef Str;
145  unsigned Width;
146  Justification Justify;
147  friend class raw_ostream;
148 };
149 
153 inline FormattedString left_justify(StringRef Str, unsigned Width) {
154  return FormattedString(Str, Width, FormattedString::JustifyLeft);
155 }
156 
160 inline FormattedString right_justify(StringRef Str, unsigned Width) {
161  return FormattedString(Str, Width, FormattedString::JustifyRight);
162 }
163 
167 inline FormattedString center_justify(StringRef Str, unsigned Width) {
168  return FormattedString(Str, Width, FormattedString::JustifyCenter);
169 }
170 
173  uint64_t HexValue;
174  int64_t DecValue;
175  unsigned Width;
176  bool Hex;
177  bool Upper;
178  bool HexPrefix;
179  friend class raw_ostream;
180 
181 public:
182  FormattedNumber(uint64_t HV, int64_t DV, unsigned W, bool H, bool U,
183  bool Prefix)
184  : HexValue(HV), DecValue(DV), Width(W), Hex(H), Upper(U),
185  HexPrefix(Prefix) {}
186 };
187 
194 inline FormattedNumber format_hex(uint64_t N, unsigned Width,
195  bool Upper = false) {
196  assert(Width <= 18 && "hex width must be <= 18");
197  return FormattedNumber(N, 0, Width, true, Upper, true);
198 }
199 
207 inline FormattedNumber format_hex_no_prefix(uint64_t N, unsigned Width,
208  bool Upper = false) {
209  assert(Width <= 16 && "hex width must be <= 16");
210  return FormattedNumber(N, 0, Width, true, Upper, false);
211 }
212 
219 inline FormattedNumber format_decimal(int64_t N, unsigned Width) {
220  return FormattedNumber(0, N, Width, false, false, false);
221 }
222 
224  ArrayRef<uint8_t> Bytes;
225 
226  // If not nullopt, display offsets for each line relative to starting value.
227  std::optional<uint64_t> FirstByteOffset;
228  uint32_t IndentLevel; // Number of characters to indent each line.
229  uint32_t NumPerLine; // Number of bytes to show per line.
230  uint8_t ByteGroupSize; // How many hex bytes are grouped without spaces
231  bool Upper; // Show offset and hex bytes as upper case.
232  bool ASCII; // Show the ASCII bytes for the hex bytes to the right.
233  friend class raw_ostream;
234 
235 public:
236  FormattedBytes(ArrayRef<uint8_t> B, uint32_t IL, std::optional<uint64_t> O,
237  uint32_t NPL, uint8_t BGS, bool U, bool A)
238  : Bytes(B), FirstByteOffset(O), IndentLevel(IL), NumPerLine(NPL),
239  ByteGroupSize(BGS), Upper(U), ASCII(A) {
240 
241  if (ByteGroupSize > NumPerLine)
242  ByteGroupSize = NumPerLine;
243  }
244 };
245 
246 inline FormattedBytes
247 format_bytes(ArrayRef<uint8_t> Bytes, std::optional<uint64_t> FirstByteOffset = std::nullopt,
248  uint32_t NumPerLine = 16, uint8_t ByteGroupSize = 4,
249  uint32_t IndentLevel = 0, bool Upper = false) {
250  return FormattedBytes(Bytes, IndentLevel, FirstByteOffset, NumPerLine,
251  ByteGroupSize, Upper, false);
252 }
253 
254 inline FormattedBytes
255 format_bytes_with_ascii(ArrayRef<uint8_t> Bytes,
256  std::optional<uint64_t> FirstByteOffset = std::nullopt,
257  uint32_t NumPerLine = 16, uint8_t ByteGroupSize = 4,
258  uint32_t IndentLevel = 0, bool Upper = false) {
259  return FormattedBytes(Bytes, IndentLevel, FirstByteOffset, NumPerLine,
260  ByteGroupSize, Upper, true);
261 }
262 
263 } // end namespace wpi
264 
265 #endif
wpi::right_justify
FormattedString right_justify(StringRef Str, unsigned Width)
right_justify - add spaces before string so total output is Width characters.
Definition: Format.h:160
wpi::format_object::snprint
int snprint(char *Buffer, unsigned BufferSize) const override
Call snprintf() for this object, on the given buffer and size.
Definition: Format.h:117
wpi::format
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:132
wpi::FormattedString
This is a helper class for left_justify, right_justify, and center_justify.
Definition: Format.h:137
wpi::ArrayRef< uint8_t >
wpi::format_object
Definition: Format.h:91
wpi::validate_format_parameters
These are templated helper classes used by the format function that capture the object to be formatte...
Definition: Format.h:81
wpi
WPILib C++ utilities (wpiutil) namespace.
Definition: Endian.h:31
wpi::FormattedNumber
This is a helper class used for format_hex() and format_decimal().
Definition: Format.h:172
wpi::format_object_base
This is a helper class used for handling formatted output.
Definition: Format.h:39
wpi::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
wpi::format_decimal
FormattedNumber format_decimal(int64_t N, unsigned Width)
format_decimal - Output N as a right justified, fixed-width decimal.
Definition: Format.h:219
wpi::format_hex_no_prefix
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:207
wpi::format_object_base::print
unsigned print(char *Buffer, unsigned BufferSize) const
Format the object into the specified buffer.
Definition: Format.h:55
wpi::format_object_base::snprint
virtual int snprint(char *Buffer, unsigned BufferSize) const =0
Call snprintf() for this object, on the given buffer and size.
wpi::FormattedBytes
Definition: Format.h:223
wpi::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:47
wpi::center_justify
FormattedString center_justify(StringRef Str, unsigned Width)
center_justify - add spaces before and after string so total output is Width characters.
Definition: Format.h:167
wpi::left_justify
FormattedString left_justify(StringRef Str, unsigned Width)
left_justify - append spaces after string so total output is Width characters.
Definition: Format.h:153
wpi::format_hex
FormattedNumber format_hex(uint64_t N, unsigned Width, bool Upper=false)
format_hex - Output N as a fixed width hexadecimal.
Definition: Format.h:194