blob: aa754a6a5b36f46499ca733c9f7233d23b11b724 [file] [log] [blame]
Glen Stark72d51e02016-06-08 01:23:32 +02001/*
2 Formatting library for C++
3
4 Copyright (c) 2012 - 2016, Victor Zverovich
5 All rights reserved.
6
7 For the license information refer to format.h.
8 */
9
10#ifndef FMT_PRINTF_H_
11#define FMT_PRINTF_H_
12
13#include <algorithm> // std::fill_n
14#include <limits> // std::numeric_limits
15
16#include "fmt/format.h"
17
18namespace fmt {
19namespace internal {
20
21// Checks if a value fits in int - used to avoid warnings about comparing
22// signed and unsigned integers.
23template <bool IsSigned>
24struct IntChecker {
25 template <typename T>
26 static bool fits_in_int(T value) {
27 unsigned max = std::numeric_limits<int>::max();
28 return value <= max;
29 }
30 static bool fits_in_int(bool) { return true; }
31};
32
33template <>
34struct IntChecker<true> {
35 template <typename T>
36 static bool fits_in_int(T value) {
37 return value >= std::numeric_limits<int>::min() &&
38 value <= std::numeric_limits<int>::max();
39 }
40 static bool fits_in_int(int) { return true; }
41};
42
43class PrecisionHandler : public ArgVisitor<PrecisionHandler, int> {
44 public:
45 void report_unhandled_arg() {
46 FMT_THROW(FormatError("precision is not integer"));
47 }
48
49 template <typename T>
50 int visit_any_int(T value) {
51 if (!IntChecker<std::numeric_limits<T>::is_signed>::fits_in_int(value))
52 FMT_THROW(FormatError("number is too big"));
53 return static_cast<int>(value);
54 }
55};
56
57// IsZeroInt::visit(arg) returns true iff arg is a zero integer.
58class IsZeroInt : public ArgVisitor<IsZeroInt, bool> {
59 public:
60 template <typename T>
61 bool visit_any_int(T value) { return value == 0; }
62};
63
64template <typename T, typename U>
65struct is_same {
66 enum { value = 0 };
67};
68
69template <typename T>
70struct is_same<T, T> {
71 enum { value = 1 };
72};
73
74// An argument visitor that converts an integer argument to T for printf,
75// if T is an integral type. If T is void, the argument is converted to
76// corresponding signed or unsigned type depending on the type specifier:
77// 'd' and 'i' - signed, other - unsigned)
78template <typename T = void>
79class ArgConverter : public ArgVisitor<ArgConverter<T>, void> {
80 private:
81 internal::Arg &arg_;
82 wchar_t type_;
83
84 FMT_DISALLOW_COPY_AND_ASSIGN(ArgConverter);
85
86 public:
87 ArgConverter(internal::Arg &arg, wchar_t type)
88 : arg_(arg), type_(type) {}
89
90 void visit_bool(bool value) {
91 if (type_ != 's')
92 visit_any_int(value);
93 }
94
95 template <typename U>
96 void visit_any_int(U value) {
97 bool is_signed = type_ == 'd' || type_ == 'i';
98 using internal::Arg;
99 typedef typename internal::Conditional<
100 is_same<T, void>::value, U, T>::type TargetType;
101 if (sizeof(TargetType) <= sizeof(int)) {
102 // Extra casts are used to silence warnings.
103 if (is_signed) {
104 arg_.type = Arg::INT;
105 arg_.int_value = static_cast<int>(static_cast<TargetType>(value));
106 } else {
107 arg_.type = Arg::UINT;
108 typedef typename internal::MakeUnsigned<TargetType>::Type Unsigned;
109 arg_.uint_value = static_cast<unsigned>(static_cast<Unsigned>(value));
110 }
111 } else {
112 if (is_signed) {
113 arg_.type = Arg::LONG_LONG;
114 // glibc's printf doesn't sign extend arguments of smaller types:
115 // std::printf("%lld", -42); // prints "4294967254"
116 // but we don't have to do the same because it's a UB.
117 arg_.long_long_value = static_cast<LongLong>(value);
118 } else {
119 arg_.type = Arg::ULONG_LONG;
120 arg_.ulong_long_value =
121 static_cast<typename internal::MakeUnsigned<U>::Type>(value);
122 }
123 }
124 }
125};
126
127// Converts an integer argument to char for printf.
128class CharConverter : public ArgVisitor<CharConverter, void> {
129 private:
130 internal::Arg &arg_;
131
132 FMT_DISALLOW_COPY_AND_ASSIGN(CharConverter);
133
134 public:
135 explicit CharConverter(internal::Arg &arg) : arg_(arg) {}
136
137 template <typename T>
138 void visit_any_int(T value) {
139 arg_.type = internal::Arg::CHAR;
140 arg_.int_value = static_cast<char>(value);
141 }
142};
143
144// Checks if an argument is a valid printf width specifier and sets
145// left alignment if it is negative.
146class WidthHandler : public ArgVisitor<WidthHandler, unsigned> {
147 private:
148 FormatSpec &spec_;
149
150 FMT_DISALLOW_COPY_AND_ASSIGN(WidthHandler);
151
152 public:
153 explicit WidthHandler(FormatSpec &spec) : spec_(spec) {}
154
155 void report_unhandled_arg() {
156 FMT_THROW(FormatError("width is not integer"));
157 }
158
159 template <typename T>
160 unsigned visit_any_int(T value) {
161 typedef typename internal::IntTraits<T>::MainType UnsignedType;
162 UnsignedType width = static_cast<UnsignedType>(value);
163 if (internal::is_negative(value)) {
164 spec_.align_ = ALIGN_LEFT;
165 width = 0 - width;
166 }
167 if (width > std::numeric_limits<int>::max())
168 FMT_THROW(FormatError("number is too big"));
169 return static_cast<unsigned>(width);
170 }
171};
172
173template <typename Impl, typename Char>
174class BasicPrintfArgFormatter : public ArgFormatterBase<Impl, Char> {
175 private:
176 void write_null_pointer() {
177 this->spec().type_ = 0;
178 this->write("(nil)");
179 }
180
181 typedef ArgFormatterBase<Impl, Char> Base;
182
183 public:
184 BasicPrintfArgFormatter(BasicWriter<Char> &w, FormatSpec &s)
185 : ArgFormatterBase<Impl, Char>(w, s) {}
186
187 void visit_bool(bool value) {
188 FormatSpec &fmt_spec = this->spec();
189 if (fmt_spec.type_ != 's')
190 return this->visit_any_int(value);
191 fmt_spec.type_ = 0;
192 this->write(value);
193 }
194
195 void visit_char(int value) {
196 const FormatSpec &fmt_spec = this->spec();
197 BasicWriter<Char> &w = this->writer();
198 if (fmt_spec.type_ && fmt_spec.type_ != 'c')
199 w.write_int(value, fmt_spec);
200 typedef typename BasicWriter<Char>::CharPtr CharPtr;
201 CharPtr out = CharPtr();
202 if (fmt_spec.width_ > 1) {
203 Char fill = ' ';
204 out = w.grow_buffer(fmt_spec.width_);
205 if (fmt_spec.align_ != ALIGN_LEFT) {
206 std::fill_n(out, fmt_spec.width_ - 1, fill);
207 out += fmt_spec.width_ - 1;
208 } else {
209 std::fill_n(out + 1, fmt_spec.width_ - 1, fill);
210 }
211 } else {
212 out = w.grow_buffer(1);
213 }
214 *out = static_cast<Char>(value);
215 }
216
217 void visit_cstring(const char *value) {
218 if (value)
219 Base::visit_cstring(value);
220 else if (this->spec().type_ == 'p')
221 write_null_pointer();
222 else
223 this->write("(null)");
224 }
225
226 void visit_pointer(const void *value) {
227 if (value)
228 return Base::visit_pointer(value);
229 this->spec().type_ = 0;
230 write_null_pointer();
231 }
232
233 void visit_custom(Arg::CustomValue c) {
234 BasicFormatter<Char> formatter(ArgList(), this->writer());
235 const Char format_str[] = {'}', 0};
236 const Char *format = format_str;
237 c.format(&formatter, c.value, &format);
238 }
239};
240
241/** The default printf argument formatter. */
242template <typename Char>
243class PrintfArgFormatter
244 : public BasicPrintfArgFormatter<PrintfArgFormatter<Char>, Char> {
245 public:
246 /** Constructs an argument formatter object. */
247 PrintfArgFormatter(BasicWriter<Char> &w, FormatSpec &s)
248 : BasicPrintfArgFormatter<PrintfArgFormatter<Char>, Char>(w, s) {}
249};
250
251// A printf formatter.
252template <typename Char, typename ArgFormatter = PrintfArgFormatter<Char> >
253class PrintfFormatter : private FormatterBase {
254 private:
255 void parse_flags(FormatSpec &spec, const Char *&s);
256
257 // Returns the argument with specified index or, if arg_index is equal
258 // to the maximum unsigned value, the next argument.
259 Arg get_arg(const Char *s,
260 unsigned arg_index = (std::numeric_limits<unsigned>::max)());
261
262 // Parses argument index, flags and width and returns the argument index.
263 unsigned parse_header(const Char *&s, FormatSpec &spec);
264
265 public:
266 explicit PrintfFormatter(const ArgList &args) : FormatterBase(args) {}
267 FMT_API void format(BasicWriter<Char> &writer,
268 BasicCStringRef<Char> format_str);
269};
270
271template <typename Char, typename AF>
272void PrintfFormatter<Char, AF>::parse_flags(FormatSpec &spec, const Char *&s) {
273 for (;;) {
274 switch (*s++) {
275 case '-':
276 spec.align_ = ALIGN_LEFT;
277 break;
278 case '+':
279 spec.flags_ |= SIGN_FLAG | PLUS_FLAG;
280 break;
281 case '0':
282 spec.fill_ = '0';
283 break;
284 case ' ':
285 spec.flags_ |= SIGN_FLAG;
286 break;
287 case '#':
288 spec.flags_ |= HASH_FLAG;
289 break;
290 default:
291 --s;
292 return;
293 }
294 }
295}
296
297template <typename Char, typename AF>
298Arg PrintfFormatter<Char, AF>::get_arg(const Char *s, unsigned arg_index) {
299 (void)s;
300 const char *error = 0;
301 Arg arg = arg_index == std::numeric_limits<unsigned>::max() ?
302 next_arg(error) : FormatterBase::get_arg(arg_index - 1, error);
303 if (error)
304 FMT_THROW(FormatError(!*s ? "invalid format string" : error));
305 return arg;
306}
307
308template <typename Char, typename AF>
309unsigned PrintfFormatter<Char, AF>::parse_header(
310 const Char *&s, FormatSpec &spec) {
311 unsigned arg_index = std::numeric_limits<unsigned>::max();
312 Char c = *s;
313 if (c >= '0' && c <= '9') {
314 // Parse an argument index (if followed by '$') or a width possibly
315 // preceded with '0' flag(s).
316 unsigned value = parse_nonnegative_int(s);
317 if (*s == '$') { // value is an argument index
318 ++s;
319 arg_index = value;
320 } else {
321 if (c == '0')
322 spec.fill_ = '0';
323 if (value != 0) {
324 // Nonzero value means that we parsed width and don't need to
325 // parse it or flags again, so return now.
326 spec.width_ = value;
327 return arg_index;
328 }
329 }
330 }
331 parse_flags(spec, s);
332 // Parse width.
333 if (*s >= '0' && *s <= '9') {
334 spec.width_ = parse_nonnegative_int(s);
335 } else if (*s == '*') {
336 ++s;
337 spec.width_ = WidthHandler(spec).visit(get_arg(s));
338 }
339 return arg_index;
340}
341
342template <typename Char, typename AF>
343void PrintfFormatter<Char, AF>::format(
344 BasicWriter<Char> &writer, BasicCStringRef<Char> format_str) {
345 const Char *start = format_str.c_str();
346 const Char *s = start;
347 while (*s) {
348 Char c = *s++;
349 if (c != '%') continue;
350 if (*s == c) {
351 write(writer, start, s);
352 start = ++s;
353 continue;
354 }
355 write(writer, start, s - 1);
356
357 FormatSpec spec;
358 spec.align_ = ALIGN_RIGHT;
359
360 // Parse argument index, flags and width.
361 unsigned arg_index = parse_header(s, spec);
362
363 // Parse precision.
364 if (*s == '.') {
365 ++s;
366 if ('0' <= *s && *s <= '9') {
367 spec.precision_ = static_cast<int>(parse_nonnegative_int(s));
368 } else if (*s == '*') {
369 ++s;
370 spec.precision_ = PrecisionHandler().visit(get_arg(s));
371 }
372 }
373
374 Arg arg = get_arg(s, arg_index);
375 if (spec.flag(HASH_FLAG) && IsZeroInt().visit(arg))
376 spec.flags_ &= ~to_unsigned<int>(HASH_FLAG);
377 if (spec.fill_ == '0') {
378 if (arg.type <= Arg::LAST_NUMERIC_TYPE)
379 spec.align_ = ALIGN_NUMERIC;
380 else
381 spec.fill_ = ' '; // Ignore '0' flag for non-numeric types.
382 }
383
384 // Parse length and convert the argument to the required type.
385 switch (*s++) {
386 case 'h':
387 if (*s == 'h')
388 ArgConverter<signed char>(arg, *++s).visit(arg);
389 else
390 ArgConverter<short>(arg, *s).visit(arg);
391 break;
392 case 'l':
393 if (*s == 'l')
394 ArgConverter<fmt::LongLong>(arg, *++s).visit(arg);
395 else
396 ArgConverter<long>(arg, *s).visit(arg);
397 break;
398 case 'j':
399 ArgConverter<intmax_t>(arg, *s).visit(arg);
400 break;
401 case 'z':
402 ArgConverter<std::size_t>(arg, *s).visit(arg);
403 break;
404 case 't':
405 ArgConverter<std::ptrdiff_t>(arg, *s).visit(arg);
406 break;
407 case 'L':
408 // printf produces garbage when 'L' is omitted for long double, no
409 // need to do the same.
410 break;
411 default:
412 --s;
413 ArgConverter<void>(arg, *s).visit(arg);
414 }
415
416 // Parse type.
417 if (!*s)
418 FMT_THROW(FormatError("invalid format string"));
419 spec.type_ = static_cast<char>(*s++);
420 if (arg.type <= Arg::LAST_INTEGER_TYPE) {
421 // Normalize type.
422 switch (spec.type_) {
423 case 'i': case 'u':
424 spec.type_ = 'd';
425 break;
426 case 'c':
427 // TODO: handle wchar_t
428 CharConverter(arg).visit(arg);
429 break;
430 }
431 }
432
433 start = s;
434
435 // Format argument.
436 AF(writer, spec).visit(arg);
437 }
438 write(writer, start, s);
439}
440} // namespace internal
441
442template <typename Char>
443void printf(BasicWriter<Char> &w, BasicCStringRef<Char> format, ArgList args) {
444 internal::PrintfFormatter<Char>(args).format(w, format);
445}
446
447/**
448 \rst
449 Formats arguments and returns the result as a string.
450
451 **Example**::
452
453 std::string message = fmt::sprintf("The answer is %d", 42);
454 \endrst
455*/
456inline std::string sprintf(CStringRef format, ArgList args) {
457 MemoryWriter w;
458 printf(w, format, args);
459 return w.str();
460}
461FMT_VARIADIC(std::string, sprintf, CStringRef)
462
463inline std::wstring sprintf(WCStringRef format, ArgList args) {
464 WMemoryWriter w;
465 printf(w, format, args);
466 return w.str();
467}
468FMT_VARIADIC_W(std::wstring, sprintf, WCStringRef)
469
470/**
471 \rst
472 Prints formatted data to the file *f*.
473
474 **Example**::
475
476 fmt::fprintf(stderr, "Don't %s!", "panic");
477 \endrst
478 */
479FMT_API int fprintf(std::FILE *f, CStringRef format, ArgList args);
480FMT_VARIADIC(int, fprintf, std::FILE *, CStringRef)
481
482/**
483 \rst
484 Prints formatted data to ``stdout``.
485
486 **Example**::
487
488 fmt::printf("Elapsed time: %.2f seconds", 1.23);
489 \endrst
490 */
491inline int printf(CStringRef format, ArgList args) {
492 return fprintf(stdout, format, args);
493}
494FMT_VARIADIC(int, printf, CStringRef)
495} // namespace fmt
496
497#endif // FMT_PRINTF_H_