blob: 78cda420ab8c3901c188f823c84f69b829f8f92e [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 }
Victor Zveroviche0d6f632016-06-15 06:29:47 -0700167 unsigned int_max = std::numeric_limits<int>::max();
168 if (width > int_max)
Glen Stark72d51e02016-06-08 01:23:32 +0200169 FMT_THROW(FormatError("number is too big"));
170 return static_cast<unsigned>(width);
171 }
172};
173
174template <typename Impl, typename Char>
175class BasicPrintfArgFormatter : public ArgFormatterBase<Impl, Char> {
176 private:
177 void write_null_pointer() {
178 this->spec().type_ = 0;
179 this->write("(nil)");
180 }
181
182 typedef ArgFormatterBase<Impl, Char> Base;
183
184 public:
185 BasicPrintfArgFormatter(BasicWriter<Char> &w, FormatSpec &s)
186 : ArgFormatterBase<Impl, Char>(w, s) {}
187
188 void visit_bool(bool value) {
189 FormatSpec &fmt_spec = this->spec();
190 if (fmt_spec.type_ != 's')
191 return this->visit_any_int(value);
192 fmt_spec.type_ = 0;
193 this->write(value);
194 }
195
196 void visit_char(int value) {
197 const FormatSpec &fmt_spec = this->spec();
198 BasicWriter<Char> &w = this->writer();
199 if (fmt_spec.type_ && fmt_spec.type_ != 'c')
200 w.write_int(value, fmt_spec);
201 typedef typename BasicWriter<Char>::CharPtr CharPtr;
202 CharPtr out = CharPtr();
203 if (fmt_spec.width_ > 1) {
204 Char fill = ' ';
205 out = w.grow_buffer(fmt_spec.width_);
206 if (fmt_spec.align_ != ALIGN_LEFT) {
207 std::fill_n(out, fmt_spec.width_ - 1, fill);
208 out += fmt_spec.width_ - 1;
209 } else {
210 std::fill_n(out + 1, fmt_spec.width_ - 1, fill);
211 }
212 } else {
213 out = w.grow_buffer(1);
214 }
215 *out = static_cast<Char>(value);
216 }
217
218 void visit_cstring(const char *value) {
219 if (value)
220 Base::visit_cstring(value);
221 else if (this->spec().type_ == 'p')
222 write_null_pointer();
223 else
224 this->write("(null)");
225 }
226
227 void visit_pointer(const void *value) {
228 if (value)
229 return Base::visit_pointer(value);
230 this->spec().type_ = 0;
231 write_null_pointer();
232 }
233
234 void visit_custom(Arg::CustomValue c) {
235 BasicFormatter<Char> formatter(ArgList(), this->writer());
236 const Char format_str[] = {'}', 0};
237 const Char *format = format_str;
238 c.format(&formatter, c.value, &format);
239 }
240};
241
242/** The default printf argument formatter. */
243template <typename Char>
244class PrintfArgFormatter
245 : public BasicPrintfArgFormatter<PrintfArgFormatter<Char>, Char> {
246 public:
247 /** Constructs an argument formatter object. */
248 PrintfArgFormatter(BasicWriter<Char> &w, FormatSpec &s)
249 : BasicPrintfArgFormatter<PrintfArgFormatter<Char>, Char>(w, s) {}
250};
Victor Zverovichd4ddaaf2016-07-20 08:09:14 -0700251} // namespace internal
Glen Stark72d51e02016-06-08 01:23:32 +0200252
Victor Zverovichd4ddaaf2016-07-20 08:09:14 -0700253/** This template formats data and writes the output to a writer. */
254template <typename Char,
255 typename ArgFormatter = internal::PrintfArgFormatter<Char> >
256class PrintfFormatter : private internal::FormatterBase {
Glen Stark72d51e02016-06-08 01:23:32 +0200257 private:
Victor Zverovichab054532016-07-20 08:21:13 -0700258 BasicWriter<Char> &writer_;
259
Glen Stark72d51e02016-06-08 01:23:32 +0200260 void parse_flags(FormatSpec &spec, const Char *&s);
261
262 // Returns the argument with specified index or, if arg_index is equal
263 // to the maximum unsigned value, the next argument.
Victor Zverovichd4ddaaf2016-07-20 08:09:14 -0700264 internal::Arg get_arg(
265 const Char *s,
Glen Stark72d51e02016-06-08 01:23:32 +0200266 unsigned arg_index = (std::numeric_limits<unsigned>::max)());
267
268 // Parses argument index, flags and width and returns the argument index.
269 unsigned parse_header(const Char *&s, FormatSpec &spec);
270
271 public:
Victor Zverovichd4ddaaf2016-07-20 08:09:14 -0700272 /**
273 \rst
Victor Zverovichab054532016-07-20 08:21:13 -0700274 Constructs a ``PrintfFormatter`` object. References to the arguments and
275 the writer are stored in the formatter object so make sure they have
276 appropriate lifetimes.
Victor Zverovichd4ddaaf2016-07-20 08:09:14 -0700277 \endrst
278 */
Victor Zverovichab054532016-07-20 08:21:13 -0700279 explicit PrintfFormatter(const ArgList &args, BasicWriter<Char> &w)
280 : FormatterBase(args), writer_(w) {}
Victor Zverovichd4ddaaf2016-07-20 08:09:14 -0700281
Victor Zverovich355861f2016-07-20 08:26:14 -0700282 /** Formats stored arguments and writes the output to the writer. */
Victor Zverovichab054532016-07-20 08:21:13 -0700283 FMT_API void format(BasicCStringRef<Char> format_str);
Glen Stark72d51e02016-06-08 01:23:32 +0200284};
285
286template <typename Char, typename AF>
287void PrintfFormatter<Char, AF>::parse_flags(FormatSpec &spec, const Char *&s) {
288 for (;;) {
289 switch (*s++) {
290 case '-':
291 spec.align_ = ALIGN_LEFT;
292 break;
293 case '+':
294 spec.flags_ |= SIGN_FLAG | PLUS_FLAG;
295 break;
296 case '0':
297 spec.fill_ = '0';
298 break;
299 case ' ':
300 spec.flags_ |= SIGN_FLAG;
301 break;
302 case '#':
303 spec.flags_ |= HASH_FLAG;
304 break;
305 default:
306 --s;
307 return;
308 }
309 }
310}
311
312template <typename Char, typename AF>
Victor Zverovichd4ddaaf2016-07-20 08:09:14 -0700313internal::Arg PrintfFormatter<Char, AF>::get_arg(const Char *s,
314 unsigned arg_index) {
Glen Stark72d51e02016-06-08 01:23:32 +0200315 (void)s;
316 const char *error = 0;
Victor Zverovichd4ddaaf2016-07-20 08:09:14 -0700317 internal::Arg arg = arg_index == std::numeric_limits<unsigned>::max() ?
Glen Stark72d51e02016-06-08 01:23:32 +0200318 next_arg(error) : FormatterBase::get_arg(arg_index - 1, error);
319 if (error)
320 FMT_THROW(FormatError(!*s ? "invalid format string" : error));
321 return arg;
322}
323
324template <typename Char, typename AF>
325unsigned PrintfFormatter<Char, AF>::parse_header(
326 const Char *&s, FormatSpec &spec) {
327 unsigned arg_index = std::numeric_limits<unsigned>::max();
328 Char c = *s;
329 if (c >= '0' && c <= '9') {
330 // Parse an argument index (if followed by '$') or a width possibly
331 // preceded with '0' flag(s).
Victor Zverovichd4ddaaf2016-07-20 08:09:14 -0700332 unsigned value = internal::parse_nonnegative_int(s);
Glen Stark72d51e02016-06-08 01:23:32 +0200333 if (*s == '$') { // value is an argument index
334 ++s;
335 arg_index = value;
336 } else {
337 if (c == '0')
338 spec.fill_ = '0';
339 if (value != 0) {
340 // Nonzero value means that we parsed width and don't need to
341 // parse it or flags again, so return now.
342 spec.width_ = value;
343 return arg_index;
344 }
345 }
346 }
347 parse_flags(spec, s);
348 // Parse width.
349 if (*s >= '0' && *s <= '9') {
Victor Zverovichd4ddaaf2016-07-20 08:09:14 -0700350 spec.width_ = internal::parse_nonnegative_int(s);
Glen Stark72d51e02016-06-08 01:23:32 +0200351 } else if (*s == '*') {
352 ++s;
Victor Zverovichd4ddaaf2016-07-20 08:09:14 -0700353 spec.width_ = internal::WidthHandler(spec).visit(get_arg(s));
Glen Stark72d51e02016-06-08 01:23:32 +0200354 }
355 return arg_index;
356}
357
358template <typename Char, typename AF>
Victor Zverovichab054532016-07-20 08:21:13 -0700359void PrintfFormatter<Char, AF>::format(BasicCStringRef<Char> format_str) {
Glen Stark72d51e02016-06-08 01:23:32 +0200360 const Char *start = format_str.c_str();
361 const Char *s = start;
362 while (*s) {
363 Char c = *s++;
364 if (c != '%') continue;
365 if (*s == c) {
Victor Zverovichab054532016-07-20 08:21:13 -0700366 write(writer_, start, s);
Glen Stark72d51e02016-06-08 01:23:32 +0200367 start = ++s;
368 continue;
369 }
Victor Zverovichab054532016-07-20 08:21:13 -0700370 write(writer_, start, s - 1);
Glen Stark72d51e02016-06-08 01:23:32 +0200371
372 FormatSpec spec;
373 spec.align_ = ALIGN_RIGHT;
374
375 // Parse argument index, flags and width.
376 unsigned arg_index = parse_header(s, spec);
377
378 // Parse precision.
379 if (*s == '.') {
380 ++s;
381 if ('0' <= *s && *s <= '9') {
Victor Zverovichd4ddaaf2016-07-20 08:09:14 -0700382 spec.precision_ = static_cast<int>(internal::parse_nonnegative_int(s));
Glen Stark72d51e02016-06-08 01:23:32 +0200383 } else if (*s == '*') {
384 ++s;
Victor Zverovichd4ddaaf2016-07-20 08:09:14 -0700385 spec.precision_ = internal::PrecisionHandler().visit(get_arg(s));
Glen Stark72d51e02016-06-08 01:23:32 +0200386 }
387 }
388
Victor Zverovichd4ddaaf2016-07-20 08:09:14 -0700389 using internal::Arg;
Glen Stark72d51e02016-06-08 01:23:32 +0200390 Arg arg = get_arg(s, arg_index);
Victor Zverovichd4ddaaf2016-07-20 08:09:14 -0700391 if (spec.flag(HASH_FLAG) && internal::IsZeroInt().visit(arg))
392 spec.flags_ &= ~internal::to_unsigned<int>(HASH_FLAG);
Glen Stark72d51e02016-06-08 01:23:32 +0200393 if (spec.fill_ == '0') {
394 if (arg.type <= Arg::LAST_NUMERIC_TYPE)
395 spec.align_ = ALIGN_NUMERIC;
396 else
397 spec.fill_ = ' '; // Ignore '0' flag for non-numeric types.
398 }
399
400 // Parse length and convert the argument to the required type.
Victor Zverovichd4ddaaf2016-07-20 08:09:14 -0700401 using internal::ArgConverter;
Glen Stark72d51e02016-06-08 01:23:32 +0200402 switch (*s++) {
403 case 'h':
404 if (*s == 'h')
405 ArgConverter<signed char>(arg, *++s).visit(arg);
406 else
407 ArgConverter<short>(arg, *s).visit(arg);
408 break;
409 case 'l':
410 if (*s == 'l')
411 ArgConverter<fmt::LongLong>(arg, *++s).visit(arg);
412 else
413 ArgConverter<long>(arg, *s).visit(arg);
414 break;
415 case 'j':
416 ArgConverter<intmax_t>(arg, *s).visit(arg);
417 break;
418 case 'z':
419 ArgConverter<std::size_t>(arg, *s).visit(arg);
420 break;
421 case 't':
422 ArgConverter<std::ptrdiff_t>(arg, *s).visit(arg);
423 break;
424 case 'L':
425 // printf produces garbage when 'L' is omitted for long double, no
426 // need to do the same.
427 break;
428 default:
429 --s;
430 ArgConverter<void>(arg, *s).visit(arg);
431 }
432
433 // Parse type.
434 if (!*s)
435 FMT_THROW(FormatError("invalid format string"));
436 spec.type_ = static_cast<char>(*s++);
437 if (arg.type <= Arg::LAST_INTEGER_TYPE) {
438 // Normalize type.
439 switch (spec.type_) {
440 case 'i': case 'u':
441 spec.type_ = 'd';
442 break;
443 case 'c':
444 // TODO: handle wchar_t
Victor Zverovichd4ddaaf2016-07-20 08:09:14 -0700445 internal::CharConverter(arg).visit(arg);
Glen Stark72d51e02016-06-08 01:23:32 +0200446 break;
447 }
448 }
449
450 start = s;
451
452 // Format argument.
Victor Zverovichab054532016-07-20 08:21:13 -0700453 AF(writer_, spec).visit(arg);
Glen Stark72d51e02016-06-08 01:23:32 +0200454 }
Victor Zverovichab054532016-07-20 08:21:13 -0700455 write(writer_, start, s);
Glen Stark72d51e02016-06-08 01:23:32 +0200456}
Glen Stark72d51e02016-06-08 01:23:32 +0200457
458template <typename Char>
459void printf(BasicWriter<Char> &w, BasicCStringRef<Char> format, ArgList args) {
Victor Zverovichab054532016-07-20 08:21:13 -0700460 PrintfFormatter<Char>(args, w).format(format);
Glen Stark72d51e02016-06-08 01:23:32 +0200461}
462
463/**
464 \rst
465 Formats arguments and returns the result as a string.
466
467 **Example**::
468
469 std::string message = fmt::sprintf("The answer is %d", 42);
470 \endrst
471*/
472inline std::string sprintf(CStringRef format, ArgList args) {
473 MemoryWriter w;
474 printf(w, format, args);
475 return w.str();
476}
477FMT_VARIADIC(std::string, sprintf, CStringRef)
478
479inline std::wstring sprintf(WCStringRef format, ArgList args) {
480 WMemoryWriter w;
481 printf(w, format, args);
482 return w.str();
483}
484FMT_VARIADIC_W(std::wstring, sprintf, WCStringRef)
485
486/**
487 \rst
488 Prints formatted data to the file *f*.
489
490 **Example**::
491
492 fmt::fprintf(stderr, "Don't %s!", "panic");
493 \endrst
494 */
495FMT_API int fprintf(std::FILE *f, CStringRef format, ArgList args);
496FMT_VARIADIC(int, fprintf, std::FILE *, CStringRef)
497
498/**
499 \rst
500 Prints formatted data to ``stdout``.
501
502 **Example**::
503
504 fmt::printf("Elapsed time: %.2f seconds", 1.23);
505 \endrst
506 */
507inline int printf(CStringRef format, ArgList args) {
508 return fprintf(stdout, format, args);
509}
510FMT_VARIADIC(int, printf, CStringRef)
511} // namespace fmt
512
513#endif // FMT_PRINTF_H_