Debian Codegraph @

podofo/3rdparty/fmtlib/fmt/printf.h

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