1// Formatting library for C++ - legacy printf implementation
2//
3// Copyright (c) 2012 - 2016, Victor Zverovich
4// All rights reserved.
5//
6// For the license information refer to format.h.
7
8#ifndef FMT_PRINTF_H_
9#define FMT_PRINTF_H_
10
11#ifndef FMT_MODULE
12# include <algorithm> // std::max
13# include <limits> // std::numeric_limits
14#endif
15
16#include "format.h"
17
18FMT_BEGIN_NAMESPACE
19FMT_BEGIN_EXPORT
20
21template <typename T> struct printf_formatter {
22 printf_formatter() = delete;
23};
24
25template <typename Char> class basic_printf_context {
26 private:
27 basic_appender<Char> out_;
28 basic_format_args<basic_printf_context> args_;
29
30 static_assert(std::is_same<Char, char>::value ||
31 std::is_same<Char, wchar_t>::value,
32 "Unsupported code unit type.");
33
34 public:
35 using char_type = Char;
36 using parse_context_type = parse_context<Char>;
37 template <typename T> using formatter_type = printf_formatter<T>;
38 enum { builtin_types = 1 };
39
40 /// Constructs a `printf_context` object. References to the arguments are
41 /// stored in the context object so make sure they have appropriate lifetimes.
42 basic_printf_context(basic_appender<Char> out,
43 basic_format_args<basic_printf_context> args)
44 : out_(out), args_(args) {}
45
46 auto out() -> basic_appender<Char> { return out_; }
47 void advance_to(basic_appender<Char>) {}
48
49 auto locale() -> detail::locale_ref { return {}; }
50
51 auto arg(int id) const -> basic_format_arg<basic_printf_context> {
52 return args_.get(id);
53 }
54};
55
56namespace detail {
57
58// Return the result via the out param to workaround gcc bug 77539.
59template <bool IS_CONSTEXPR, typename T, typename Ptr = const T*>
60FMT_CONSTEXPR auto find(Ptr first, Ptr last, T value, Ptr& out) -> bool {
61 for (out = first; out != last; ++out) {
62 if (*out == value) return true;
63 }
64 return false;
65}
66
67template <>
68inline auto find<false, char>(const char* first, const char* last, char value,
69 const char*& out) -> bool {
70 out =
71 static_cast<const char*>(memchr(s: first, c: value, n: to_unsigned(value: last - first)));
72 return out != nullptr;
73}
74
75// Checks if a value fits in int - used to avoid warnings about comparing
76// signed and unsigned integers.
77template <bool IsSigned> struct int_checker {
78 template <typename T> static auto fits_in_int(T value) -> bool {
79 unsigned max = to_unsigned(value: max_value<int>());
80 return value <= max;
81 }
82 inline static auto fits_in_int(bool) -> bool { return true; }
83};
84
85template <> struct int_checker<true> {
86 template <typename T> static auto fits_in_int(T value) -> bool {
87 return value >= (std::numeric_limits<int>::min)() &&
88 value <= max_value<int>();
89 }
90 inline static auto fits_in_int(int) -> bool { return true; }
91};
92
93struct printf_precision_handler {
94 template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
95 auto operator()(T value) -> int {
96 if (!int_checker<std::numeric_limits<T>::is_signed>::fits_in_int(value))
97 report_error(message: "number is too big");
98 return (std::max)(a: static_cast<int>(value), b: 0);
99 }
100
101 template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
102 auto operator()(T) -> int {
103 report_error(message: "precision is not integer");
104 return 0;
105 }
106};
107
108// An argument visitor that returns true iff arg is a zero integer.
109struct is_zero_int {
110 template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
111 auto operator()(T value) -> bool {
112 return value == 0;
113 }
114
115 template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
116 auto operator()(T) -> bool {
117 return false;
118 }
119};
120
121template <typename T> struct make_unsigned_or_bool : std::make_unsigned<T> {};
122
123template <> struct make_unsigned_or_bool<bool> {
124 using type = bool;
125};
126
127template <typename T, typename Context> class arg_converter {
128 private:
129 using char_type = typename Context::char_type;
130
131 basic_format_arg<Context>& arg_;
132 char_type type_;
133
134 public:
135 arg_converter(basic_format_arg<Context>& arg, char_type type)
136 : arg_(arg), type_(type) {}
137
138 void operator()(bool value) {
139 if (type_ != 's') operator()<bool>(value);
140 }
141
142 template <typename U, FMT_ENABLE_IF(std::is_integral<U>::value)>
143 void operator()(U value) {
144 bool is_signed = type_ == 'd' || type_ == 'i';
145 using target_type = conditional_t<std::is_same<T, void>::value, U, T>;
146 if (const_check(val: sizeof(target_type) <= sizeof(int))) {
147 // Extra casts are used to silence warnings.
148 using unsigned_type = typename make_unsigned_or_bool<target_type>::type;
149 if (is_signed)
150 arg_ = static_cast<int>(static_cast<target_type>(value));
151 else
152 arg_ = static_cast<unsigned>(static_cast<unsigned_type>(value));
153 } else {
154 // glibc's printf doesn't sign extend arguments of smaller types:
155 // std::printf("%lld", -42); // prints "4294967254"
156 // but we don't have to do the same because it's a UB.
157 if (is_signed)
158 arg_ = static_cast<long long>(value);
159 else
160 arg_ = static_cast<typename make_unsigned_or_bool<U>::type>(value);
161 }
162 }
163
164 template <typename U, FMT_ENABLE_IF(!std::is_integral<U>::value)>
165 void operator()(U) {} // No conversion needed for non-integral types.
166};
167
168// Converts an integer argument to T for printf, if T is an integral type.
169// If T is void, the argument is converted to corresponding signed or unsigned
170// type depending on the type specifier: 'd' and 'i' - signed, other -
171// unsigned).
172template <typename T, typename Context, typename Char>
173void convert_arg(basic_format_arg<Context>& arg, Char type) {
174 arg.visit(arg_converter<T, Context>(arg, type));
175}
176
177// Converts an integer argument to char for printf.
178template <typename Context> class char_converter {
179 private:
180 basic_format_arg<Context>& arg_;
181
182 public:
183 explicit char_converter(basic_format_arg<Context>& arg) : arg_(arg) {}
184
185 template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
186 void operator()(T value) {
187 arg_ = static_cast<typename Context::char_type>(value);
188 }
189
190 template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
191 void operator()(T) {} // No conversion needed for non-integral types.
192};
193
194// An argument visitor that return a pointer to a C string if argument is a
195// string or null otherwise.
196template <typename Char> struct get_cstring {
197 template <typename T> auto operator()(T) -> const Char* { return nullptr; }
198 auto operator()(const Char* s) -> const Char* { return s; }
199};
200
201// Checks if an argument is a valid printf width specifier and sets
202// left alignment if it is negative.
203class printf_width_handler {
204 private:
205 format_specs& specs_;
206
207 public:
208 inline explicit printf_width_handler(format_specs& specs) : specs_(specs) {}
209
210 template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
211 auto operator()(T value) -> unsigned {
212 auto width = static_cast<uint32_or_64_or_128_t<T>>(value);
213 if (detail::is_negative(value)) {
214 specs_.set_align(align::left);
215 width = 0 - width;
216 }
217 unsigned int_max = to_unsigned(value: max_value<int>());
218 if (width > int_max) report_error(message: "number is too big");
219 return static_cast<unsigned>(width);
220 }
221
222 template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
223 auto operator()(T) -> unsigned {
224 report_error(message: "width is not integer");
225 return 0;
226 }
227};
228
229// Workaround for a bug with the XL compiler when initializing
230// printf_arg_formatter's base class.
231template <typename Char>
232auto make_arg_formatter(basic_appender<Char> iter, format_specs& s)
233 -> arg_formatter<Char> {
234 return {iter, s, locale_ref()};
235}
236
237// The `printf` argument formatter.
238template <typename Char>
239class printf_arg_formatter : public arg_formatter<Char> {
240 private:
241 using base = arg_formatter<Char>;
242 using context_type = basic_printf_context<Char>;
243
244 context_type& context_;
245
246 void write_null_pointer(bool is_string = false) {
247 auto s = this->specs;
248 s.set_type(presentation_type::none);
249 write_bytes<Char>(this->out, is_string ? "(null)" : "(nil)", s);
250 }
251
252 template <typename T> void write(T value) {
253 detail::write<Char>(this->out, value, this->specs, this->locale);
254 }
255
256 public:
257 printf_arg_formatter(basic_appender<Char> iter, format_specs& s,
258 context_type& ctx)
259 : base(make_arg_formatter(iter, s)), context_(ctx) {}
260
261 void operator()(monostate value) { write(value); }
262
263 template <typename T, FMT_ENABLE_IF(detail::is_integral<T>::value)>
264 void operator()(T value) {
265 // MSVC2013 fails to compile separate overloads for bool and Char so use
266 // std::is_same instead.
267 if (!std::is_same<T, Char>::value) {
268 write(value);
269 return;
270 }
271 format_specs s = this->specs;
272 if (s.type() != presentation_type::none &&
273 s.type() != presentation_type::chr) {
274 return (*this)(static_cast<int>(value));
275 }
276 s.set_sign(sign::none);
277 s.clear_alt();
278 s.set_fill(' '); // Ignore '0' flag for char types.
279 // align::numeric needs to be overwritten here since the '0' flag is
280 // ignored for non-numeric types
281 if (s.align() == align::none || s.align() == align::numeric)
282 s.set_align(align::right);
283 detail::write<Char>(this->out, static_cast<Char>(value), s);
284 }
285
286 template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
287 void operator()(T value) {
288 write(value);
289 }
290
291 void operator()(const char* value) {
292 if (value)
293 write(value);
294 else
295 write_null_pointer(is_string: this->specs.type() != presentation_type::pointer);
296 }
297
298 void operator()(const wchar_t* value) {
299 if (value)
300 write(value);
301 else
302 write_null_pointer(is_string: this->specs.type() != presentation_type::pointer);
303 }
304
305 void operator()(basic_string_view<Char> value) { write(value); }
306
307 void operator()(const void* value) {
308 if (value)
309 write(value);
310 else
311 write_null_pointer();
312 }
313
314 void operator()(typename basic_format_arg<context_type>::handle handle) {
315 auto parse_ctx = parse_context<Char>({});
316 handle.format(parse_ctx, context_);
317 }
318};
319
320template <typename Char>
321void parse_flags(format_specs& specs, const Char*& it, const Char* end) {
322 for (; it != end; ++it) {
323 switch (*it) {
324 case '-': specs.set_align(align::left); break;
325 case '+': specs.set_sign(sign::plus); break;
326 case '0': specs.set_fill('0'); break;
327 case ' ':
328 if (specs.sign() != sign::plus) specs.set_sign(sign::space);
329 break;
330 case '#': specs.set_alt(); break;
331 default: return;
332 }
333 }
334}
335
336template <typename Char, typename GetArg>
337auto parse_header(const Char*& it, const Char* end, format_specs& specs,
338 GetArg get_arg) -> int {
339 int arg_index = -1;
340 Char c = *it;
341 if (c >= '0' && c <= '9') {
342 // Parse an argument index (if followed by '$') or a width possibly
343 // preceded with '0' flag(s).
344 int value = parse_nonnegative_int(it, end, -1);
345 if (it != end && *it == '$') { // value is an argument index
346 ++it;
347 arg_index = value != -1 ? value : max_value<int>();
348 } else {
349 if (c == '0') specs.set_fill('0');
350 if (value != 0) {
351 // Nonzero value means that we parsed width and don't need to
352 // parse it or flags again, so return now.
353 if (value == -1) report_error(message: "number is too big");
354 specs.width = value;
355 return arg_index;
356 }
357 }
358 }
359 parse_flags(specs, it, end);
360 // Parse width.
361 if (it != end) {
362 if (*it >= '0' && *it <= '9') {
363 specs.width = parse_nonnegative_int(it, end, -1);
364 if (specs.width == -1) report_error(message: "number is too big");
365 } else if (*it == '*') {
366 ++it;
367 specs.width = static_cast<int>(
368 get_arg(-1).visit(detail::printf_width_handler(specs)));
369 }
370 }
371 return arg_index;
372}
373
374inline auto parse_printf_presentation_type(char c, type t, bool& upper)
375 -> presentation_type {
376 using pt = presentation_type;
377 constexpr auto integral_set = sint_set | uint_set | bool_set | char_set;
378 switch (c) {
379 case 'd': return in(t, set: integral_set) ? pt::dec : pt::none;
380 case 'o': return in(t, set: integral_set) ? pt::oct : pt::none;
381 case 'X': upper = true; FMT_FALLTHROUGH;
382 case 'x': return in(t, set: integral_set) ? pt::hex : pt::none;
383 case 'E': upper = true; FMT_FALLTHROUGH;
384 case 'e': return in(t, set: float_set) ? pt::exp : pt::none;
385 case 'F': upper = true; FMT_FALLTHROUGH;
386 case 'f': return in(t, set: float_set) ? pt::fixed : pt::none;
387 case 'G': upper = true; FMT_FALLTHROUGH;
388 case 'g': return in(t, set: float_set) ? pt::general : pt::none;
389 case 'A': upper = true; FMT_FALLTHROUGH;
390 case 'a': return in(t, set: float_set) ? pt::hexfloat : pt::none;
391 case 'c': return in(t, set: integral_set) ? pt::chr : pt::none;
392 case 's': return in(t, set: string_set | cstring_set) ? pt::string : pt::none;
393 case 'p': return in(t, set: pointer_set | cstring_set) ? pt::pointer : pt::none;
394 default: return pt::none;
395 }
396}
397
398template <typename Char, typename Context>
399void vprintf(buffer<Char>& buf, basic_string_view<Char> format,
400 basic_format_args<Context> args) {
401 using iterator = basic_appender<Char>;
402 auto out = iterator(buf);
403 auto context = basic_printf_context<Char>(out, args);
404 auto parse_ctx = parse_context<Char>(format);
405
406 // Returns the argument with specified index or, if arg_index is -1, the next
407 // argument.
408 auto get_arg = [&](int arg_index) {
409 if (arg_index < 0)
410 arg_index = parse_ctx.next_arg_id();
411 else
412 parse_ctx.check_arg_id(--arg_index);
413 return detail::get_arg(context, arg_index);
414 };
415
416 const Char* start = parse_ctx.begin();
417 const Char* end = parse_ctx.end();
418 auto it = start;
419 while (it != end) {
420 if (!find<false, Char>(it, end, '%', it)) {
421 it = end; // find leaves it == nullptr if it doesn't find '%'.
422 break;
423 }
424 Char c = *it++;
425 if (it != end && *it == c) {
426 write(out, basic_string_view<Char>(start, to_unsigned(it - start)));
427 start = ++it;
428 continue;
429 }
430 write(out, basic_string_view<Char>(start, to_unsigned(it - 1 - start)));
431
432 auto specs = format_specs();
433 specs.set_align(align::right);
434
435 // Parse argument index, flags and width.
436 int arg_index = parse_header(it, end, specs, get_arg);
437 if (arg_index == 0) report_error(message: "argument not found");
438
439 // Parse precision.
440 if (it != end && *it == '.') {
441 ++it;
442 c = it != end ? *it : 0;
443 if ('0' <= c && c <= '9') {
444 specs.precision = parse_nonnegative_int(it, end, 0);
445 } else if (c == '*') {
446 ++it;
447 specs.precision =
448 static_cast<int>(get_arg(-1).visit(printf_precision_handler()));
449 } else {
450 specs.precision = 0;
451 }
452 }
453
454 auto arg = get_arg(arg_index);
455 // For d, i, o, u, x, and X conversion specifiers, if a precision is
456 // specified, the '0' flag is ignored
457 if (specs.precision >= 0 && is_integral_type(arg.type())) {
458 // Ignore '0' for non-numeric types or if '-' present.
459 specs.set_fill(' ');
460 }
461 if (specs.precision >= 0 && arg.type() == type::cstring_type) {
462 auto str = arg.visit(get_cstring<Char>());
463 auto str_end = str + specs.precision;
464 auto nul = std::find(str, str_end, Char());
465 auto sv = basic_string_view<Char>(
466 str, to_unsigned(nul != str_end ? nul - str : specs.precision));
467 arg = sv;
468 }
469 if (specs.alt() && arg.visit(is_zero_int())) specs.clear_alt();
470 if (specs.fill_unit<Char>() == '0') {
471 if (is_arithmetic_type(arg.type()) && specs.align() != align::left) {
472 specs.set_align(align::numeric);
473 } else {
474 // Ignore '0' flag for non-numeric types or if '-' flag is also present.
475 specs.set_fill(' ');
476 }
477 }
478
479 // Parse length and convert the argument to the required type.
480 c = it != end ? *it++ : 0;
481 Char t = it != end ? *it : 0;
482 switch (c) {
483 case 'h':
484 if (t == 'h') {
485 ++it;
486 t = it != end ? *it : 0;
487 convert_arg<signed char>(arg, t);
488 } else {
489 convert_arg<short>(arg, t);
490 }
491 break;
492 case 'l':
493 if (t == 'l') {
494 ++it;
495 t = it != end ? *it : 0;
496 convert_arg<long long>(arg, t);
497 } else {
498 convert_arg<long>(arg, t);
499 }
500 break;
501 case 'j': convert_arg<intmax_t>(arg, t); break;
502 case 'z': convert_arg<size_t>(arg, t); break;
503 case 't': convert_arg<std::ptrdiff_t>(arg, t); break;
504 case 'L':
505 // printf produces garbage when 'L' is omitted for long double, no
506 // need to do the same.
507 break;
508 default: --it; convert_arg<void>(arg, c);
509 }
510
511 // Parse type.
512 if (it == end) report_error(message: "invalid format string");
513 char type = static_cast<char>(*it++);
514 if (is_integral_type(arg.type())) {
515 // Normalize type.
516 switch (type) {
517 case 'i':
518 case 'u': type = 'd'; break;
519 case 'c':
520 arg.visit(char_converter<basic_printf_context<Char>>(arg));
521 break;
522 }
523 }
524 bool upper = false;
525 specs.set_type(parse_printf_presentation_type(type, arg.type(), upper));
526 if (specs.type() == presentation_type::none)
527 report_error(message: "invalid format specifier");
528 if (upper) specs.set_upper();
529
530 start = it;
531
532 // Format argument.
533 arg.visit(printf_arg_formatter<Char>(out, specs, context));
534 }
535 write(out, basic_string_view<Char>(start, to_unsigned(it - start)));
536}
537} // namespace detail
538
539using printf_context = basic_printf_context<char>;
540using wprintf_context = basic_printf_context<wchar_t>;
541
542using printf_args = basic_format_args<printf_context>;
543using wprintf_args = basic_format_args<wprintf_context>;
544
545/// Constructs an `format_arg_store` object that contains references to
546/// arguments and can be implicitly converted to `printf_args`.
547template <typename Char = char, typename... T>
548inline auto make_printf_args(T&... args)
549 -> decltype(fmt::make_format_args<basic_printf_context<Char>>(args...)) {
550 return fmt::make_format_args<basic_printf_context<Char>>(args...);
551}
552
553template <typename Char> struct vprintf_args {
554 using type = basic_format_args<basic_printf_context<Char>>;
555};
556
557template <typename Char>
558inline auto vsprintf(basic_string_view<Char> fmt,
559 typename vprintf_args<Char>::type args)
560 -> std::basic_string<Char> {
561 auto buf = basic_memory_buffer<Char>();
562 detail::vprintf(buf, fmt, args);
563 return {buf.data(), buf.size()};
564}
565
566/**
567 * Formats `args` according to specifications in `fmt` and returns the result
568 * as as string.
569 *
570 * **Example**:
571 *
572 * std::string message = fmt::sprintf("The answer is %d", 42);
573 */
574template <typename S, typename... T, typename Char = detail::char_t<S>>
575inline auto sprintf(const S& fmt, const T&... args) -> std::basic_string<Char> {
576 return vsprintf(detail::to_string_view(fmt),
577 fmt::make_format_args<basic_printf_context<Char>>(args...));
578}
579
580template <typename Char>
581inline auto vfprintf(std::FILE* f, basic_string_view<Char> fmt,
582 typename vprintf_args<Char>::type args) -> int {
583 auto buf = basic_memory_buffer<Char>();
584 detail::vprintf(buf, fmt, args);
585 size_t size = buf.size();
586 return std::fwrite(ptr: buf.data(), size: sizeof(Char), n: size, s: f) < size
587 ? -1
588 : static_cast<int>(size);
589}
590
591/**
592 * Formats `args` according to specifications in `fmt` and writes the output
593 * to `f`.
594 *
595 * **Example**:
596 *
597 * fmt::fprintf(stderr, "Don't %s!", "panic");
598 */
599template <typename S, typename... T, typename Char = detail::char_t<S>>
600inline auto fprintf(std::FILE* f, const S& fmt, const T&... args) -> int {
601 return vfprintf(f, detail::to_string_view(fmt),
602 make_printf_args<Char>(args...));
603}
604
605template <typename Char>
606FMT_DEPRECATED inline auto vprintf(basic_string_view<Char> fmt,
607 typename vprintf_args<Char>::type args)
608 -> int {
609 return vfprintf(stdout, fmt, args);
610}
611
612/**
613 * Formats `args` according to specifications in `fmt` and writes the output
614 * to `stdout`.
615 *
616 * **Example**:
617 *
618 * fmt::printf("Elapsed time: %.2f seconds", 1.23);
619 */
620template <typename... T>
621inline auto printf(string_view fmt, const T&... args) -> int {
622 return vfprintf(stdout, fmt, make_printf_args(args...));
623}
624template <typename... T>
625FMT_DEPRECATED inline auto printf(basic_string_view<wchar_t> fmt,
626 const T&... args) -> int {
627 return vfprintf(stdout, fmt, make_printf_args<wchar_t>(args...));
628}
629
630FMT_END_EXPORT
631FMT_END_NAMESPACE
632
633#endif // FMT_PRINTF_H_
634