WPILibC++  2019.1.1-beta-2-13-ge4aa45f
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Modules Pages
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/STLExtras.h"
28 #include "wpi/StringRef.h"
29 #include <cassert>
30 #include <cstdint>
31 #include <cstdio>
32 #include <tuple>
33 
34 namespace wpi {
35 
39 protected:
40  const char *Fmt;
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.
44 
46  virtual int snprint(char *Buffer, unsigned BufferSize) const = 0;
47 
48 public:
49  format_object_base(const char *fmt) : Fmt(fmt) {}
50 
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 
78 
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");
86 };
87 template <> struct validate_format_parameters<> {};
88 
89 template <typename... Ts>
90 class 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  index_sequence<Is...>) const {
96 #ifdef _MSC_VER
97  return _snprintf(Buffer, BufferSize, Fmt, std::get<Is>(Vals)...);
98 #else
99 #ifdef __GNUC__
100 #pragma GCC diagnostic push
101 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
102 #endif
103  return snprintf(Buffer, BufferSize, Fmt, std::get<Is>(Vals)...);
104 #ifdef __GNUC__
105 #pragma GCC diagnostic pop
106 #endif
107 #endif
108  }
109 
110 public:
111  format_object(const char *fmt, const Ts &... vals)
112  : format_object_base(fmt), Vals(vals...) {
114  }
115 
116  int snprint(char *Buffer, unsigned BufferSize) const override {
117  return snprint_tuple(Buffer, BufferSize, index_sequence_for<Ts...>());
118  }
119 };
120 
129 
130 template <typename... Ts>
131 inline format_object<Ts...> format(const char *Fmt, const Ts &... Vals) {
132  return format_object<Ts...>(Fmt, Vals...);
133 }
134 
137 public:
138  enum Justification { JustifyNone, JustifyLeft, JustifyRight, JustifyCenter };
139  FormattedString(StringRef S, unsigned W, Justification J)
140  : Str(S), Width(W), Justify(J) {}
141 
142 private:
143  StringRef Str;
144  unsigned Width;
145  Justification Justify;
146  friend class raw_ostream;
147 };
148 
152 inline FormattedString left_justify(StringRef Str, unsigned Width) {
153  return FormattedString(Str, Width, FormattedString::JustifyLeft);
154 }
155 
159 inline FormattedString right_justify(StringRef Str, unsigned Width) {
160  return FormattedString(Str, Width, FormattedString::JustifyRight);
161 }
162 
166 inline FormattedString center_justify(StringRef Str, unsigned Width) {
167  return FormattedString(Str, Width, FormattedString::JustifyCenter);
168 }
169 
172  uint64_t HexValue;
173  int64_t DecValue;
174  unsigned Width;
175  bool Hex;
176  bool Upper;
177  bool HexPrefix;
178  friend class raw_ostream;
179 
180 public:
181  FormattedNumber(uint64_t HV, int64_t DV, unsigned W, bool H, bool U,
182  bool Prefix)
183  : HexValue(HV), DecValue(DV), Width(W), Hex(H), Upper(U),
184  HexPrefix(Prefix) {}
185 };
186 
193 inline FormattedNumber format_hex(uint64_t N, unsigned Width,
194  bool Upper = false) {
195  assert(Width <= 18 && "hex width must be <= 18");
196  return FormattedNumber(N, 0, Width, true, Upper, true);
197 }
198 
206 inline FormattedNumber format_hex_no_prefix(uint64_t N, unsigned Width,
207  bool Upper = false) {
208  assert(Width <= 16 && "hex width must be <= 16");
209  return FormattedNumber(N, 0, Width, true, Upper, false);
210 }
211 
218 inline FormattedNumber format_decimal(int64_t N, unsigned Width) {
219  return FormattedNumber(0, N, Width, false, false, false);
220 }
221 
223  ArrayRef<uint8_t> Bytes;
224 
225  // If not None, display offsets for each line relative to starting value.
226  Optional<uint64_t> FirstByteOffset;
227  uint32_t IndentLevel; // Number of characters to indent each line.
228  uint32_t NumPerLine; // Number of bytes to show per line.
229  uint8_t ByteGroupSize; // How many hex bytes are grouped without spaces
230  bool Upper; // Show offset and hex bytes as upper case.
231  bool ASCII; // Show the ASCII bytes for the hex bytes to the right.
232  friend class raw_ostream;
233 
234 public:
236  uint32_t NPL, uint8_t BGS, bool U, bool A)
237  : Bytes(B), FirstByteOffset(O), IndentLevel(IL), NumPerLine(NPL),
238  ByteGroupSize(BGS), Upper(U), ASCII(A) {
239 
240  if (ByteGroupSize > NumPerLine)
241  ByteGroupSize = NumPerLine;
242  }
243 };
244 
245 inline FormattedBytes
246 format_bytes(ArrayRef<uint8_t> Bytes, Optional<uint64_t> FirstByteOffset = None,
247  uint32_t NumPerLine = 16, uint8_t ByteGroupSize = 4,
248  uint32_t IndentLevel = 0, bool Upper = false) {
249  return FormattedBytes(Bytes, IndentLevel, FirstByteOffset, NumPerLine,
250  ByteGroupSize, Upper, false);
251 }
252 
253 inline FormattedBytes
254 format_bytes_with_ascii(ArrayRef<uint8_t> Bytes,
255  Optional<uint64_t> FirstByteOffset = None,
256  uint32_t NumPerLine = 16, uint8_t ByteGroupSize = 4,
257  uint32_t IndentLevel = 0, bool Upper = false) {
258  return FormattedBytes(Bytes, IndentLevel, FirstByteOffset, NumPerLine,
259  ByteGroupSize, Upper, true);
260 }
261 
262 } // end namespace wpi
263 
264 #endif
This is a helper class for left_justify, right_justify, and center_justify.
Definition: Format.h:136
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:45
FormattedString center_justify(StringRef Str, unsigned Width)
center_justify - add spaces before and after string so total output is Width characters.
Definition: Format.h:166
FormattedNumber format_hex(uint64_t N, unsigned Width, bool Upper=false)
format_hex - Output N as a fixed width hexadecimal.
Definition: Format.h:193
FormattedString right_justify(StringRef Str, unsigned Width)
right_justify - add spaces before string so total output is Width characters.
Definition: Format.h:159
Alias for the common case of a sequence of size_ts.
Definition: STLExtras.h:407
virtual int snprint(char *Buffer, unsigned BufferSize) const =0
Call snprintf() for this object, on the given buffer and size.
Definition: Format.h:90
WPILib C++ utilities (wpiutil) namespace.
Definition: SmallString.h:21
This is a helper class used for format_hex() and format_decimal().
Definition: Format.h:171
Creates a compile-time integer sequence for a parameter pack.
Definition: STLExtras.h:409
int snprint(char *Buffer, unsigned BufferSize) const override
Call snprintf() for this object, on the given buffer and size.
Definition: Format.h:116
This is a helper class used for handling formatted output.
Definition: Format.h:38
format_object< Ts...> format(const char *Fmt, const Ts &...Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:131
unsigned print(char *Buffer, unsigned BufferSize) const
Format the object into the specified buffer.
Definition: Format.h:54
FormattedNumber format_decimal(int64_t N, unsigned Width)
format_decimal - Output N as a right justified, fixed-width decimal.
Definition: Format.h:218
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
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:206
Definition: Format.h:222
FormattedString left_justify(StringRef Str, unsigned Width)
left_justify - append spaces after string so total output is Width characters.
Definition: Format.h:152
These are templated helper classes used by the format function that capture the object to be formatte...
Definition: Format.h:80