Roboruka
Knihovna pro obsluhu RoboRuky.
printf.h
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#include <algorithm> // std::max
12#include <limits> // std::numeric_limits
13
14#include "ostream.h"
15
16FMT_BEGIN_NAMESPACE
17namespace internal {
18
19// Checks if a value fits in int - used to avoid warnings about comparing
20// signed and unsigned integers.
21template <bool IsSigned> struct int_checker {
22 template <typename T> static bool fits_in_int(T value) {
23 unsigned max = max_value<int>();
24 return value <= max;
25 }
26 static bool fits_in_int(bool) { return true; }
27};
28
29template <> struct int_checker<true> {
30 template <typename T> static bool fits_in_int(T value) {
31 return value >= (std::numeric_limits<int>::min)() &&
32 value <= max_value<int>();
33 }
34 static bool fits_in_int(int) { return true; }
35};
36
37class printf_precision_handler {
38 public:
39 template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
40 int operator()(T value) {
41 if (!int_checker<std::numeric_limits<T>::is_signed>::fits_in_int(value))
42 FMT_THROW(format_error("number is too big"));
43 return (std::max)(static_cast<int>(value), 0);
44 }
45
46 template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
47 int operator()(T) {
48 FMT_THROW(format_error("precision is not integer"));
49 return 0;
50 }
51};
52
53// An argument visitor that returns true iff arg is a zero integer.
54class is_zero_int {
55 public:
56 template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
57 bool operator()(T value) {
58 return value == 0;
59 }
60
61 template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
62 bool operator()(T) {
63 return false;
64 }
65};
66
67template <typename T> struct make_unsigned_or_bool : std::make_unsigned<T> {};
68
69template <> struct make_unsigned_or_bool<bool> { using type = bool; };
70
71template <typename T, typename Context> class arg_converter {
72 private:
73 using char_type = typename Context::char_type;
74
75 basic_format_arg<Context>& arg_;
76 char_type type_;
77
78 public:
79 arg_converter(basic_format_arg<Context>& arg, char_type type)
80 : arg_(arg), type_(type) {}
81
82 void operator()(bool value) {
83 if (type_ != 's') operator()<bool>(value);
84 }
85
86 template <typename U, FMT_ENABLE_IF(std::is_integral<U>::value)>
87 void operator()(U value) {
88 bool is_signed = type_ == 'd' || type_ == 'i';
89 using target_type = conditional_t<std::is_same<T, void>::value, U, T>;
90 if (const_check(sizeof(target_type) <= sizeof(int))) {
91 // Extra casts are used to silence warnings.
92 if (is_signed) {
93 arg_ = internal::make_arg<Context>(
94 static_cast<int>(static_cast<target_type>(value)));
95 } else {
96 using unsigned_type = typename make_unsigned_or_bool<target_type>::type;
97 arg_ = internal::make_arg<Context>(
98 static_cast<unsigned>(static_cast<unsigned_type>(value)));
99 }
100 } else {
101 if (is_signed) {
102 // glibc's printf doesn't sign extend arguments of smaller types:
103 // std::printf("%lld", -42); // prints "4294967254"
104 // but we don't have to do the same because it's a UB.
105 arg_ = internal::make_arg<Context>(static_cast<long long>(value));
106 } else {
107 arg_ = internal::make_arg<Context>(
108 static_cast<typename make_unsigned_or_bool<U>::type>(value));
109 }
110 }
111 }
112
113 template <typename U, FMT_ENABLE_IF(!std::is_integral<U>::value)>
114 void operator()(U) {} // No conversion needed for non-integral types.
115};
116
117// Converts an integer argument to T for printf, if T is an integral type.
118// If T is void, the argument is converted to corresponding signed or unsigned
119// type depending on the type specifier: 'd' and 'i' - signed, other -
120// unsigned).
121template <typename T, typename Context, typename Char>
122void convert_arg(basic_format_arg<Context>& arg, Char type) {
123 visit_format_arg(arg_converter<T, Context>(arg, type), arg);
124}
125
126// Converts an integer argument to char for printf.
127template <typename Context> class char_converter {
128 private:
129 basic_format_arg<Context>& arg_;
130
131 public:
132 explicit char_converter(basic_format_arg<Context>& arg) : arg_(arg) {}
133
134 template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
135 void operator()(T value) {
136 arg_ = internal::make_arg<Context>(
137 static_cast<typename Context::char_type>(value));
138 }
139
140 template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
141 void operator()(T) {} // No conversion needed for non-integral types.
142};
143
144// Checks if an argument is a valid printf width specifier and sets
145// left alignment if it is negative.
146template <typename Char> class printf_width_handler {
147 private:
148 using format_specs = basic_format_specs<Char>;
149
150 format_specs& specs_;
151
152 public:
153 explicit printf_width_handler(format_specs& specs) : specs_(specs) {}
154
155 template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
156 unsigned operator()(T value) {
157 auto width = static_cast<uint32_or_64_or_128_t<T>>(value);
158 if (internal::is_negative(value)) {
159 specs_.align = align::left;
160 width = 0 - width;
161 }
162 unsigned int_max = max_value<int>();
163 if (width > int_max) FMT_THROW(format_error("number is too big"));
164 return static_cast<unsigned>(width);
165 }
166
167 template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
168 unsigned operator()(T) {
169 FMT_THROW(format_error("width is not integer"));
170 return 0;
171 }
172};
173
174template <typename Char, typename Context>
175void printf(buffer<Char>& buf, basic_string_view<Char> format,
177 Context(std::back_inserter(buf), format, args).format();
178}
179
180template <typename OutputIt, typename Char, typename Context>
181internal::truncating_iterator<OutputIt> printf(
182 internal::truncating_iterator<OutputIt> it, basic_string_view<Char> format,
184 return Context(it, format, args).format();
185}
186} // namespace internal
187
188using internal::printf; // For printing into memory_buffer.
189
190template <typename Range> class printf_arg_formatter;
191
192template <typename Char>
193class basic_printf_parse_context : public basic_format_parse_context<Char> {
195};
196template <typename OutputIt, typename Char> class basic_printf_context;
197
203template <typename Range>
204class printf_arg_formatter : public internal::arg_formatter_base<Range> {
205 public:
206 using iterator = typename Range::iterator;
207
208 private:
209 using char_type = typename Range::value_type;
210 using base = internal::arg_formatter_base<Range>;
212
213 context_type& context_;
214
215 void write_null_pointer(char) {
216 this->specs()->type = 0;
217 this->write("(nil)");
218 }
219
220 void write_null_pointer(wchar_t) {
221 this->specs()->type = 0;
222 this->write(L"(nil)");
223 }
224
225 public:
226 using format_specs = typename base::format_specs;
227
235 printf_arg_formatter(iterator iter, format_specs& specs, context_type& ctx)
236 : base(Range(iter), &specs, internal::locale_ref()), context_(ctx) {}
237
238 template <typename T, FMT_ENABLE_IF(fmt::internal::is_integral<T>::value)>
239 iterator operator()(T value) {
240 // MSVC2013 fails to compile separate overloads for bool and char_type so
241 // use std::is_same instead.
242 if (std::is_same<T, bool>::value) {
243 format_specs& fmt_specs = *this->specs();
244 if (fmt_specs.type != 's') return base::operator()(value ? 1 : 0);
245 fmt_specs.type = 0;
246 this->write(value != 0);
247 } else if (std::is_same<T, char_type>::value) {
248 format_specs& fmt_specs = *this->specs();
249 if (fmt_specs.type && fmt_specs.type != 'c')
250 return (*this)(static_cast<int>(value));
251 fmt_specs.sign = sign::none;
252 fmt_specs.alt = false;
253 fmt_specs.align = align::right;
254 return base::operator()(value);
255 } else {
256 return base::operator()(value);
257 }
258 return this->out();
259 }
260
261 template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
262 iterator operator()(T value) {
263 return base::operator()(value);
264 }
265
267 iterator operator()(const char* value) {
268 if (value)
269 base::operator()(value);
270 else if (this->specs()->type == 'p')
271 write_null_pointer(char_type());
272 else
273 this->write("(null)");
274 return this->out();
275 }
276
278 iterator operator()(const wchar_t* value) {
279 if (value)
280 base::operator()(value);
281 else if (this->specs()->type == 'p')
282 write_null_pointer(char_type());
283 else
284 this->write(L"(null)");
285 return this->out();
286 }
287
288 iterator operator()(basic_string_view<char_type> value) {
289 return base::operator()(value);
290 }
291
292 iterator operator()(monostate value) { return base::operator()(value); }
293
295 iterator operator()(const void* value) {
296 if (value) return base::operator()(value);
297 this->specs()->type = 0;
298 write_null_pointer(char_type());
299 return this->out();
300 }
301
303 iterator operator()(typename basic_format_arg<context_type>::handle handle) {
304 handle.format(context_.parse_context(), context_);
305 return this->out();
306 }
307};
308
309template <typename T> struct printf_formatter {
310 printf_formatter() = delete;
311
312 template <typename ParseContext>
313 auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
314 return ctx.begin();
315 }
316
317 template <typename FormatContext>
318 auto format(const T& value, FormatContext& ctx) -> decltype(ctx.out()) {
319 internal::format_value(internal::get_container(ctx.out()), value);
320 return ctx.out();
321 }
322};
323
325template <typename OutputIt, typename Char> class basic_printf_context {
326 public:
328 using char_type = Char;
329 using iterator = OutputIt;
330 using format_arg = basic_format_arg<basic_printf_context>;
331 using parse_context_type = basic_printf_parse_context<Char>;
332 template <typename T> using formatter_type = printf_formatter<T>;
333
334 private:
335 using format_specs = basic_format_specs<char_type>;
336
337 OutputIt out_;
339 parse_context_type parse_ctx_;
340
341 static void parse_flags(format_specs& specs, const Char*& it,
342 const Char* end);
343
344 // Returns the argument with specified index or, if arg_index is -1, the next
345 // argument.
346 format_arg get_arg(int arg_index = -1);
347
348 // Parses argument index, flags and width and returns the argument index.
349 int parse_header(const Char*& it, const Char* end, format_specs& specs);
350
351 public:
361 : out_(out), args_(args), parse_ctx_(format_str) {}
362
363 OutputIt out() { return out_; }
364 void advance_to(OutputIt it) { out_ = it; }
365
366 internal::locale_ref locale() { return {}; }
367
368 format_arg arg(int id) const { return args_.get(id); }
369
370 parse_context_type& parse_context() { return parse_ctx_; }
371
372 FMT_CONSTEXPR void on_error(const char* message) {
373 parse_ctx_.on_error(message);
374 }
375
377 template <typename ArgFormatter = printf_arg_formatter<buffer_range<Char>>>
378 OutputIt format();
379};
380
381template <typename OutputIt, typename Char>
383 const Char*& it,
384 const Char* end) {
385 for (; it != end; ++it) {
386 switch (*it) {
387 case '-':
388 specs.align = align::left;
389 break;
390 case '+':
391 specs.sign = sign::plus;
392 break;
393 case '0':
394 specs.fill[0] = '0';
395 break;
396 case ' ':
397 specs.sign = sign::space;
398 break;
399 case '#':
400 specs.alt = true;
401 break;
402 default:
403 return;
404 }
405 }
406}
407
408template <typename OutputIt, typename Char>
409typename basic_printf_context<OutputIt, Char>::format_arg
411 if (arg_index < 0)
412 arg_index = parse_ctx_.next_arg_id();
413 else
414 parse_ctx_.check_arg_id(--arg_index);
415 return internal::get_arg(*this, arg_index);
416}
417
418template <typename OutputIt, typename Char>
420 const Char* end,
421 format_specs& specs) {
422 int arg_index = -1;
423 char_type c = *it;
424 if (c >= '0' && c <= '9') {
425 // Parse an argument index (if followed by '$') or a width possibly
426 // preceded with '0' flag(s).
427 internal::error_handler eh;
428 int value = parse_nonnegative_int(it, end, eh);
429 if (it != end && *it == '$') { // value is an argument index
430 ++it;
431 arg_index = value;
432 } else {
433 if (c == '0') specs.fill[0] = '0';
434 if (value != 0) {
435 // Nonzero value means that we parsed width and don't need to
436 // parse it or flags again, so return now.
437 specs.width = value;
438 return arg_index;
439 }
440 }
441 }
442 parse_flags(specs, it, end);
443 // Parse width.
444 if (it != end) {
445 if (*it >= '0' && *it <= '9') {
446 internal::error_handler eh;
447 specs.width = parse_nonnegative_int(it, end, eh);
448 } else if (*it == '*') {
449 ++it;
450 specs.width = static_cast<int>(visit_format_arg(
451 internal::printf_width_handler<char_type>(specs), get_arg()));
452 }
453 }
454 return arg_index;
455}
456
457template <typename OutputIt, typename Char>
458template <typename ArgFormatter>
460 auto out = this->out();
461 const Char* start = parse_ctx_.begin();
462 const Char* end = parse_ctx_.end();
463 auto it = start;
464 while (it != end) {
465 char_type c = *it++;
466 if (c != '%') continue;
467 if (it != end && *it == c) {
468 out = std::copy(start, it, out);
469 start = ++it;
470 continue;
471 }
472 out = std::copy(start, it - 1, out);
473
474 format_specs specs;
475 specs.align = align::right;
476
477 // Parse argument index, flags and width.
478 int arg_index = parse_header(it, end, specs);
479 if (arg_index == 0) on_error("argument index out of range");
480
481 // Parse precision.
482 if (it != end && *it == '.') {
483 ++it;
484 c = it != end ? *it : 0;
485 if ('0' <= c && c <= '9') {
486 internal::error_handler eh;
487 specs.precision = parse_nonnegative_int(it, end, eh);
488 } else if (c == '*') {
489 ++it;
490 specs.precision = static_cast<int>(
491 visit_format_arg(internal::printf_precision_handler(), get_arg()));
492 } else {
493 specs.precision = 0;
494 }
495 }
496
497 format_arg arg = get_arg(arg_index);
498 if (specs.alt && visit_format_arg(internal::is_zero_int(), arg))
499 specs.alt = false;
500 if (specs.fill[0] == '0') {
501 if (arg.is_arithmetic())
502 specs.align = align::numeric;
503 else
504 specs.fill[0] = ' '; // Ignore '0' flag for non-numeric types.
505 }
506
507 // Parse length and convert the argument to the required type.
508 c = it != end ? *it++ : 0;
509 char_type t = it != end ? *it : 0;
510 using internal::convert_arg;
511 switch (c) {
512 case 'h':
513 if (t == 'h') {
514 ++it;
515 t = it != end ? *it : 0;
516 convert_arg<signed char>(arg, t);
517 } else {
518 convert_arg<short>(arg, t);
519 }
520 break;
521 case 'l':
522 if (t == 'l') {
523 ++it;
524 t = it != end ? *it : 0;
525 convert_arg<long long>(arg, t);
526 } else {
527 convert_arg<long>(arg, t);
528 }
529 break;
530 case 'j':
531 convert_arg<intmax_t>(arg, t);
532 break;
533 case 'z':
534 convert_arg<std::size_t>(arg, t);
535 break;
536 case 't':
537 convert_arg<std::ptrdiff_t>(arg, t);
538 break;
539 case 'L':
540 // printf produces garbage when 'L' is omitted for long double, no
541 // need to do the same.
542 break;
543 default:
544 --it;
545 convert_arg<void>(arg, c);
546 }
547
548 // Parse type.
549 if (it == end) FMT_THROW(format_error("invalid format string"));
550 specs.type = static_cast<char>(*it++);
551 if (arg.is_integral()) {
552 // Normalize type.
553 switch (specs.type) {
554 case 'i':
555 case 'u':
556 specs.type = 'd';
557 break;
558 case 'c':
559 visit_format_arg(internal::char_converter<basic_printf_context>(arg),
560 arg);
561 break;
562 }
563 }
564
565 start = it;
566
567 // Format argument.
568 visit_format_arg(ArgFormatter(out, specs, *this), arg);
569 }
570 return std::copy(start, it, out);
571}
572
573template <typename Char>
576 Char>;
577
580
583
590template <typename... Args>
591inline format_arg_store<printf_context, Args...> make_printf_args(
592 const Args&... args) {
593 return {args...};
594}
595
602template <typename... Args>
603inline format_arg_store<wprintf_context, Args...> make_wprintf_args(
604 const Args&... args) {
605 return {args...};
606}
607
608template <typename S, typename Char = char_t<S>>
609inline std::basic_string<Char> vsprintf(
610 const S& format,
611 basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args) {
613 printf(buffer, to_string_view(format), args);
614 return to_string(buffer);
615}
616
626template <typename S, typename... Args,
627 typename Char = enable_if_t<internal::is_string<S>::value, char_t<S>>>
628inline std::basic_string<Char> sprintf(const S& format, const Args&... args) {
629 using context = basic_printf_context_t<Char>;
630 return vsprintf(to_string_view(format), make_format_args<context>(args...));
631}
632
633template <typename S, typename Char = char_t<S>>
634inline int vfprintf(
635 std::FILE* f, const S& format,
636 basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args) {
638 printf(buffer, to_string_view(format), args);
639 std::size_t size = buffer.size();
640 return std::fwrite(buffer.data(), sizeof(Char), size, f) < size
641 ? -1
642 : static_cast<int>(size);
643}
644
654template <typename S, typename... Args,
655 typename Char = enable_if_t<internal::is_string<S>::value, char_t<S>>>
656inline int fprintf(std::FILE* f, const S& format, const Args&... args) {
657 using context = basic_printf_context_t<Char>;
658 return vfprintf(f, to_string_view(format),
659 make_format_args<context>(args...));
660}
661
662template <typename S, typename Char = char_t<S>>
663inline int vprintf(
664 const S& format,
665 basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args) {
666 return vfprintf(stdout, to_string_view(format), args);
667}
668
678template <typename S, typename... Args,
679 FMT_ENABLE_IF(internal::is_string<S>::value)>
680inline int printf(const S& format_str, const Args&... args) {
681 using context = basic_printf_context_t<char_t<S>>;
682 return vprintf(to_string_view(format_str),
683 make_format_args<context>(args...));
684}
685
686template <typename S, typename Char = char_t<S>>
687inline int vfprintf(
688 std::basic_ostream<Char>& os, const S& format,
689 basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args) {
691 printf(buffer, to_string_view(format), args);
692 internal::write(os, buffer);
693 return static_cast<int>(buffer.size());
694}
695
697template <typename ArgFormatter, typename Char,
698 typename Context =
700typename ArgFormatter::iterator vprintf(
702 basic_format_args<type_identity_t<Context>> args) {
703 typename ArgFormatter::iterator iter(out);
704 Context(iter, format_str, args).template format<ArgFormatter>();
705 return iter;
706}
707
717template <typename S, typename... Args, typename Char = char_t<S>>
718inline int fprintf(std::basic_ostream<Char>& os, const S& format_str,
719 const Args&... args) {
720 using context = basic_printf_context_t<Char>;
721 return vfprintf(os, to_string_view(format_str),
722 make_format_args<context>(args...));
723}
724FMT_END_NAMESPACE
725
726#endif // FMT_PRINTF_H_
Definition: core.h:1480
format_arg get(int index) const
Definition: core.h:1563
Definition: core.h:551
Definition: format.h:631
Definition: printf.h:325
Char char_type
Definition: printf.h:328
basic_printf_context(OutputIt out, basic_string_view< char_type > format_str, basic_format_args< basic_printf_context > args)
Definition: printf.h:359
OutputIt format()
Definition: printf.h:459
Definition: core.h:351
Definition: core.h:1331
Definition: format.h:724
std::size_t size() const FMT_NOEXCEPT
Definition: core.h:684
T * data() FMT_NOEXCEPT
Definition: core.h:690
Definition: printf.h:204
iterator operator()(const void *value)
Definition: printf.h:295
iterator operator()(const char *value)
Definition: printf.h:267
iterator operator()(typename basic_format_arg< context_type >::handle handle)
Definition: printf.h:303
iterator operator()(const wchar_t *value)
Definition: printf.h:278
printf_arg_formatter(iterator iter, format_specs &specs, context_type &ctx)
Definition: printf.h:235