diff --git a/include/spdlog/fmt/bundled/chrono.h b/include/spdlog/fmt/bundled/chrono.h new file mode 100644 index 00000000..209cdc25 --- /dev/null +++ b/include/spdlog/fmt/bundled/chrono.h @@ -0,0 +1,452 @@ +// Formatting library for C++ - chrono support +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_CHRONO_H_ +#define FMT_CHRONO_H_ + +#include "format.h" +#include "locale.h" + +#include +#include +#include +#include + +FMT_BEGIN_NAMESPACE + +namespace internal{ + +enum class numeric_system { + standard, + // Alternative numeric system, e.g. 十二 instead of 12 in ja_JP locale. + alternative +}; + +// Parses a put_time-like format string and invokes handler actions. +template +FMT_CONSTEXPR const Char *parse_chrono_format( + const Char *begin, const Char *end, Handler &&handler) { + auto ptr = begin; + while (ptr != end) { + auto c = *ptr; + if (c == '}') break; + if (c != '%') { + ++ptr; + continue; + } + if (begin != ptr) + handler.on_text(begin, ptr); + ++ptr; // consume '%' + if (ptr == end) + throw format_error("invalid format"); + c = *ptr++; + switch (c) { + case '%': + handler.on_text(ptr - 1, ptr); + break; + case 'n': { + const char newline[] = "\n"; + handler.on_text(newline, newline + 1); + break; + } + case 't': { + const char tab[] = "\t"; + handler.on_text(tab, tab + 1); + break; + } + // Day of the week: + case 'a': + handler.on_abbr_weekday(); + break; + case 'A': + handler.on_full_weekday(); + break; + case 'w': + handler.on_dec0_weekday(numeric_system::standard); + break; + case 'u': + handler.on_dec1_weekday(numeric_system::standard); + break; + // Month: + case 'b': + handler.on_abbr_month(); + break; + case 'B': + handler.on_full_month(); + break; + // Hour, minute, second: + case 'H': + handler.on_24_hour(numeric_system::standard); + break; + case 'I': + handler.on_12_hour(numeric_system::standard); + break; + case 'M': + handler.on_minute(numeric_system::standard); + break; + case 'S': + handler.on_second(numeric_system::standard); + break; + // Other: + case 'c': + handler.on_datetime(numeric_system::standard); + break; + case 'x': + handler.on_loc_date(numeric_system::standard); + break; + case 'X': + handler.on_loc_time(numeric_system::standard); + break; + case 'D': + handler.on_us_date(); + break; + case 'F': + handler.on_iso_date(); + break; + case 'r': + handler.on_12_hour_time(); + break; + case 'R': + handler.on_24_hour_time(); + break; + case 'T': + handler.on_iso_time(); + break; + case 'p': + handler.on_am_pm(); + break; + case 'z': + handler.on_utc_offset(); + break; + case 'Z': + handler.on_tz_name(); + break; + // Alternative representation: + case 'E': { + if (ptr == end) + throw format_error("invalid format"); + c = *ptr++; + switch (c) { + case 'c': + handler.on_datetime(numeric_system::alternative); + break; + case 'x': + handler.on_loc_date(numeric_system::alternative); + break; + case 'X': + handler.on_loc_time(numeric_system::alternative); + break; + default: + throw format_error("invalid format"); + } + break; + } + case 'O': + if (ptr == end) + throw format_error("invalid format"); + c = *ptr++; + switch (c) { + case 'w': + handler.on_dec0_weekday(numeric_system::alternative); + break; + case 'u': + handler.on_dec1_weekday(numeric_system::alternative); + break; + case 'H': + handler.on_24_hour(numeric_system::alternative); + break; + case 'I': + handler.on_12_hour(numeric_system::alternative); + break; + case 'M': + handler.on_minute(numeric_system::alternative); + break; + case 'S': + handler.on_second(numeric_system::alternative); + break; + default: + throw format_error("invalid format"); + } + break; + default: + throw format_error("invalid format"); + } + begin = ptr; + } + if (begin != ptr) + handler.on_text(begin, ptr); + return ptr; +} + +struct chrono_format_checker { + void report_no_date() { throw format_error("no date"); } + + template + void on_text(const Char *, const Char *) {} + void on_abbr_weekday() { report_no_date(); } + void on_full_weekday() { report_no_date(); } + void on_dec0_weekday(numeric_system) { report_no_date(); } + void on_dec1_weekday(numeric_system) { report_no_date(); } + void on_abbr_month() { report_no_date(); } + void on_full_month() { report_no_date(); } + void on_24_hour(numeric_system) {} + void on_12_hour(numeric_system) {} + void on_minute(numeric_system) {} + void on_second(numeric_system) {} + void on_datetime(numeric_system) { report_no_date(); } + void on_loc_date(numeric_system) { report_no_date(); } + void on_loc_time(numeric_system) { report_no_date(); } + void on_us_date() { report_no_date(); } + void on_iso_date() { report_no_date(); } + void on_12_hour_time() {} + void on_24_hour_time() {} + void on_iso_time() {} + void on_am_pm() {} + void on_utc_offset() { report_no_date(); } + void on_tz_name() { report_no_date(); } +}; + +template +inline int to_int(Int value) { + FMT_ASSERT(value >= (std::numeric_limits::min)() && + value <= (std::numeric_limits::max)(), "invalid value"); + return static_cast(value); +} + +template +struct chrono_formatter { + FormatContext &context; + OutputIt out; + std::chrono::seconds s; + std::chrono::milliseconds ms; + + typedef typename FormatContext::char_type char_type; + + explicit chrono_formatter(FormatContext &ctx, OutputIt o) + : context(ctx), out(o) {} + + int hour() const { return to_int((s.count() / 3600) % 24); } + + int hour12() const { + auto hour = to_int((s.count() / 3600) % 12); + return hour > 0 ? hour : 12; + } + + int minute() const { return to_int((s.count() / 60) % 60); } + int second() const { return to_int(s.count() % 60); } + + std::tm time() const { + auto time = std::tm(); + time.tm_hour = hour(); + time.tm_min = minute(); + time.tm_sec = second(); + return time; + } + + void write(int value, int width) { + typedef typename int_traits::main_type main_type; + main_type n = to_unsigned(value); + int num_digits = internal::count_digits(n); + if (width > num_digits) + out = std::fill_n(out, width - num_digits, '0'); + out = format_decimal(out, n, num_digits); + } + + void format_localized(const tm &time, const char *format) { + auto locale = context.locale().template get(); + auto &facet = std::use_facet>(locale); + std::basic_ostringstream os; + os.imbue(locale); + facet.put(os, os, ' ', &time, format, format + std::strlen(format)); + auto str = os.str(); + std::copy(str.begin(), str.end(), out); + } + + void on_text(const char_type *begin, const char_type *end) { + std::copy(begin, end, out); + } + + // These are not implemented because durations don't have date information. + void on_abbr_weekday() {} + void on_full_weekday() {} + void on_dec0_weekday(numeric_system) {} + void on_dec1_weekday(numeric_system) {} + void on_abbr_month() {} + void on_full_month() {} + void on_datetime(numeric_system) {} + void on_loc_date(numeric_system) {} + void on_loc_time(numeric_system) {} + void on_us_date() {} + void on_iso_date() {} + void on_utc_offset() {} + void on_tz_name() {} + + void on_24_hour(numeric_system ns) { + if (ns == numeric_system::standard) + return write(hour(), 2); + auto time = tm(); + time.tm_hour = hour(); + format_localized(time, "%OH"); + } + + void on_12_hour(numeric_system ns) { + if (ns == numeric_system::standard) + return write(hour12(), 2); + auto time = tm(); + time.tm_hour = hour(); + format_localized(time, "%OI"); + } + + void on_minute(numeric_system ns) { + if (ns == numeric_system::standard) + return write(minute(), 2); + auto time = tm(); + time.tm_min = minute(); + format_localized(time, "%OM"); + } + + void on_second(numeric_system ns) { + if (ns == numeric_system::standard) { + write(second(), 2); + if (ms != std::chrono::milliseconds(0)) { + *out++ = '.'; + write(to_int(ms.count()), 3); + } + return; + } + auto time = tm(); + time.tm_sec = second(); + format_localized(time, "%OS"); + } + + void on_12_hour_time() { format_localized(time(), "%r"); } + + void on_24_hour_time() { + write(hour(), 2); + *out++ = ':'; + write(minute(), 2); + } + + void on_iso_time() { + on_24_hour_time(); + *out++ = ':'; + write(second(), 2); + } + + void on_am_pm() { format_localized(time(), "%p"); } +}; +} // namespace internal + +template FMT_CONSTEXPR const char *get_units() { + return FMT_NULL; +} +template <> FMT_CONSTEXPR const char *get_units() { return "as"; } +template <> FMT_CONSTEXPR const char *get_units() { return "fs"; } +template <> FMT_CONSTEXPR const char *get_units() { return "ps"; } +template <> FMT_CONSTEXPR const char *get_units() { return "ns"; } +template <> FMT_CONSTEXPR const char *get_units() { return "µs"; } +template <> FMT_CONSTEXPR const char *get_units() { return "ms"; } +template <> FMT_CONSTEXPR const char *get_units() { return "cs"; } +template <> FMT_CONSTEXPR const char *get_units() { return "ds"; } +template <> FMT_CONSTEXPR const char *get_units>() { return "s"; } +template <> FMT_CONSTEXPR const char *get_units() { return "das"; } +template <> FMT_CONSTEXPR const char *get_units() { return "hs"; } +template <> FMT_CONSTEXPR const char *get_units() { return "ks"; } +template <> FMT_CONSTEXPR const char *get_units() { return "Ms"; } +template <> FMT_CONSTEXPR const char *get_units() { return "Gs"; } +template <> FMT_CONSTEXPR const char *get_units() { return "Ts"; } +template <> FMT_CONSTEXPR const char *get_units() { return "Ps"; } +template <> FMT_CONSTEXPR const char *get_units() { return "Es"; } +template <> FMT_CONSTEXPR const char *get_units>() { + return "m"; +} +template <> FMT_CONSTEXPR const char *get_units>() { + return "h"; +} + +template +struct formatter, Char> { + private: + align_spec spec; + internal::arg_ref width_ref; + mutable basic_string_view format_str; + typedef std::chrono::duration duration; + + struct spec_handler { + formatter &f; + basic_parse_context &context; + + typedef internal::arg_ref arg_ref_type; + + template + FMT_CONSTEXPR arg_ref_type make_arg_ref(Id arg_id) { + context.check_arg_id(arg_id); + return arg_ref_type(arg_id); + } + + FMT_CONSTEXPR arg_ref_type make_arg_ref(internal::auto_id) { + return arg_ref_type(context.next_arg_id()); + } + + void on_error(const char *msg) { throw format_error(msg); } + void on_fill(Char fill) { f.spec.fill_ = fill; } + void on_align(alignment align) { f.spec.align_ = align; } + void on_width(unsigned width) { f.spec.width_ = width; } + + template + void on_dynamic_width(Id arg_id) { + f.width_ref = make_arg_ref(arg_id); + } + }; + + public: + formatter() : spec() {} + + FMT_CONSTEXPR auto parse(basic_parse_context &ctx) + -> decltype(ctx.begin()) { + auto begin = ctx.begin(), end = ctx.end(); + if (begin == end) return begin; + spec_handler handler{*this, ctx}; + begin = internal::parse_align(begin, end, handler); + if (begin == end) return begin; + begin = internal::parse_width(begin, end, handler); + end = parse_chrono_format(begin, end, internal::chrono_format_checker()); + format_str = basic_string_view(&*begin, internal::to_unsigned(end - begin)); + return end; + } + + template + auto format(const duration &d, FormatContext &ctx) + -> decltype(ctx.out()) { + auto begin = format_str.begin(), end = format_str.end(); + memory_buffer buf; + typedef output_range range; + basic_writer w(range(ctx.out())); + if (begin == end || *begin == '}') { + if (const char *unit = get_units()) + format_to(buf, "{}{}", d.count(), unit); + else if (Period::den == 1) + format_to(buf, "{}[{}]s", d.count(), Period::num); + else + format_to(buf, "{}[{}/{}]s", d.count(), Period::num, Period::den); + internal::handle_dynamic_spec( + spec.width_, width_ref, ctx); + } else { + auto out = std::back_inserter(buf); + internal::chrono_formatter f(ctx, out); + f.s = std::chrono::duration_cast(d); + f.ms = std::chrono::duration_cast(d - f.s); + parse_chrono_format(begin, end, f); + } + w.write(buf.data(), buf.size(), spec); + return w.out(); + } +}; + +FMT_END_NAMESPACE + +#endif // FMT_CHRONO_H_ diff --git a/include/spdlog/fmt/bundled/color.h b/include/spdlog/fmt/bundled/color.h new file mode 100644 index 00000000..5db861c9 --- /dev/null +++ b/include/spdlog/fmt/bundled/color.h @@ -0,0 +1,577 @@ +// Formatting library for C++ - color support +// +// Copyright (c) 2018 - present, Victor Zverovich and fmt contributors +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_COLOR_H_ +#define FMT_COLOR_H_ + +#include "format.h" + +FMT_BEGIN_NAMESPACE + +#ifdef FMT_DEPRECATED_COLORS + +// color and (v)print_colored are deprecated. +enum color { black, red, green, yellow, blue, magenta, cyan, white }; +FMT_API void vprint_colored(color c, string_view format, format_args args); +FMT_API void vprint_colored(color c, wstring_view format, wformat_args args); +template +inline void print_colored(color c, string_view format_str, + const Args & ... args) { + vprint_colored(c, format_str, make_format_args(args...)); +} +template +inline void print_colored(color c, wstring_view format_str, + const Args & ... args) { + vprint_colored(c, format_str, make_format_args(args...)); +} + +inline void vprint_colored(color c, string_view format, format_args args) { + char escape[] = "\x1b[30m"; + escape[3] = static_cast('0' + c); + std::fputs(escape, stdout); + vprint(format, args); + std::fputs(internal::data::RESET_COLOR, stdout); +} + +inline void vprint_colored(color c, wstring_view format, wformat_args args) { + wchar_t escape[] = L"\x1b[30m"; + escape[3] = static_cast('0' + c); + std::fputws(escape, stdout); + vprint(format, args); + std::fputws(internal::data::WRESET_COLOR, stdout); +} + +#else + +enum class color : uint32_t { + alice_blue = 0xF0F8FF, // rgb(240,248,255) + antique_white = 0xFAEBD7, // rgb(250,235,215) + aqua = 0x00FFFF, // rgb(0,255,255) + aquamarine = 0x7FFFD4, // rgb(127,255,212) + azure = 0xF0FFFF, // rgb(240,255,255) + beige = 0xF5F5DC, // rgb(245,245,220) + bisque = 0xFFE4C4, // rgb(255,228,196) + black = 0x000000, // rgb(0,0,0) + blanched_almond = 0xFFEBCD, // rgb(255,235,205) + blue = 0x0000FF, // rgb(0,0,255) + blue_violet = 0x8A2BE2, // rgb(138,43,226) + brown = 0xA52A2A, // rgb(165,42,42) + burly_wood = 0xDEB887, // rgb(222,184,135) + cadet_blue = 0x5F9EA0, // rgb(95,158,160) + chartreuse = 0x7FFF00, // rgb(127,255,0) + chocolate = 0xD2691E, // rgb(210,105,30) + coral = 0xFF7F50, // rgb(255,127,80) + cornflower_blue = 0x6495ED, // rgb(100,149,237) + cornsilk = 0xFFF8DC, // rgb(255,248,220) + crimson = 0xDC143C, // rgb(220,20,60) + cyan = 0x00FFFF, // rgb(0,255,255) + dark_blue = 0x00008B, // rgb(0,0,139) + dark_cyan = 0x008B8B, // rgb(0,139,139) + dark_golden_rod = 0xB8860B, // rgb(184,134,11) + dark_gray = 0xA9A9A9, // rgb(169,169,169) + dark_green = 0x006400, // rgb(0,100,0) + dark_khaki = 0xBDB76B, // rgb(189,183,107) + dark_magenta = 0x8B008B, // rgb(139,0,139) + dark_olive_green = 0x556B2F, // rgb(85,107,47) + dark_orange = 0xFF8C00, // rgb(255,140,0) + dark_orchid = 0x9932CC, // rgb(153,50,204) + dark_red = 0x8B0000, // rgb(139,0,0) + dark_salmon = 0xE9967A, // rgb(233,150,122) + dark_sea_green = 0x8FBC8F, // rgb(143,188,143) + dark_slate_blue = 0x483D8B, // rgb(72,61,139) + dark_slate_gray = 0x2F4F4F, // rgb(47,79,79) + dark_turquoise = 0x00CED1, // rgb(0,206,209) + dark_violet = 0x9400D3, // rgb(148,0,211) + deep_pink = 0xFF1493, // rgb(255,20,147) + deep_sky_blue = 0x00BFFF, // rgb(0,191,255) + dim_gray = 0x696969, // rgb(105,105,105) + dodger_blue = 0x1E90FF, // rgb(30,144,255) + fire_brick = 0xB22222, // rgb(178,34,34) + floral_white = 0xFFFAF0, // rgb(255,250,240) + forest_green = 0x228B22, // rgb(34,139,34) + fuchsia = 0xFF00FF, // rgb(255,0,255) + gainsboro = 0xDCDCDC, // rgb(220,220,220) + ghost_white = 0xF8F8FF, // rgb(248,248,255) + gold = 0xFFD700, // rgb(255,215,0) + golden_rod = 0xDAA520, // rgb(218,165,32) + gray = 0x808080, // rgb(128,128,128) + green = 0x008000, // rgb(0,128,0) + green_yellow = 0xADFF2F, // rgb(173,255,47) + honey_dew = 0xF0FFF0, // rgb(240,255,240) + hot_pink = 0xFF69B4, // rgb(255,105,180) + indian_red = 0xCD5C5C, // rgb(205,92,92) + indigo = 0x4B0082, // rgb(75,0,130) + ivory = 0xFFFFF0, // rgb(255,255,240) + khaki = 0xF0E68C, // rgb(240,230,140) + lavender = 0xE6E6FA, // rgb(230,230,250) + lavender_blush = 0xFFF0F5, // rgb(255,240,245) + lawn_green = 0x7CFC00, // rgb(124,252,0) + lemon_chiffon = 0xFFFACD, // rgb(255,250,205) + light_blue = 0xADD8E6, // rgb(173,216,230) + light_coral = 0xF08080, // rgb(240,128,128) + light_cyan = 0xE0FFFF, // rgb(224,255,255) + light_golden_rod_yellow = 0xFAFAD2, // rgb(250,250,210) + light_gray = 0xD3D3D3, // rgb(211,211,211) + light_green = 0x90EE90, // rgb(144,238,144) + light_pink = 0xFFB6C1, // rgb(255,182,193) + light_salmon = 0xFFA07A, // rgb(255,160,122) + light_sea_green = 0x20B2AA, // rgb(32,178,170) + light_sky_blue = 0x87CEFA, // rgb(135,206,250) + light_slate_gray = 0x778899, // rgb(119,136,153) + light_steel_blue = 0xB0C4DE, // rgb(176,196,222) + light_yellow = 0xFFFFE0, // rgb(255,255,224) + lime = 0x00FF00, // rgb(0,255,0) + lime_green = 0x32CD32, // rgb(50,205,50) + linen = 0xFAF0E6, // rgb(250,240,230) + magenta = 0xFF00FF, // rgb(255,0,255) + maroon = 0x800000, // rgb(128,0,0) + medium_aquamarine = 0x66CDAA, // rgb(102,205,170) + medium_blue = 0x0000CD, // rgb(0,0,205) + medium_orchid = 0xBA55D3, // rgb(186,85,211) + medium_purple = 0x9370DB, // rgb(147,112,219) + medium_sea_green = 0x3CB371, // rgb(60,179,113) + medium_slate_blue = 0x7B68EE, // rgb(123,104,238) + medium_spring_green = 0x00FA9A, // rgb(0,250,154) + medium_turquoise = 0x48D1CC, // rgb(72,209,204) + medium_violet_red = 0xC71585, // rgb(199,21,133) + midnight_blue = 0x191970, // rgb(25,25,112) + mint_cream = 0xF5FFFA, // rgb(245,255,250) + misty_rose = 0xFFE4E1, // rgb(255,228,225) + moccasin = 0xFFE4B5, // rgb(255,228,181) + navajo_white = 0xFFDEAD, // rgb(255,222,173) + navy = 0x000080, // rgb(0,0,128) + old_lace = 0xFDF5E6, // rgb(253,245,230) + olive = 0x808000, // rgb(128,128,0) + olive_drab = 0x6B8E23, // rgb(107,142,35) + orange = 0xFFA500, // rgb(255,165,0) + orange_red = 0xFF4500, // rgb(255,69,0) + orchid = 0xDA70D6, // rgb(218,112,214) + pale_golden_rod = 0xEEE8AA, // rgb(238,232,170) + pale_green = 0x98FB98, // rgb(152,251,152) + pale_turquoise = 0xAFEEEE, // rgb(175,238,238) + pale_violet_red = 0xDB7093, // rgb(219,112,147) + papaya_whip = 0xFFEFD5, // rgb(255,239,213) + peach_puff = 0xFFDAB9, // rgb(255,218,185) + peru = 0xCD853F, // rgb(205,133,63) + pink = 0xFFC0CB, // rgb(255,192,203) + plum = 0xDDA0DD, // rgb(221,160,221) + powder_blue = 0xB0E0E6, // rgb(176,224,230) + purple = 0x800080, // rgb(128,0,128) + rebecca_purple = 0x663399, // rgb(102,51,153) + red = 0xFF0000, // rgb(255,0,0) + rosy_brown = 0xBC8F8F, // rgb(188,143,143) + royal_blue = 0x4169E1, // rgb(65,105,225) + saddle_brown = 0x8B4513, // rgb(139,69,19) + salmon = 0xFA8072, // rgb(250,128,114) + sandy_brown = 0xF4A460, // rgb(244,164,96) + sea_green = 0x2E8B57, // rgb(46,139,87) + sea_shell = 0xFFF5EE, // rgb(255,245,238) + sienna = 0xA0522D, // rgb(160,82,45) + silver = 0xC0C0C0, // rgb(192,192,192) + sky_blue = 0x87CEEB, // rgb(135,206,235) + slate_blue = 0x6A5ACD, // rgb(106,90,205) + slate_gray = 0x708090, // rgb(112,128,144) + snow = 0xFFFAFA, // rgb(255,250,250) + spring_green = 0x00FF7F, // rgb(0,255,127) + steel_blue = 0x4682B4, // rgb(70,130,180) + tan = 0xD2B48C, // rgb(210,180,140) + teal = 0x008080, // rgb(0,128,128) + thistle = 0xD8BFD8, // rgb(216,191,216) + tomato = 0xFF6347, // rgb(255,99,71) + turquoise = 0x40E0D0, // rgb(64,224,208) + violet = 0xEE82EE, // rgb(238,130,238) + wheat = 0xF5DEB3, // rgb(245,222,179) + white = 0xFFFFFF, // rgb(255,255,255) + white_smoke = 0xF5F5F5, // rgb(245,245,245) + yellow = 0xFFFF00, // rgb(255,255,0) + yellow_green = 0x9ACD32 // rgb(154,205,50) +}; // enum class color + +enum class terminal_color : uint8_t { + black = 30, + red, + green, + yellow, + blue, + magenta, + cyan, + white, + bright_black = 90, + bright_red, + bright_green, + bright_yellow, + bright_blue, + bright_magenta, + bright_cyan, + bright_white +}; // enum class terminal_color + +enum class emphasis : uint8_t { + bold = 1, + italic = 1 << 1, + underline = 1 << 2, + strikethrough = 1 << 3 +}; // enum class emphasis + +// rgb is a struct for red, green and blue colors. +// We use rgb as name because some editors will show it as color direct in the +// editor. +struct rgb { + FMT_CONSTEXPR_DECL rgb() : r(0), g(0), b(0) {} + FMT_CONSTEXPR_DECL rgb(uint8_t r_, uint8_t g_, uint8_t b_) + : r(r_), g(g_), b(b_) {} + FMT_CONSTEXPR_DECL rgb(uint32_t hex) + : r((hex >> 16) & 0xFF), g((hex >> 8) & 0xFF), b((hex) & 0xFF) {} + FMT_CONSTEXPR_DECL rgb(color hex) + : r((uint32_t(hex) >> 16) & 0xFF), g((uint32_t(hex) >> 8) & 0xFF), + b(uint32_t(hex) & 0xFF) {} + uint8_t r; + uint8_t g; + uint8_t b; +}; + +namespace internal { + +// color is a struct of either a rgb color or a terminal color. +struct color_type { + FMT_CONSTEXPR color_type() FMT_NOEXCEPT + : is_rgb(), value{} {} + FMT_CONSTEXPR color_type(color rgb_color) FMT_NOEXCEPT + : is_rgb(true), value{} { + value.rgb_color = static_cast(rgb_color); + } + FMT_CONSTEXPR color_type(rgb rgb_color) FMT_NOEXCEPT + : is_rgb(true), value{} { + value.rgb_color = (static_cast(rgb_color.r) << 16) + | (static_cast(rgb_color.g) << 8) | rgb_color.b; + } + FMT_CONSTEXPR color_type(terminal_color term_color) FMT_NOEXCEPT + : is_rgb(), value{} { + value.term_color = static_cast(term_color); + } + bool is_rgb; + union color_union { + uint8_t term_color; + uint32_t rgb_color; + } value; +}; +} // namespace internal + +// Experimental text formatting support. +class text_style { + public: + FMT_CONSTEXPR text_style(emphasis em = emphasis()) FMT_NOEXCEPT + : set_foreground_color(), set_background_color(), ems(em) {} + + FMT_CONSTEXPR text_style &operator|=(const text_style &rhs) { + if (!set_foreground_color) { + set_foreground_color = rhs.set_foreground_color; + foreground_color = rhs.foreground_color; + } else if (rhs.set_foreground_color) { + if (!foreground_color.is_rgb || !rhs.foreground_color.is_rgb) + throw format_error("can't OR a terminal color"); + foreground_color.value.rgb_color |= rhs.foreground_color.value.rgb_color; + } + + if (!set_background_color) { + set_background_color = rhs.set_background_color; + background_color = rhs.background_color; + } else if (rhs.set_background_color) { + if (!background_color.is_rgb || !rhs.background_color.is_rgb) + throw format_error("can't OR a terminal color"); + background_color.value.rgb_color |= rhs.background_color.value.rgb_color; + } + + ems = static_cast(static_cast(ems) | + static_cast(rhs.ems)); + return *this; + } + + friend FMT_CONSTEXPR + text_style operator|(text_style lhs, const text_style &rhs) { + return lhs |= rhs; + } + + FMT_CONSTEXPR text_style &operator&=(const text_style &rhs) { + if (!set_foreground_color) { + set_foreground_color = rhs.set_foreground_color; + foreground_color = rhs.foreground_color; + } else if (rhs.set_foreground_color) { + if (!foreground_color.is_rgb || !rhs.foreground_color.is_rgb) + throw format_error("can't AND a terminal color"); + foreground_color.value.rgb_color &= rhs.foreground_color.value.rgb_color; + } + + if (!set_background_color) { + set_background_color = rhs.set_background_color; + background_color = rhs.background_color; + } else if (rhs.set_background_color) { + if (!background_color.is_rgb || !rhs.background_color.is_rgb) + throw format_error("can't AND a terminal color"); + background_color.value.rgb_color &= rhs.background_color.value.rgb_color; + } + + ems = static_cast(static_cast(ems) & + static_cast(rhs.ems)); + return *this; + } + + friend FMT_CONSTEXPR + text_style operator&(text_style lhs, const text_style &rhs) { + return lhs &= rhs; + } + + FMT_CONSTEXPR bool has_foreground() const FMT_NOEXCEPT { + return set_foreground_color; + } + FMT_CONSTEXPR bool has_background() const FMT_NOEXCEPT { + return set_background_color; + } + FMT_CONSTEXPR bool has_emphasis() const FMT_NOEXCEPT { + return static_cast(ems) != 0; + } + FMT_CONSTEXPR internal::color_type get_foreground() const FMT_NOEXCEPT { + assert(has_foreground() && "no foreground specified for this style"); + return foreground_color; + } + FMT_CONSTEXPR internal::color_type get_background() const FMT_NOEXCEPT { + assert(has_background() && "no background specified for this style"); + return background_color; + } + FMT_CONSTEXPR emphasis get_emphasis() const FMT_NOEXCEPT { + assert(has_emphasis() && "no emphasis specified for this style"); + return ems; + } + +private: + FMT_CONSTEXPR text_style(bool is_foreground, + internal::color_type text_color) FMT_NOEXCEPT + : set_foreground_color(), + set_background_color(), + ems() { + if (is_foreground) { + foreground_color = text_color; + set_foreground_color = true; + } else { + background_color = text_color; + set_background_color = true; + } + } + + friend FMT_CONSTEXPR_DECL text_style fg(internal::color_type foreground) + FMT_NOEXCEPT; + friend FMT_CONSTEXPR_DECL text_style bg(internal::color_type background) + FMT_NOEXCEPT; + + internal::color_type foreground_color; + internal::color_type background_color; + bool set_foreground_color; + bool set_background_color; + emphasis ems; +}; + +FMT_CONSTEXPR text_style fg(internal::color_type foreground) FMT_NOEXCEPT { + return text_style(/*is_foreground=*/true, foreground); +} + +FMT_CONSTEXPR text_style bg(internal::color_type background) FMT_NOEXCEPT { + return text_style(/*is_foreground=*/false, background); +} + +FMT_CONSTEXPR text_style operator|(emphasis lhs, emphasis rhs) FMT_NOEXCEPT { + return text_style(lhs) | rhs; +} + +namespace internal { + +template +struct ansi_color_escape { + FMT_CONSTEXPR ansi_color_escape(internal::color_type text_color, + const char * esc) FMT_NOEXCEPT { + // If we have a terminal color, we need to output another escape code + // sequence. + if (!text_color.is_rgb) { + bool is_background = esc == internal::data::BACKGROUND_COLOR; + uint32_t value = text_color.value.term_color; + // Background ASCII codes are the same as the foreground ones but with + // 10 more. + if (is_background) + value += 10u; + + std::size_t index = 0; + buffer[index++] = static_cast('\x1b'); + buffer[index++] = static_cast('['); + + if (value >= 100u) { + buffer[index++] = static_cast('1'); + value %= 100u; + } + buffer[index++] = static_cast('0' + value / 10u); + buffer[index++] = static_cast('0' + value % 10u); + + buffer[index++] = static_cast('m'); + buffer[index++] = static_cast('\0'); + return; + } + + for (int i = 0; i < 7; i++) { + buffer[i] = static_cast(esc[i]); + } + rgb color(text_color.value.rgb_color); + to_esc(color.r, buffer + 7, ';'); + to_esc(color.g, buffer + 11, ';'); + to_esc(color.b, buffer + 15, 'm'); + buffer[19] = static_cast(0); + } + FMT_CONSTEXPR ansi_color_escape(emphasis em) FMT_NOEXCEPT { + uint8_t em_codes[4] = {}; + uint8_t em_bits = static_cast(em); + if (em_bits & static_cast(emphasis::bold)) + em_codes[0] = 1; + if (em_bits & static_cast(emphasis::italic)) + em_codes[1] = 3; + if (em_bits & static_cast(emphasis::underline)) + em_codes[2] = 4; + if (em_bits & static_cast(emphasis::strikethrough)) + em_codes[3] = 9; + + std::size_t index = 0; + for (int i = 0; i < 4; ++i) { + if (!em_codes[i]) + continue; + buffer[index++] = static_cast('\x1b'); + buffer[index++] = static_cast('['); + buffer[index++] = static_cast('0' + em_codes[i]); + buffer[index++] = static_cast('m'); + } + buffer[index++] = static_cast(0); + } + FMT_CONSTEXPR operator const Char *() const FMT_NOEXCEPT { return buffer; } + +private: + Char buffer[7u + 3u * 4u + 1u]; + + static FMT_CONSTEXPR void to_esc(uint8_t c, Char *out, + char delimiter) FMT_NOEXCEPT { + out[0] = static_cast('0' + c / 100); + out[1] = static_cast('0' + c / 10 % 10); + out[2] = static_cast('0' + c % 10); + out[3] = static_cast(delimiter); + } +}; + +template +FMT_CONSTEXPR ansi_color_escape +make_foreground_color(internal::color_type foreground) FMT_NOEXCEPT { + return ansi_color_escape(foreground, internal::data::FOREGROUND_COLOR); +} + +template +FMT_CONSTEXPR ansi_color_escape +make_background_color(internal::color_type background) FMT_NOEXCEPT { + return ansi_color_escape(background, internal::data::BACKGROUND_COLOR); +} + +template +FMT_CONSTEXPR ansi_color_escape +make_emphasis(emphasis em) FMT_NOEXCEPT { + return ansi_color_escape(em); +} + +template +inline void fputs(const Char *chars, FILE *stream) FMT_NOEXCEPT { + std::fputs(chars, stream); +} + +template <> +inline void fputs(const wchar_t *chars, FILE *stream) FMT_NOEXCEPT { + std::fputws(chars, stream); +} + +template +inline void reset_color(FILE *stream) FMT_NOEXCEPT { + fputs(internal::data::RESET_COLOR, stream); +} + +template <> +inline void reset_color(FILE *stream) FMT_NOEXCEPT { + fputs(internal::data::WRESET_COLOR, stream); +} + +// The following specialiazation disables using std::FILE as a character type, +// which is needed because or else +// fmt::print(stderr, fmt::emphasis::bold, ""); +// would take stderr (a std::FILE *) as the format string. +template <> +struct is_string : std::false_type {}; +template <> +struct is_string : std::false_type {}; +} // namespace internal + +template < + typename S, typename Char = typename internal::char_t::type> +void vprint(std::FILE *f, const text_style &ts, const S &format, + basic_format_args::type> args) { + bool has_style = false; + if (ts.has_emphasis()) { + has_style = true; + internal::fputs( + internal::make_emphasis(ts.get_emphasis()), f); + } + if (ts.has_foreground()) { + has_style = true; + internal::fputs( + internal::make_foreground_color(ts.get_foreground()), f); + } + if (ts.has_background()) { + has_style = true; + internal::fputs( + internal::make_background_color(ts.get_background()), f); + } + vprint(f, format, args); + if (has_style) { + internal::reset_color(f); + } +} + +/** + Formats a string and prints it to the specified file stream using ANSI + escape sequences to specify text formatting. + Example: + fmt::print(fmt::emphasis::bold | fg(fmt::color::red), + "Elapsed time: {0:.2f} seconds", 1.23); + */ +template +typename std::enable_if::value>::type print( + std::FILE *f, const text_style &ts, const String &format_str, + const Args &... args) { + internal::check_format_string(format_str); + typedef typename internal::char_t::type char_t; + typedef typename buffer_context::type context_t; + format_arg_store as{args...}; + vprint(f, ts, format_str, basic_format_args(as)); +} + +/** + Formats a string and prints it to stdout using ANSI escape sequences to + specify text formatting. + Example: + fmt::print(fmt::emphasis::bold | fg(fmt::color::red), + "Elapsed time: {0:.2f} seconds", 1.23); + */ +template +typename std::enable_if::value>::type print( + const text_style &ts, const String &format_str, + const Args &... args) { + return print(stdout, ts, format_str, args...); +} + +#endif + +FMT_END_NAMESPACE + +#endif // FMT_COLOR_H_ diff --git a/include/spdlog/fmt/bundled/core.h b/include/spdlog/fmt/bundled/core.h index 5912afef..50b79351 100644 --- a/include/spdlog/fmt/bundled/core.h +++ b/include/spdlog/fmt/bundled/core.h @@ -16,7 +16,7 @@ #include // The fmt library version in the form major * 10000 + minor * 100 + patch. -#define FMT_VERSION 50201 +#define FMT_VERSION 50300 #ifdef __has_feature # define FMT_HAS_FEATURE(x) __has_feature(x) @@ -25,7 +25,7 @@ #endif #if defined(__has_include) && !defined(__INTELLISENSE__) && \ - (!defined(__INTEL_COMPILER) || __INTEL_COMPILER >= 1600) + !(defined(__INTEL_COMPILER) && __INTEL_COMPILER < 1600) # define FMT_HAS_INCLUDE(x) __has_include(x) #else # define FMT_HAS_INCLUDE(x) 0 @@ -72,7 +72,7 @@ #ifndef FMT_USE_CONSTEXPR11 # define FMT_USE_CONSTEXPR11 \ - (FMT_MSC_VER >= 1900 || FMT_GCC_VERSION >= 406 || FMT_USE_CONSTEXPR) + (FMT_USE_CONSTEXPR || FMT_GCC_VERSION >= 406 || FMT_MSC_VER >= 1900) #endif #if FMT_USE_CONSTEXPR11 # define FMT_CONSTEXPR11 constexpr @@ -89,9 +89,12 @@ # endif #endif -#if FMT_HAS_FEATURE(cxx_explicit_conversions) || FMT_MSC_VER >= 1800 +#if FMT_HAS_FEATURE(cxx_explicit_conversions) || \ + FMT_GCC_VERSION >= 405 || FMT_MSC_VER >= 1800 +# define FMT_USE_EXPLICIT 1 # define FMT_EXPLICIT explicit #else +# define FMT_USE_EXPLICIT 0 # define FMT_EXPLICIT #endif @@ -104,25 +107,18 @@ # define FMT_NULL NULL # endif #endif - #ifndef FMT_USE_NULLPTR # define FMT_USE_NULLPTR 0 #endif -#if FMT_HAS_CPP_ATTRIBUTE(noreturn) -# define FMT_NORETURN [[noreturn]] -#else -# define FMT_NORETURN -#endif - // Check if exceptions are disabled. -#if defined(__GNUC__) && !defined(__EXCEPTIONS) -# define FMT_EXCEPTIONS 0 -#elif FMT_MSC_VER && !_HAS_EXCEPTIONS -# define FMT_EXCEPTIONS 0 -#endif #ifndef FMT_EXCEPTIONS -# define FMT_EXCEPTIONS 1 +# if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || \ + FMT_MSC_VER && !_HAS_EXCEPTIONS +# define FMT_EXCEPTIONS 0 +# else +# define FMT_EXCEPTIONS 1 +# endif #endif // Define FMT_USE_NOEXCEPT to make fmt use noexcept (C++11 feature). @@ -147,14 +143,6 @@ # endif #endif -// This is needed because GCC still uses throw() in its headers when exceptions -// are disabled. -#if FMT_GCC_VERSION -# define FMT_DTOR_NOEXCEPT FMT_DETECTED_NOEXCEPT -#else -# define FMT_DTOR_NOEXCEPT FMT_NOEXCEPT -#endif - #ifndef FMT_BEGIN_NAMESPACE # if FMT_HAS_FEATURE(cxx_inline_namespaces) || FMT_GCC_VERSION >= 404 || \ FMT_MSC_VER >= 1900 @@ -187,11 +175,10 @@ (__cplusplus > 201402L || defined(_LIBCPP_VERSION))) || \ (defined(_MSVC_LANG) && _MSVC_LANG > 201402L && _MSC_VER >= 1910) # include -# define FMT_USE_STD_STRING_VIEW -#elif (FMT_HAS_INCLUDE() && \ - __cplusplus >= 201402L) +# define FMT_STRING_VIEW std::basic_string_view +#elif FMT_HAS_INCLUDE() && __cplusplus >= 201402L # include -# define FMT_USE_EXPERIMENTAL_STRING_VIEW +# define FMT_STRING_VIEW std::experimental::basic_string_view #endif // std::result_of is defined in in gcc 4.4. @@ -223,149 +210,6 @@ FMT_CONSTEXPR typename std::make_unsigned::type to_unsigned(Int value) { return static_cast::type>(value); } -// A constexpr std::char_traits::length replacement for pre-C++17. -template -FMT_CONSTEXPR size_t length(const Char *s) { - const Char *start = s; - while (*s) ++s; - return s - start; -} -#if FMT_GCC_VERSION -FMT_CONSTEXPR size_t length(const char *s) { return std::strlen(s); } -#endif -} // namespace internal - -/** - An implementation of ``std::basic_string_view`` for pre-C++17. It provides a - subset of the API. ``fmt::basic_string_view`` is used for format strings even - if ``std::string_view`` is available to prevent issues when a library is - compiled with a different ``-std`` option than the client code (which is not - recommended). - */ -template -class basic_string_view { - private: - const Char *data_; - size_t size_; - - public: - typedef Char char_type; - typedef const Char *iterator; - - // Standard basic_string_view type. -#if defined(FMT_USE_STD_STRING_VIEW) - typedef std::basic_string_view type; -#elif defined(FMT_USE_EXPERIMENTAL_STRING_VIEW) - typedef std::experimental::basic_string_view type; -#else - struct type { - const char *data() const { return FMT_NULL; } - size_t size() const { return 0; } - }; -#endif - - FMT_CONSTEXPR basic_string_view() FMT_NOEXCEPT : data_(FMT_NULL), size_(0) {} - - /** Constructs a string reference object from a C string and a size. */ - FMT_CONSTEXPR basic_string_view(const Char *s, size_t count) FMT_NOEXCEPT - : data_(s), size_(count) {} - - /** - \rst - Constructs a string reference object from a C string computing - the size with ``std::char_traits::length``. - \endrst - */ - FMT_CONSTEXPR basic_string_view(const Char *s) - : data_(s), size_(internal::length(s)) {} - - /** Constructs a string reference from a ``std::basic_string`` object. */ - template - FMT_CONSTEXPR basic_string_view( - const std::basic_string &s) FMT_NOEXCEPT - : data_(s.data()), size_(s.size()) {} - - FMT_CONSTEXPR basic_string_view(type s) FMT_NOEXCEPT - : data_(s.data()), size_(s.size()) {} - - /** Returns a pointer to the string data. */ - FMT_CONSTEXPR const Char *data() const { return data_; } - - /** Returns the string size. */ - FMT_CONSTEXPR size_t size() const { return size_; } - - FMT_CONSTEXPR iterator begin() const { return data_; } - FMT_CONSTEXPR iterator end() const { return data_ + size_; } - - FMT_CONSTEXPR void remove_prefix(size_t n) { - data_ += n; - size_ -= n; - } - - // Lexicographically compare this string reference to other. - int compare(basic_string_view other) const { - size_t str_size = size_ < other.size_ ? size_ : other.size_; - int result = std::char_traits::compare(data_, other.data_, str_size); - if (result == 0) - result = size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1); - return result; - } - - friend bool operator==(basic_string_view lhs, basic_string_view rhs) { - return lhs.compare(rhs) == 0; - } - friend bool operator!=(basic_string_view lhs, basic_string_view rhs) { - return lhs.compare(rhs) != 0; - } - friend bool operator<(basic_string_view lhs, basic_string_view rhs) { - return lhs.compare(rhs) < 0; - } - friend bool operator<=(basic_string_view lhs, basic_string_view rhs) { - return lhs.compare(rhs) <= 0; - } - friend bool operator>(basic_string_view lhs, basic_string_view rhs) { - return lhs.compare(rhs) > 0; - } - friend bool operator>=(basic_string_view lhs, basic_string_view rhs) { - return lhs.compare(rhs) >= 0; - } -}; - -typedef basic_string_view string_view; -typedef basic_string_view wstring_view; - -template -class basic_format_arg; - -template -class basic_format_args; - -template -struct no_formatter_error : std::false_type {}; - -// A formatter for objects of type T. -template -struct formatter { - static_assert(no_formatter_error::value, - "don't know how to format the type, include fmt/ostream.h if it provides " - "an operator<< that should be used"); - - // The following functions are not defined intentionally. - template - typename ParseContext::iterator parse(ParseContext &); - template - auto format(const T &val, FormatContext &ctx) -> decltype(ctx.out()); -}; - -template -struct convert_to_int { - enum { - value = !std::is_arithmetic::value && std::is_convertible::value - }; -}; - -namespace internal { - /** A contiguous memory buffer with an optional growing ability. */ template class basic_buffer { @@ -464,6 +308,17 @@ class container_buffer : public basic_buffer { : basic_buffer(c.size()), container_(c) {} }; +// Extracts a reference to the container from back_insert_iterator. +template +inline Container &get_container(std::back_insert_iterator it) { + typedef std::back_insert_iterator bi_iterator; + struct accessor: bi_iterator { + accessor(bi_iterator iter) : bi_iterator(iter) {} + using bi_iterator::container; + }; + return *accessor(it).container; +} + struct error_handler { FMT_CONSTEXPR error_handler() {} FMT_CONSTEXPR error_handler(const error_handler &) {} @@ -472,16 +327,199 @@ struct error_handler { FMT_API void on_error(const char *message); }; -// Formatting of wide characters and strings into a narrow output is disallowed: -// fmt::format("{}", L"test"); // error -// To fix this, use a wide format string: -// fmt::format(L"{}", L"test"); +template +struct no_formatter_error : std::false_type {}; +} // namespace internal + +#if FMT_GCC_VERSION && FMT_GCC_VERSION < 405 +template +struct is_constructible: std::false_type {}; +#else +template +struct is_constructible : std::is_constructible {}; +#endif + +/** + An implementation of ``std::basic_string_view`` for pre-C++17. It provides a + subset of the API. ``fmt::basic_string_view`` is used for format strings even + if ``std::string_view`` is available to prevent issues when a library is + compiled with a different ``-std`` option than the client code (which is not + recommended). + */ template -inline void require_wchar() { - static_assert( - std::is_same::value, - "formatting of wide characters into a narrow output is disallowed"); -} +class basic_string_view { + private: + const Char *data_; + size_t size_; + + public: + typedef Char char_type; + typedef const Char *iterator; + + FMT_CONSTEXPR basic_string_view() FMT_NOEXCEPT : data_(FMT_NULL), size_(0) {} + + /** Constructs a string reference object from a C string and a size. */ + FMT_CONSTEXPR basic_string_view(const Char *s, size_t count) FMT_NOEXCEPT + : data_(s), size_(count) {} + + /** + \rst + Constructs a string reference object from a C string computing + the size with ``std::char_traits::length``. + \endrst + */ + basic_string_view(const Char *s) + : data_(s), size_(std::char_traits::length(s)) {} + + /** Constructs a string reference from a ``std::basic_string`` object. */ + template + FMT_CONSTEXPR basic_string_view( + const std::basic_string &s) FMT_NOEXCEPT + : data_(s.data()), size_(s.size()) {} + +#ifdef FMT_STRING_VIEW + FMT_CONSTEXPR basic_string_view(FMT_STRING_VIEW s) FMT_NOEXCEPT + : data_(s.data()), size_(s.size()) {} +#endif + + /** Returns a pointer to the string data. */ + FMT_CONSTEXPR const Char *data() const { return data_; } + + /** Returns the string size. */ + FMT_CONSTEXPR size_t size() const { return size_; } + + FMT_CONSTEXPR iterator begin() const { return data_; } + FMT_CONSTEXPR iterator end() const { return data_ + size_; } + + FMT_CONSTEXPR void remove_prefix(size_t n) { + data_ += n; + size_ -= n; + } + + // Lexicographically compare this string reference to other. + int compare(basic_string_view other) const { + size_t str_size = size_ < other.size_ ? size_ : other.size_; + int result = std::char_traits::compare(data_, other.data_, str_size); + if (result == 0) + result = size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1); + return result; + } + + friend bool operator==(basic_string_view lhs, basic_string_view rhs) { + return lhs.compare(rhs) == 0; + } + friend bool operator!=(basic_string_view lhs, basic_string_view rhs) { + return lhs.compare(rhs) != 0; + } + friend bool operator<(basic_string_view lhs, basic_string_view rhs) { + return lhs.compare(rhs) < 0; + } + friend bool operator<=(basic_string_view lhs, basic_string_view rhs) { + return lhs.compare(rhs) <= 0; + } + friend bool operator>(basic_string_view lhs, basic_string_view rhs) { + return lhs.compare(rhs) > 0; + } + friend bool operator>=(basic_string_view lhs, basic_string_view rhs) { + return lhs.compare(rhs) >= 0; + } +}; + +typedef basic_string_view string_view; +typedef basic_string_view wstring_view; + +/** + \rst + The function ``to_string_view`` adapts non-intrusively any kind of string or + string-like type if the user provides a (possibly templated) overload of + ``to_string_view`` which takes an instance of the string class + ``StringType`` and returns a ``fmt::basic_string_view``. + The conversion function must live in the very same namespace as + ``StringType`` to be picked up by ADL. Non-templated string types + like f.e. QString must return a ``basic_string_view`` with a fixed matching + char type. + + **Example**:: + + namespace my_ns { + inline string_view to_string_view(const my_string &s) { + return {s.data(), s.length()}; + } + } + + std::string message = fmt::format(my_string("The answer is {}"), 42); + \endrst + */ +template +inline basic_string_view + to_string_view(basic_string_view s) { return s; } + +template +inline basic_string_view + to_string_view(const std::basic_string &s) { return s; } + +template +inline basic_string_view to_string_view(const Char *s) { return s; } + +#ifdef FMT_STRING_VIEW +template +inline basic_string_view + to_string_view(FMT_STRING_VIEW s) { return s; } +#endif + +// A base class for compile-time strings. It is defined in the fmt namespace to +// make formatting functions visible via ADL, e.g. format(fmt("{}"), 42). +struct compile_string {}; + +template +struct is_compile_string : std::is_base_of {}; + +template < + typename S, + typename Enable = typename std::enable_if::value>::type> +FMT_CONSTEXPR basic_string_view + to_string_view(const S &s) { return s; } + +template +class basic_format_arg; + +template +class basic_format_args; + +// A formatter for objects of type T. +template +struct formatter { + static_assert(internal::no_formatter_error::value, + "don't know how to format the type, include fmt/ostream.h if it provides " + "an operator<< that should be used"); + + // The following functions are not defined intentionally. + template + typename ParseContext::iterator parse(ParseContext &); + template + auto format(const T &val, FormatContext &ctx) -> decltype(ctx.out()); +}; + +template +struct convert_to_int: std::integral_constant< + bool, !std::is_arithmetic::value && std::is_convertible::value> {}; + +namespace internal { + +struct dummy_string_view { typedef void char_type; }; +dummy_string_view to_string_view(...); +using fmt::v5::to_string_view; + +// Specifies whether S is a string type convertible to fmt::basic_string_view. +template +struct is_string : std::integral_constant()))>::value> {}; + +template +struct char_t { + typedef decltype(to_string_view(declval())) result; + typedef typename result::char_type type; +}; template struct named_arg_base; @@ -489,12 +527,6 @@ struct named_arg_base; template struct named_arg; -template -struct is_named_arg : std::false_type {}; - -template -struct is_named_arg> : std::true_type {}; - enum type { none_type, named_arg_type, // Integer types should go first, @@ -639,15 +671,17 @@ FMT_MAKE_VALUE_SAME(long_long_type, long long) FMT_MAKE_VALUE_SAME(ulong_long_type, unsigned long long) FMT_MAKE_VALUE(int_type, signed char, int) FMT_MAKE_VALUE(uint_type, unsigned char, unsigned) -FMT_MAKE_VALUE(char_type, char, int) -#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) +// This doesn't use FMT_MAKE_VALUE because of ambiguity in gcc 4.4. +template +FMT_CONSTEXPR typename std::enable_if< + std::is_same::value, + init>::type make_value(Char val) { return val; } + template -inline init make_value(wchar_t val) { - require_wchar(); - return static_cast(val); -} -#endif +FMT_CONSTEXPR typename std::enable_if< + !std::is_same::value, + init>::type make_value(char val) { return val; } FMT_MAKE_VALUE(double_type, float, double) FMT_MAKE_VALUE_SAME(double_type, double) @@ -695,15 +729,17 @@ inline typename std::enable_if< template inline typename std::enable_if< - std::is_constructible, T>::value, + is_constructible, T>::value && + !internal::is_string::value, init, string_type>>::type make_value(const T &val) { return basic_string_view(val); } template inline typename std::enable_if< - !convert_to_int::value && + !convert_to_int::value && !std::is_same::value && !std::is_convertible>::value && - !std::is_constructible, T>::value, + !is_constructible, T>::value && + !internal::is_string::value, // Implicit conversion to std::string is not handled here because it's // unsafe: https://github.com/fmtlib/fmt/issues/729 init>::type @@ -717,8 +753,21 @@ init return static_cast(&val); } +template +FMT_CONSTEXPR11 typename std::enable_if< + internal::is_string::value, + init, string_type>>::type + make_value(const S &val) { + // Handle adapted strings. + static_assert(std::is_same< + typename C::char_type, typename internal::char_t::type>::value, + "mismatch between char-types of context and argument"); + return to_string_view(val); +} + // Maximum number of arguments with packed types. enum { max_packed_args = 15 }; +enum : unsigned long long { is_unpacked_bit = 1ull << 63 }; template class arg_map; @@ -738,7 +787,7 @@ class basic_format_arg { template friend FMT_CONSTEXPR typename internal::result_of::type - visit(Visitor &&vis, const basic_format_arg &arg); + visit_format_arg(Visitor &&vis, const basic_format_arg &arg); friend class basic_format_args; friend class internal::arg_map; @@ -779,7 +828,7 @@ struct monostate {}; */ template FMT_CONSTEXPR typename internal::result_of::type - visit(Visitor &&vis, const basic_format_arg &arg) { + visit_format_arg(Visitor &&vis, const basic_format_arg &arg) { typedef typename Context::char_type char_type; switch (arg.type_) { case internal::none_type: @@ -816,6 +865,13 @@ FMT_CONSTEXPR typename internal::result_of::type return vis(monostate()); } +// DEPRECATED! +template +FMT_CONSTEXPR typename internal::result_of::type + visit(Visitor &&vis, const basic_format_arg &arg) { + return visit_format_arg(std::forward(vis), arg); +} + // Parsing context consisting of a format string range being parsed and an // argument counter for automatic indexing. template @@ -866,6 +922,10 @@ class basic_parse_context : private ErrorHandler { FMT_CONSTEXPR ErrorHandler error_handler() const { return *this; } }; +typedef basic_parse_context format_parse_context; +typedef basic_parse_context wformat_parse_context; + +// DEPRECATED! typedef basic_parse_context parse_context; typedef basic_parse_context wparse_context; @@ -904,10 +964,26 @@ class arg_map { if (it->name == name) return it->arg; } - return basic_format_arg(); + return {}; } }; +// A type-erased reference to an std::locale to avoid heavy include. +class locale_ref { + private: + const void *locale_; // A type-erased pointer to std::locale. + friend class locale; + + public: + locale_ref() : locale_(FMT_NULL) {} + + template + explicit locale_ref(const Locale &loc); + + template + Locale get() const; +}; + template class context_base { public: @@ -917,14 +993,16 @@ class context_base { basic_parse_context parse_context_; iterator out_; basic_format_args args_; + locale_ref loc_; protected: typedef Char char_type; typedef basic_format_arg format_arg; context_base(OutputIt out, basic_string_view format_str, - basic_format_args ctx_args) - : parse_context_(format_str), out_(out), args_(ctx_args) {} + basic_format_args ctx_args, + locale_ref loc = locale_ref()) + : parse_context_(format_str), out_(out), args_(ctx_args), loc_(loc) {} // Returns the argument with specified index. format_arg do_get_arg(unsigned arg_id) { @@ -942,9 +1020,9 @@ class context_base { } public: - basic_parse_context &parse_context() { - return parse_context_; - } + basic_parse_context &parse_context() { return parse_context_; } + basic_format_args args() const { return args_; } // DEPRECATED! + basic_format_arg arg(unsigned id) const { return args_.get(id); } internal::error_handler error_handler() { return parse_context_.error_handler(); @@ -959,74 +1037,9 @@ class context_base { // Advances the begin iterator to ``it``. void advance_to(iterator it) { out_ = it; } - basic_format_args args() const { return args_; } + locale_ref locale() { return loc_; } }; -// Extracts a reference to the container from back_insert_iterator. -template -inline Container &get_container(std::back_insert_iterator it) { - typedef std::back_insert_iterator bi_iterator; - struct accessor: bi_iterator { - accessor(bi_iterator iter) : bi_iterator(iter) {} - using bi_iterator::container; - }; - return *accessor(it).container; -} -} // namespace internal - -// Formatting context. -template -class basic_format_context : - public internal::context_base< - OutputIt, basic_format_context, Char> { - public: - /** The character type for the output. */ - typedef Char char_type; - - // using formatter_type = formatter; - template - struct formatter_type { typedef formatter type; }; - - private: - internal::arg_map map_; - - basic_format_context(const basic_format_context &) = delete; - void operator=(const basic_format_context &) = delete; - - typedef internal::context_base base; - typedef typename base::format_arg format_arg; - using base::get_arg; - - public: - using typename base::iterator; - - /** - Constructs a ``basic_format_context`` object. References to the arguments are - stored in the object so make sure they have appropriate lifetimes. - */ - basic_format_context(OutputIt out, basic_string_view format_str, - basic_format_args ctx_args) - : base(out, format_str, ctx_args) {} - - format_arg next_arg() { - return this->do_get_arg(this->parse_context().next_arg_id()); - } - format_arg get_arg(unsigned arg_id) { return this->do_get_arg(arg_id); } - - // Checks if manual indexing is used and returns the argument with the - // specified name. - format_arg get_arg(basic_string_view name); -}; - -template -struct buffer_context { - typedef basic_format_context< - std::back_insert_iterator>, Char> type; -}; -typedef buffer_context::type format_context; -typedef buffer_context::type wformat_context; - -namespace internal { template struct get_type { typedef decltype(make_value( @@ -1063,6 +1076,59 @@ inline typename std::enable_if>::type } } // namespace internal +// Formatting context. +template +class basic_format_context : + public internal::context_base< + OutputIt, basic_format_context, Char> { + public: + /** The character type for the output. */ + typedef Char char_type; + + // using formatter_type = formatter; + template + struct formatter_type { typedef formatter type; }; + + private: + internal::arg_map map_; + + basic_format_context(const basic_format_context &) = delete; + void operator=(const basic_format_context &) = delete; + + typedef internal::context_base base; + typedef typename base::format_arg format_arg; + using base::get_arg; + + public: + using typename base::iterator; + + /** + Constructs a ``basic_format_context`` object. References to the arguments are + stored in the object so make sure they have appropriate lifetimes. + */ + basic_format_context(OutputIt out, basic_string_view format_str, + basic_format_args ctx_args, + internal::locale_ref loc = internal::locale_ref()) + : base(out, format_str, ctx_args, loc) {} + + format_arg next_arg() { + return this->do_get_arg(this->parse_context().next_arg_id()); + } + format_arg get_arg(unsigned arg_id) { return this->do_get_arg(arg_id); } + + // Checks if manual indexing is used and returns the argument with the + // specified name. + format_arg get_arg(basic_string_view name); +}; + +template +struct buffer_context { + typedef basic_format_context< + std::back_insert_iterator>, Char> type; +}; +typedef buffer_context::type format_context; +typedef buffer_context::type wformat_context; + /** \rst An array of references to arguments. It can be implicitly converted into @@ -1088,17 +1154,17 @@ class format_arg_store { friend class basic_format_args; - static FMT_CONSTEXPR11 long long get_types() { + static FMT_CONSTEXPR11 unsigned long long get_types() { return IS_PACKED ? - static_cast(internal::get_types()) : - -static_cast(NUM_ARGS); + internal::get_types() : + internal::is_unpacked_bit | NUM_ARGS; } public: #if FMT_USE_CONSTEXPR11 - static FMT_CONSTEXPR11 long long TYPES = get_types(); + static FMT_CONSTEXPR11 unsigned long long TYPES = get_types(); #else - static const long long TYPES; + static const unsigned long long TYPES; #endif #if (FMT_GCC_VERSION && FMT_GCC_VERSION <= 405) || \ @@ -1117,7 +1183,8 @@ class format_arg_store { #if !FMT_USE_CONSTEXPR11 template -const long long format_arg_store::TYPES = get_types(); +const unsigned long long format_arg_store::TYPES = + get_types(); #endif /** @@ -1127,17 +1194,9 @@ const long long format_arg_store::TYPES = get_types(); can be omitted in which case it defaults to `~fmt::context`. \endrst */ -template +template inline format_arg_store - make_format_args(const Args & ... args) { - return format_arg_store(args...); -} - -template -inline format_arg_store - make_format_args(const Args & ... args) { - return format_arg_store(args...); -} + make_format_args(const Args &... args) { return {args...}; } /** Formatting arguments. */ template @@ -1160,11 +1219,12 @@ class basic_format_args { const format_arg *args_; }; + bool is_packed() const { return (types_ & internal::is_unpacked_bit) == 0; } + typename internal::type type(unsigned index) const { unsigned shift = index * 4; - unsigned long long mask = 0xf; return static_cast( - (types_ & (mask << shift)) >> shift); + (types_ & (0xfull << shift)) >> shift); } friend class internal::arg_map; @@ -1174,10 +1234,8 @@ class basic_format_args { format_arg do_get(size_type index) const { format_arg arg; - long long signed_types = static_cast(types_); - if (signed_types < 0) { - unsigned long long num_args = - static_cast(-signed_types); + if (!is_packed()) { + auto num_args = max_size(); if (index < num_args) arg = args_[index]; return arg; @@ -1212,7 +1270,7 @@ class basic_format_args { \endrst */ basic_format_args(const format_arg *args, size_type count) - : types_(-static_cast(count)) { + : types_(internal::is_unpacked_bit | count) { set_data(args); } @@ -1224,34 +1282,52 @@ class basic_format_args { return arg; } - unsigned max_size() const { - long long signed_types = static_cast(types_); - return static_cast( - signed_types < 0 ? - -signed_types : static_cast(internal::max_packed_args)); + size_type max_size() const { + unsigned long long max_packed = internal::max_packed_args; + return static_cast( + is_packed() ? max_packed : types_ & ~internal::is_unpacked_bit); } }; /** An alias to ``basic_format_args``. */ // It is a separate type rather than a typedef to make symbols readable. -struct format_args: basic_format_args { +struct format_args : basic_format_args { template - format_args(Args && ... arg) + format_args(Args &&... arg) : basic_format_args(std::forward(arg)...) {} }; struct wformat_args : basic_format_args { template - wformat_args(Args && ... arg) + wformat_args(Args &&... arg) : basic_format_args(std::forward(arg)...) {} }; +#define FMT_ENABLE_IF_T(B, T) typename std::enable_if::type + +#ifndef FMT_USE_ALIAS_TEMPLATES +# define FMT_USE_ALIAS_TEMPLATES FMT_HAS_FEATURE(cxx_alias_templates) +#endif +#if FMT_USE_ALIAS_TEMPLATES +/** String's character type. */ +template +using char_t = FMT_ENABLE_IF_T( + internal::is_string::value, typename internal::char_t::type); +#define FMT_CHAR(S) fmt::char_t +#else +template +struct char_t : std::enable_if< + internal::is_string::value, typename internal::char_t::type> {}; +#define FMT_CHAR(S) typename char_t::type +#endif + namespace internal { template struct named_arg_base { basic_string_view name; // Serialized value. - mutable char data[sizeof(basic_format_arg)]; + mutable char data[ + sizeof(basic_format_arg::type>)]; named_arg_base(basic_string_view nm) : name(nm) {} @@ -1270,6 +1346,36 @@ struct named_arg : named_arg_base { named_arg(basic_string_view name, const T &val) : named_arg_base(name), value(val) {} }; + +template +inline typename std::enable_if::value>::type + check_format_string(const S &) {} +template +typename std::enable_if::value>::type + check_format_string(S); + +template +struct checked_args : format_arg_store< + typename buffer_context::type, Args...> { + typedef typename buffer_context::type context; + + checked_args(const S &format_str, const Args &... args): + format_arg_store(args...) { + internal::check_format_string(format_str); + } + + basic_format_args operator*() const { return *this; } +}; + +template +std::basic_string vformat( + basic_string_view format_str, + basic_format_args::type> args); + +template +typename buffer_context::type::iterator vformat_to( + internal::basic_buffer &buf, basic_string_view format_str, + basic_format_args::type> args); } /** @@ -1283,142 +1389,55 @@ struct named_arg : named_arg_base { */ template inline internal::named_arg arg(string_view name, const T &arg) { - return internal::named_arg(name, arg); + return {name, arg}; } template inline internal::named_arg arg(wstring_view name, const T &arg) { - return internal::named_arg(name, arg); + return {name, arg}; } -// This function template is deleted intentionally to disable nested named -// arguments as in ``format("{}", arg("a", arg("b", 42)))``. +// Disable nested named arguments, e.g. ``arg("a", arg("b", 42))``. template void arg(S, internal::named_arg) = delete; -// A base class for compile-time strings. It is defined in the fmt namespace to -// make formatting functions visible via ADL, e.g. format(fmt("{}"), 42). -struct compile_string {}; - -namespace internal { -// If S is a format string type, format_string_traints::char_type gives its -// character type. -template -struct format_string_traits { - private: - // Use constructability as a way to detect if format_string_traits is - // specialized because other methods are broken on MSVC2013. - format_string_traits(); -}; - -template -struct format_string_traits_base { typedef Char char_type; }; - -template -struct format_string_traits : format_string_traits_base {}; - -template -struct format_string_traits : format_string_traits_base {}; - -template -struct format_string_traits : format_string_traits_base {}; - -template -struct format_string_traits : format_string_traits_base {}; - -template -struct format_string_traits> : - format_string_traits_base {}; - -template -struct format_string_traits< - S, typename std::enable_if, S>::value>::type> : - format_string_traits_base {}; - -template -struct is_format_string : - std::integral_constant< - bool, std::is_constructible>::value> {}; - -template -struct is_compile_string : - std::integral_constant::value> {}; - -template -inline typename std::enable_if::value>::type - check_format_string(const S &) {} -template -typename std::enable_if::value>::type - check_format_string(S); - -template -std::basic_string vformat( - basic_string_view format_str, - basic_format_args::type> args); -} // namespace internal - -format_context::iterator vformat_to( - internal::buffer &buf, string_view format_str, format_args args); -wformat_context::iterator vformat_to( - internal::wbuffer &buf, wstring_view format_str, wformat_args args); - template -struct is_contiguous : std::false_type {}; +struct is_contiguous: std::false_type {}; template -struct is_contiguous> : std::true_type {}; +struct is_contiguous >: std::true_type {}; template -struct is_contiguous> : std::true_type {}; +struct is_contiguous >: std::true_type {}; /** Formats a string and writes the output to ``out``. */ -template +template typename std::enable_if< - is_contiguous::value, std::back_insert_iterator>::type - vformat_to(std::back_insert_iterator out, - string_view format_str, format_args args) { + is_contiguous::value, std::back_insert_iterator>::type + vformat_to( + std::back_insert_iterator out, + const S &format_str, + basic_format_args::type> args) { internal::container_buffer buf(internal::get_container(out)); - vformat_to(buf, format_str, args); + internal::vformat_to(buf, to_string_view(format_str), args); return out; } -template -typename std::enable_if< - is_contiguous::value, std::back_insert_iterator>::type - vformat_to(std::back_insert_iterator out, - wstring_view format_str, wformat_args args) { - internal::container_buffer buf(internal::get_container(out)); - vformat_to(buf, format_str, args); - return out; -} - -template +template inline typename std::enable_if< - is_contiguous::value, std::back_insert_iterator>::type - format_to(std::back_insert_iterator out, - string_view format_str, const Args & ... args) { - format_arg_store as{args...}; - return vformat_to(out, format_str, as); + is_contiguous::value && internal::is_string::value, + std::back_insert_iterator>::type + format_to(std::back_insert_iterator out, const S &format_str, + const Args &... args) { + internal::checked_args ca(format_str, args...); + return vformat_to(out, to_string_view(format_str), *ca); } -template -inline typename std::enable_if< - is_contiguous::value, std::back_insert_iterator>::type - format_to(std::back_insert_iterator out, - wstring_view format_str, const Args & ... args) { - return vformat_to(out, format_str, - make_format_args(args...)); -} - -template < - typename String, - typename Char = typename internal::format_string_traits::char_type> +template inline std::basic_string vformat( - const String &format_str, + const S &format_str, basic_format_args::type> args) { - // Convert format string to string_view to reduce the number of overloads. - return internal::vformat(basic_string_view(format_str), args); + return internal::vformat(to_string_view(format_str), args); } /** @@ -1431,19 +1450,12 @@ inline std::basic_string vformat( std::string message = fmt::format("The answer is {}", 42); \endrst */ -template -inline std::basic_string< - typename internal::format_string_traits::char_type> - format(const String &format_str, const Args & ... args) { - internal::check_format_string(format_str); - // This should be just - // return vformat(format_str, make_format_args(args...)); - // but gcc has trouble optimizing the latter, so break it down. - typedef typename internal::format_string_traits::char_type char_t; - typedef typename buffer_context::type context_t; - format_arg_store as{args...}; +template +inline std::basic_string format( + const S &format_str, const Args &... args) { return internal::vformat( - basic_string_view(format_str), basic_format_args(as)); + to_string_view(format_str), + *internal::checked_args(format_str, args...)); } FMT_API void vprint(std::FILE *f, string_view format_str, format_args args); @@ -1451,27 +1463,20 @@ FMT_API void vprint(std::FILE *f, wstring_view format_str, wformat_args args); /** \rst - Prints formatted data to the file *f*. + Prints formatted data to the file *f*. For wide format strings, + *f* should be in wide-oriented mode set via ``fwide(f, 1)`` or + ``_setmode(_fileno(f), _O_U8TEXT)`` on Windows. **Example**:: fmt::print(stderr, "Don't {}!", "panic"); \endrst */ -template -inline void print(std::FILE *f, string_view format_str, const Args & ... args) { - format_arg_store as(args...); - vprint(f, format_str, as); -} -/** - Prints formatted data to the file *f* which should be in wide-oriented mode - set via ``fwide(f, 1)`` or ``_setmode(_fileno(f), _O_U8TEXT)`` on Windows. - */ -template -inline void print(std::FILE *f, wstring_view format_str, - const Args & ... args) { - format_arg_store as(args...); - vprint(f, format_str, as); +template +inline FMT_ENABLE_IF_T(internal::is_string::value, void) + print(std::FILE *f, const S &format_str, const Args &... args) { + vprint(f, to_string_view(format_str), + internal::checked_args(format_str, args...)); } FMT_API void vprint(string_view format_str, format_args args); @@ -1486,16 +1491,11 @@ FMT_API void vprint(wstring_view format_str, wformat_args args); fmt::print("Elapsed time: {0:.2f} seconds", 1.23); \endrst */ -template -inline void print(string_view format_str, const Args & ... args) { - format_arg_store as{args...}; - vprint(format_str, as); -} - -template -inline void print(wstring_view format_str, const Args & ... args) { - format_arg_store as(args...); - vprint(format_str, as); +template +inline FMT_ENABLE_IF_T(internal::is_string::value, void) + print(const S &format_str, const Args &... args) { + vprint(to_string_view(format_str), + internal::checked_args(format_str, args...)); } FMT_END_NAMESPACE diff --git a/include/spdlog/fmt/bundled/format-inl.h b/include/spdlog/fmt/bundled/format-inl.h index 56c4d581..552c9430 100644 --- a/include/spdlog/fmt/bundled/format-inl.h +++ b/include/spdlog/fmt/bundled/format-inl.h @@ -136,12 +136,14 @@ int safe_strerror( ERANGE : result; } +#if !FMT_MSC_VER // Fallback to strerror if strerror_r and strerror_s are not available. int fallback(internal::null<>) { errno = 0; buffer_ = strerror(error_code_); return errno; } +#endif public: dispatcher(int err_code, char *&buf, std::size_t buf_size) @@ -170,7 +172,7 @@ void format_error_code(internal::buffer &out, int error_code, abs_value = 0 - abs_value; ++error_code_size; } - error_code_size += internal::count_digits(abs_value); + error_code_size += internal::to_unsigned(internal::count_digits(abs_value)); writer w(out); if (message.size() <= inline_buffer_size - error_code_size) { w.write(message); @@ -192,34 +194,39 @@ void report_error(FormatFunc func, int error_code, } } // namespace -#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR) -class locale { - private: - std::locale locale_; - - public: - explicit locale(std::locale loc = std::locale()) : locale_(loc) {} - std::locale get() { return locale_; } -}; - -FMT_FUNC size_t internal::count_code_points(u8string_view s) { +FMT_FUNC size_t internal::count_code_points(basic_string_view s) { const char8_t *data = s.data(); - int num_code_points = 0; + size_t num_code_points = 0; for (size_t i = 0, size = s.size(); i != size; ++i) { - if ((data[i].value & 0xc0) != 0x80) + if ((data[i] & 0xc0) != 0x80) ++num_code_points; } return num_code_points; } +#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR) +namespace internal { + +template +locale_ref::locale_ref(const Locale &loc) : locale_(&loc) { + static_assert(std::is_same::value, ""); +} + +template +Locale locale_ref::get() const { + static_assert(std::is_same::value, ""); + return locale_ ? *static_cast(locale_) : std::locale(); +} + template -FMT_FUNC Char internal::thousands_sep(locale_provider *lp) { - std::locale loc = lp ? lp->locale().get() : std::locale(); - return std::use_facet>(loc).thousands_sep(); +FMT_FUNC Char thousands_sep_impl(locale_ref loc) { + return std::use_facet >( + loc.get()).thousands_sep(); +} } #else template -FMT_FUNC Char internal::thousands_sep(locale_provider *lp) { +FMT_FUNC Char internal::thousands_sep_impl(locale_ref) { return FMT_STATIC_THOUSANDS_SEPARATOR; } #endif @@ -236,19 +243,19 @@ FMT_FUNC void system_error::init( namespace internal { template int char_traits::format_float( - char *buffer, std::size_t size, const char *format, int precision, T value) { + char *buf, std::size_t size, const char *format, int precision, T value) { return precision < 0 ? - FMT_SNPRINTF(buffer, size, format, value) : - FMT_SNPRINTF(buffer, size, format, precision, value); + FMT_SNPRINTF(buf, size, format, value) : + FMT_SNPRINTF(buf, size, format, precision, value); } template int char_traits::format_float( - wchar_t *buffer, std::size_t size, const wchar_t *format, int precision, + wchar_t *buf, std::size_t size, const wchar_t *format, int precision, T value) { return precision < 0 ? - FMT_SWPRINTF(buffer, size, format, value) : - FMT_SWPRINTF(buffer, size, format, precision, value); + FMT_SWPRINTF(buf, size, format, value) : + FMT_SWPRINTF(buf, size, format, precision, value); } template @@ -337,6 +344,8 @@ const int16_t basic_data::POW10_EXPONENTS[] = { 827, 853, 880, 907, 933, 960, 986, 1013, 1039, 1066 }; +template const char basic_data::FOREGROUND_COLOR[] = "\x1b[38;2;"; +template const char basic_data::BACKGROUND_COLOR[] = "\x1b[48;2;"; template const char basic_data::RESET_COLOR[] = "\x1b[0m"; template const wchar_t basic_data::WRESET_COLOR[] = L"\x1b[0m"; @@ -363,7 +372,7 @@ class fp { sizeof(significand_type) * char_size; fp(): f(0), e(0) {} - fp(uint64_t f, int e): f(f), e(e) {} + fp(uint64_t f_val, int e_val): f(f_val), e(e_val) {} // Constructs fp from an IEEE754 double. It is a template to prevent compile // errors on platforms where double is not IEEE754. @@ -454,19 +463,28 @@ FMT_FUNC fp get_cached_power(int min_exponent, int &pow10_exponent) { return fp(data::POW10_SIGNIFICANDS[index], data::POW10_EXPONENTS[index]); } +FMT_FUNC bool grisu2_round( + char *buf, int &size, int max_digits, uint64_t delta, + uint64_t remainder, uint64_t exp, uint64_t diff, int &exp10) { + while (remainder < diff && delta - remainder >= exp && + (remainder + exp < diff || diff - remainder > remainder + exp - diff)) { + --buf[size - 1]; + remainder += exp; + } + if (size > max_digits) { + --size; + ++exp10; + if (buf[size] >= '5') + return false; + } + return true; +} + // Generates output using Grisu2 digit-gen algorithm. -FMT_FUNC void grisu2_gen_digits( - const fp &scaled_value, const fp &scaled_upper, uint64_t delta, - char *buffer, size_t &size, int &dec_exp) { - internal::fp one(1ull << -scaled_upper.e, scaled_upper.e); - // hi (p1 in Grisu) contains the most significant digits of scaled_upper. - // hi = floor(scaled_upper / one). - uint32_t hi = static_cast(scaled_upper.f >> -one.e); - // lo (p2 in Grisu) contains the least significants digits of scaled_upper. - // lo = scaled_upper mod 1. - uint64_t lo = scaled_upper.f & (one.f - 1); - size = 0; - auto exp = count_digits(hi); // kappa in Grisu. +FMT_FUNC bool grisu2_gen_digits( + char *buf, int &size, uint32_t hi, uint64_t lo, int &exp, + uint64_t delta, const fp &one, const fp &diff, int max_digits) { + // Generate digits for the most significant part (hi). while (exp > 0) { uint32_t digit = 0; // This optimization by miloyip reduces the number of integer divisions by @@ -486,148 +504,32 @@ FMT_FUNC void grisu2_gen_digits( FMT_ASSERT(false, "invalid number of digits"); } if (digit != 0 || size != 0) - buffer[size++] = static_cast('0' + digit); + buf[size++] = static_cast('0' + digit); --exp; uint64_t remainder = (static_cast(hi) << -one.e) + lo; - if (remainder <= delta) { - dec_exp += exp; - // TODO: use scaled_value - (void)scaled_value; - return; + if (remainder <= delta || size > max_digits) { + return grisu2_round( + buf, size, max_digits, delta, remainder, + static_cast(data::POWERS_OF_10_32[exp]) << -one.e, + diff.f, exp); } } + // Generate digits for the least significant part (lo). for (;;) { lo *= 10; delta *= 10; char digit = static_cast(lo >> -one.e); if (digit != 0 || size != 0) - buffer[size++] = static_cast('0' + digit); + buf[size++] = static_cast('0' + digit); lo &= one.f - 1; --exp; - if (lo < delta) { - dec_exp += exp; - return; + if (lo < delta || size > max_digits) { + return grisu2_round(buf, size, max_digits, delta, lo, one.f, + diff.f * data::POWERS_OF_10_32[-exp], exp); } } } -FMT_FUNC void grisu2_format_positive(double value, char *buffer, size_t &size, - int &dec_exp) { - FMT_ASSERT(value > 0, "value is nonpositive"); - fp fp_value(value); - fp lower, upper; // w^- and w^+ in the Grisu paper. - fp_value.compute_boundaries(lower, upper); - // Find a cached power of 10 close to 1 / upper. - const int min_exp = -60; // alpha in Grisu. - auto dec_pow = get_cached_power( // \tilde{c}_{-k} in Grisu. - min_exp - (upper.e + fp::significand_size), dec_exp); - dec_exp = -dec_exp; - fp_value.normalize(); - fp scaled_value = fp_value * dec_pow; - fp scaled_lower = lower * dec_pow; // \tilde{M}^- in Grisu. - fp scaled_upper = upper * dec_pow; // \tilde{M}^+ in Grisu. - ++scaled_lower.f; // \tilde{M}^- + 1 ulp -> M^-_{\uparrow}. - --scaled_upper.f; // \tilde{M}^+ - 1 ulp -> M^+_{\downarrow}. - uint64_t delta = scaled_upper.f - scaled_lower.f; - grisu2_gen_digits(scaled_value, scaled_upper, delta, buffer, size, dec_exp); -} - -FMT_FUNC void round(char *buffer, size_t &size, int &exp, - int digits_to_remove) { - size -= to_unsigned(digits_to_remove); - exp += digits_to_remove; - int digit = buffer[size] - '0'; - // TODO: proper rounding and carry - if (digit > 5 || (digit == 5 && (digits_to_remove > 1 || - (buffer[size - 1] - '0') % 2) != 0)) { - ++buffer[size - 1]; - } -} - -// Writes the exponent exp in the form "[+-]d{1,3}" to buffer. -FMT_FUNC char *write_exponent(char *buffer, int exp) { - FMT_ASSERT(-1000 < exp && exp < 1000, "exponent out of range"); - if (exp < 0) { - *buffer++ = '-'; - exp = -exp; - } else { - *buffer++ = '+'; - } - if (exp >= 100) { - *buffer++ = static_cast('0' + exp / 100); - exp %= 100; - const char *d = data::DIGITS + exp * 2; - *buffer++ = d[0]; - *buffer++ = d[1]; - } else { - const char *d = data::DIGITS + exp * 2; - *buffer++ = d[0]; - *buffer++ = d[1]; - } - return buffer; -} - -FMT_FUNC void format_exp_notation( - char *buffer, size_t &size, int exp, int precision, bool upper) { - // Insert a decimal point after the first digit and add an exponent. - std::memmove(buffer + 2, buffer + 1, size - 1); - buffer[1] = '.'; - exp += static_cast(size) - 1; - int num_digits = precision - static_cast(size) + 1; - if (num_digits > 0) { - std::uninitialized_fill_n(buffer + size + 1, num_digits, '0'); - size += to_unsigned(num_digits); - } else if (num_digits < 0) { - round(buffer, size, exp, -num_digits); - } - char *p = buffer + size + 1; - *p++ = upper ? 'E' : 'e'; - size = to_unsigned(write_exponent(p, exp) - buffer); -} - -// Prettifies the output of the Grisu2 algorithm. -// The number is given as v = buffer * 10^exp. -FMT_FUNC void grisu2_prettify(char *buffer, size_t &size, int exp, - int precision, bool upper) { - // pow(10, full_exp - 1) <= v <= pow(10, full_exp). - int int_size = static_cast(size); - int full_exp = int_size + exp; - const int exp_threshold = 21; - if (int_size <= full_exp && full_exp <= exp_threshold) { - // 1234e7 -> 12340000000[.0+] - std::uninitialized_fill_n(buffer + int_size, full_exp - int_size, '0'); - char *p = buffer + full_exp; - if (precision > 0) { - *p++ = '.'; - std::uninitialized_fill_n(p, precision, '0'); - p += precision; - } - size = to_unsigned(p - buffer); - } else if (0 < full_exp && full_exp <= exp_threshold) { - // 1234e-2 -> 12.34[0+] - int fractional_size = -exp; - std::memmove(buffer + full_exp + 1, buffer + full_exp, - to_unsigned(fractional_size)); - buffer[full_exp] = '.'; - int num_zeros = precision - fractional_size; - if (num_zeros > 0) { - std::uninitialized_fill_n(buffer + size + 1, num_zeros, '0'); - size += to_unsigned(num_zeros); - } - ++size; - } else if (-6 < full_exp && full_exp <= 0) { - // 1234e-6 -> 0.001234 - int offset = 2 - full_exp; - std::memmove(buffer + offset, buffer, size); - buffer[0] = '0'; - buffer[1] = '.'; - std::uninitialized_fill_n(buffer + 2, -full_exp, '0'); - size = to_unsigned(int_size + offset); - } else { - format_exp_notation(buffer, size, exp, precision, upper); - } -} - #if FMT_CLANG_VERSION # define FMT_FALLTHROUGH [[clang::fallthrough]]; #elif FMT_GCC_VERSION >= 700 @@ -636,58 +538,270 @@ FMT_FUNC void grisu2_prettify(char *buffer, size_t &size, int exp, # define FMT_FALLTHROUGH #endif -// Formats a nonnegative value using Grisu2 algorithm. Grisu2 doesn't give any -// guarantees on the shortness of the result. -FMT_FUNC void grisu2_format(double value, char *buffer, size_t &size, char type, - int precision, bool write_decimal_point) { - FMT_ASSERT(value >= 0, "value is negative"); - int dec_exp = 0; // K in Grisu. - if (value > 0) { - grisu2_format_positive(value, buffer, size, dec_exp); +struct gen_digits_params { + int num_digits; + bool fixed; + bool upper; + bool trailing_zeros; +}; + +struct prettify_handler { + char *data; + ptrdiff_t size; + buffer &buf; + + explicit prettify_handler(buffer &b, ptrdiff_t n) + : data(b.data()), size(n), buf(b) {} + ~prettify_handler() { + assert(buf.size() >= to_unsigned(size)); + buf.resize(to_unsigned(size)); + } + + template + void insert(ptrdiff_t pos, ptrdiff_t n, F f) { + std::memmove(data + pos + n, data + pos, to_unsigned(size - pos)); + f(data + pos); + size += n; + } + + void insert(ptrdiff_t pos, char c) { + std::memmove(data + pos + 1, data + pos, to_unsigned(size - pos)); + data[pos] = c; + ++size; + } + + void append(ptrdiff_t n, char c) { + std::uninitialized_fill_n(data + size, n, c); + size += n; + } + + void append(char c) { data[size++] = c; } + + void remove_trailing(char c) { + while (data[size - 1] == c) --size; + } +}; + +// Writes the exponent exp in the form "[+-]d{2,3}" to buffer. +template +FMT_FUNC void write_exponent(int exp, Handler &&h) { + FMT_ASSERT(-1000 < exp && exp < 1000, "exponent out of range"); + if (exp < 0) { + h.append('-'); + exp = -exp; } else { - *buffer = '0'; - size = 1; + h.append('+'); } - const int default_precision = 6; - if (precision < 0) - precision = default_precision; - bool upper = false; - switch (type) { - case 'G': - upper = true; - FMT_FALLTHROUGH - case '\0': case 'g': { - int digits_to_remove = static_cast(size) - precision; - if (digits_to_remove > 0) { - round(buffer, size, dec_exp, digits_to_remove); - // Remove trailing zeros. - while (size > 0 && buffer[size - 1] == '0') { - --size; - ++dec_exp; - } - } - precision = 0; - break; + if (exp >= 100) { + h.append(static_cast('0' + exp / 100)); + exp %= 100; + const char *d = data::DIGITS + exp * 2; + h.append(d[0]); + h.append(d[1]); + } else { + const char *d = data::DIGITS + exp * 2; + h.append(d[0]); + h.append(d[1]); } - case 'F': - upper = true; - FMT_FALLTHROUGH - case 'f': { - int digits_to_remove = -dec_exp - precision; - if (digits_to_remove > 0) { - if (digits_to_remove >= static_cast(size)) - digits_to_remove = static_cast(size) - 1; - round(buffer, size, dec_exp, digits_to_remove); - } - break; +} + +struct fill { + size_t n; + void operator()(char *buf) const { + buf[0] = '0'; + buf[1] = '.'; + std::uninitialized_fill_n(buf + 2, n, '0'); } - case 'e': case 'E': - format_exp_notation(buffer, size, dec_exp, precision, type == 'E'); +}; + +// The number is given as v = f * pow(10, exp), where f has size digits. +template +FMT_FUNC void grisu2_prettify(const gen_digits_params ¶ms, + int size, int exp, Handler &&handler) { + if (!params.fixed) { + // Insert a decimal point after the first digit and add an exponent. + handler.insert(1, '.'); + exp += size - 1; + if (size < params.num_digits) + handler.append(params.num_digits - size, '0'); + handler.append(params.upper ? 'E' : 'e'); + write_exponent(exp, handler); return; } - if (write_decimal_point && precision < 1) - precision = 1; - grisu2_prettify(buffer, size, dec_exp, precision, upper); + // pow(10, full_exp - 1) <= v <= pow(10, full_exp). + int full_exp = size + exp; + const int exp_threshold = 21; + if (size <= full_exp && full_exp <= exp_threshold) { + // 1234e7 -> 12340000000[.0+] + handler.append(full_exp - size, '0'); + int num_zeros = params.num_digits - full_exp; + if (num_zeros > 0 && params.trailing_zeros) { + handler.append('.'); + handler.append(num_zeros, '0'); + } + } else if (full_exp > 0) { + // 1234e-2 -> 12.34[0+] + handler.insert(full_exp, '.'); + if (!params.trailing_zeros) { + // Remove trailing zeros. + handler.remove_trailing('0'); + } else if (params.num_digits > size) { + // Add trailing zeros. + ptrdiff_t num_zeros = params.num_digits - size; + handler.append(num_zeros, '0'); + } + } else { + // 1234e-6 -> 0.001234 + handler.insert(0, 2 - full_exp, fill{to_unsigned(-full_exp)}); + } +} + +struct char_counter { + ptrdiff_t size; + + template + void insert(ptrdiff_t, ptrdiff_t n, F) { size += n; } + void insert(ptrdiff_t, char) { ++size; } + void append(ptrdiff_t n, char) { size += n; } + void append(char) { ++size; } + void remove_trailing(char) {} +}; + +// Converts format specifiers into parameters for digit generation and computes +// output buffer size for a number in the range [pow(10, exp - 1), pow(10, exp) +// or 0 if exp == 1. +FMT_FUNC gen_digits_params process_specs(const core_format_specs &specs, + int exp, buffer &buf) { + auto params = gen_digits_params(); + int num_digits = specs.precision >= 0 ? specs.precision : 6; + switch (specs.type) { + case 'G': + params.upper = true; + FMT_FALLTHROUGH + case '\0': case 'g': + params.trailing_zeros = (specs.flags & HASH_FLAG) != 0; + if (-4 <= exp && exp < num_digits + 1) { + params.fixed = true; + if (!specs.type && params.trailing_zeros && exp >= 0) + num_digits = exp + 1; + } + break; + case 'F': + params.upper = true; + FMT_FALLTHROUGH + case 'f': { + params.fixed = true; + params.trailing_zeros = true; + int adjusted_min_digits = num_digits + exp; + if (adjusted_min_digits > 0) + num_digits = adjusted_min_digits; + break; + } + case 'E': + params.upper = true; + FMT_FALLTHROUGH + case 'e': + ++num_digits; + break; + } + params.num_digits = num_digits; + char_counter counter{num_digits}; + grisu2_prettify(params, params.num_digits, exp - num_digits, counter); + buf.resize(to_unsigned(counter.size)); + return params; +} + +template +FMT_FUNC typename std::enable_if::type + grisu2_format(Double value, buffer &buf, core_format_specs specs) { + FMT_ASSERT(value >= 0, "value is negative"); + if (value == 0) { + gen_digits_params params = process_specs(specs, 1, buf); + const size_t size = 1; + buf[0] = '0'; + grisu2_prettify(params, size, 0, prettify_handler(buf, size)); + return true; + } + + fp fp_value(value); + fp lower, upper; // w^- and w^+ in the Grisu paper. + fp_value.compute_boundaries(lower, upper); + + // Find a cached power of 10 close to 1 / upper and use it to scale upper. + const int min_exp = -60; // alpha in Grisu. + int cached_exp = 0; // K in Grisu. + auto cached_pow = get_cached_power( // \tilde{c}_{-k} in Grisu. + min_exp - (upper.e + fp::significand_size), cached_exp); + cached_exp = -cached_exp; + upper = upper * cached_pow; // \tilde{M}^+ in Grisu. + --upper.f; // \tilde{M}^+ - 1 ulp -> M^+_{\downarrow}. + fp one(1ull << -upper.e, upper.e); + // hi (p1 in Grisu) contains the most significant digits of scaled_upper. + // hi = floor(upper / one). + uint32_t hi = static_cast(upper.f >> -one.e); + int exp = count_digits(hi); // kappa in Grisu. + gen_digits_params params = process_specs(specs, cached_exp + exp, buf); + fp_value.normalize(); + fp scaled_value = fp_value * cached_pow; + lower = lower * cached_pow; // \tilde{M}^- in Grisu. + ++lower.f; // \tilde{M}^- + 1 ulp -> M^-_{\uparrow}. + uint64_t delta = upper.f - lower.f; + fp diff = upper - scaled_value; // wp_w in Grisu. + // lo (p2 in Grisu) contains the least significants digits of scaled_upper. + // lo = supper % one. + uint64_t lo = upper.f & (one.f - 1); + int size = 0; + if (!grisu2_gen_digits(buf.data(), size, hi, lo, exp, delta, one, diff, + params.num_digits)) { + buf.clear(); + return false; + } + grisu2_prettify(params, size, cached_exp + exp, prettify_handler(buf, size)); + return true; +} + +template +void sprintf_format(Double value, internal::buffer &buf, + core_format_specs spec) { + // Buffer capacity must be non-zero, otherwise MSVC's vsnprintf_s will fail. + FMT_ASSERT(buf.capacity() != 0, "empty buffer"); + + // Build format string. + enum { MAX_FORMAT_SIZE = 10}; // longest format: %#-*.*Lg + char format[MAX_FORMAT_SIZE]; + char *format_ptr = format; + *format_ptr++ = '%'; + if (spec.has(HASH_FLAG)) + *format_ptr++ = '#'; + if (spec.precision >= 0) { + *format_ptr++ = '.'; + *format_ptr++ = '*'; + } + if (std::is_same::value) + *format_ptr++ = 'L'; + *format_ptr++ = spec.type; + *format_ptr = '\0'; + + // Format using snprintf. + char *start = FMT_NULL; + for (;;) { + std::size_t buffer_size = buf.capacity(); + start = &buf[0]; + int result = internal::char_traits::format_float( + start, buffer_size, format, spec.precision, value); + if (result >= 0) { + unsigned n = internal::to_unsigned(result); + if (n < buf.capacity()) { + buf.resize(n); + break; // The buffer is large enough - continue with formatting. + } + buf.reserve(n + 1); + } else { + // If result is negative we ask to increase the capacity by at least 1, + // but as std::vector, the buffer grows exponentially. + buf.reserve(buf.capacity() + 1); + } + } } } // namespace internal @@ -812,11 +926,6 @@ FMT_FUNC void format_system_error( format_error_code(out, error_code, message); } -template -void basic_fixed_buffer::grow(std::size_t) { - FMT_THROW(std::runtime_error("buffer overflow")); -} - FMT_FUNC void internal::error_handler::on_error(const char *message) { FMT_THROW(format_error(message)); } @@ -835,13 +944,14 @@ FMT_FUNC void report_windows_error( FMT_FUNC void vprint(std::FILE *f, string_view format_str, format_args args) { memory_buffer buffer; - vformat_to(buffer, format_str, args); + internal::vformat_to(buffer, format_str, + basic_format_args::type>(args)); std::fwrite(buffer.data(), 1, buffer.size(), f); } FMT_FUNC void vprint(std::FILE *f, wstring_view format_str, wformat_args args) { wmemory_buffer buffer; - vformat_to(buffer, format_str, args); + internal::vformat_to(buffer, format_str, args); std::fwrite(buffer.data(), sizeof(wchar_t), buffer.size(), f); } @@ -853,10 +963,6 @@ FMT_FUNC void vprint(wstring_view format_str, wformat_args args) { vprint(stdout, format_str, args); } -#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR) -FMT_FUNC locale locale_provider::locale() { return fmt::locale(); } -#endif - FMT_END_NAMESPACE #ifdef _MSC_VER diff --git a/include/spdlog/fmt/bundled/format.h b/include/spdlog/fmt/bundled/format.h index 9f522f39..1bb24a52 100644 --- a/include/spdlog/fmt/bundled/format.h +++ b/include/spdlog/fmt/bundled/format.h @@ -66,9 +66,9 @@ // many valid cases. # pragma GCC diagnostic ignored "-Wshadow" -// Disable the warning about implicit conversions that may change the sign of -// an integer; silencing it otherwise would require many explicit casts. -# pragma GCC diagnostic ignored "-Wsign-conversion" +// Disable the warning about nonliteral format strings because we construct +// them dynamically when falling back to snprintf for FP formatting. +# pragma GCC diagnostic ignored "-Wformat-nonliteral" #endif # if FMT_CLANG_VERSION @@ -163,6 +163,7 @@ FMT_END_NAMESPACE #ifndef FMT_USE_GRISU # define FMT_USE_GRISU 0 +//# define FMT_USE_GRISU std::numeric_limits::is_iec559 #endif // __builtin_clz is broken in clang with Microsoft CodeGen: @@ -177,14 +178,6 @@ FMT_END_NAMESPACE # endif #endif -// A workaround for gcc 4.4 that doesn't support union members with ctors. -#if (FMT_GCC_VERSION && FMT_GCC_VERSION <= 404) || \ - (FMT_MSC_VER && FMT_MSC_VER <= 1800) -# define FMT_UNION struct -#else -# define FMT_UNION union -#endif - // Some compilers masquerade as both MSVC and GCC-likes or otherwise support // __builtin_clz and __builtin_clzll, so only define FMT_BUILTIN_CLZ using the // MSVC intrinsics if the clz and clzll builtins are not available. @@ -278,24 +271,13 @@ struct dummy_int { }; typedef std::numeric_limits fputil; -// Dummy implementations of system functions such as signbit and ecvt called -// if the latter are not available. -inline dummy_int signbit(...) { return dummy_int(); } -inline dummy_int _ecvt_s(...) { return dummy_int(); } +// Dummy implementations of system functions called if the latter are not +// available. inline dummy_int isinf(...) { return dummy_int(); } inline dummy_int _finite(...) { return dummy_int(); } inline dummy_int isnan(...) { return dummy_int(); } inline dummy_int _isnan(...) { return dummy_int(); } -inline bool use_grisu() { - return FMT_USE_GRISU && std::numeric_limits::is_iec559; -} - -// Formats value using Grisu2 algorithm: -// https://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf -FMT_API void grisu2_format(double value, char *buffer, size_t &size, char type, - int precision, bool write_decimal_point); - template typename Allocator::value_type *allocate(Allocator& alloc, std::size_t n) { #if __cplusplus >= 201103L || FMT_MSC_VER >= 1700 @@ -316,7 +298,7 @@ namespace std { // Standard permits specialization of std::numeric_limits. This specialization // is used to resolve ambiguity between isinf and std::isinf in glibc: // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=48891 -// and the same for isnan and signbit. +// and the same for isnan. template <> class numeric_limits : public std::numeric_limits { @@ -327,7 +309,7 @@ class numeric_limits : using namespace fmt::internal; // The resolution "priority" is: // isinf macro > std::isinf > ::isinf > fmt::internal::isinf - if (const_check(sizeof(isinf(x)) != sizeof(dummy_int))) + if (const_check(sizeof(isinf(x)) != sizeof(fmt::internal::dummy_int))) return isinf(x) != 0; return !_finite(static_cast(x)); } @@ -340,19 +322,6 @@ class numeric_limits : return isnan(x) != 0; return _isnan(static_cast(x)) != 0; } - - // Portable version of signbit. - static bool isnegative(double x) { - using namespace fmt::internal; - if (const_check(sizeof(signbit(x)) != sizeof(fmt::internal::dummy_int))) - return signbit(x) != 0; - if (x < 0) return true; - if (!isnotanumber(x)) return false; - int dec = 0, sign = 0; - char buffer[2]; // The buffer size must be >= 2 or _ecvt_s will fail. - _ecvt_s(buffer, sizeof(buffer), x, 0, &dec, &sign); - return sign != 0; - } }; } // namespace std @@ -431,48 +400,32 @@ void basic_buffer::append(const U *begin, const U *end) { } } // namespace internal +// C++20 feature test, since r346892 Clang considers char8_t a fundamental +// type in this mode. If this is the case __cpp_char8_t will be defined. +#if !defined(__cpp_char8_t) // A UTF-8 code unit type. -struct char8_t { - char value; - FMT_CONSTEXPR explicit operator bool() const FMT_NOEXCEPT { - return value != 0; - } -}; +enum char8_t: unsigned char {}; +#endif // A UTF-8 string view. class u8string_view : public basic_string_view { - private: - typedef basic_string_view base; - public: - using basic_string_view::basic_string_view; - using basic_string_view::char_type; + typedef char8_t char_type; - u8string_view(const char *s) - : base(reinterpret_cast(s)) {} - - u8string_view(const char *s, size_t count) FMT_NOEXCEPT - : base(reinterpret_cast(s), count) {} + u8string_view(const char *s): + basic_string_view(reinterpret_cast(s)) {} + u8string_view(const char *s, size_t count) FMT_NOEXCEPT: + basic_string_view(reinterpret_cast(s), count) {} }; #if FMT_USE_USER_DEFINED_LITERALS inline namespace literals { inline u8string_view operator"" _u(const char *s, std::size_t n) { - return u8string_view(s, n); + return {s, n}; } } #endif -// A wrapper around std::locale used to reduce compile times since -// is very heavy. -class locale; - -class locale_provider { - public: - virtual ~locale_provider() {} - virtual fmt::locale locale(); -}; - // The number of characters to store in the basic_memory_buffer object itself // to avoid dynamic memory allocation. enum { inline_buffer_size = 500 }; @@ -497,7 +450,7 @@ enum { inline_buffer_size = 500 }; fmt::memory_buffer out; format_to(out, "The answer is {}.", 42); - This will write the following output to the ``out`` object: + This will append the following output to the ``out`` object: .. code-block:: none @@ -522,6 +475,9 @@ class basic_memory_buffer: private Allocator, public internal::basic_buffer { void grow(std::size_t size) FMT_OVERRIDE; public: + typedef T value_type; + typedef const T &const_reference; + explicit basic_memory_buffer(const Allocator &alloc = Allocator()) : Allocator(alloc) { this->set(store_, SIZE); @@ -597,43 +553,6 @@ void basic_memory_buffer::grow(std::size_t size) { typedef basic_memory_buffer memory_buffer; typedef basic_memory_buffer wmemory_buffer; -/** - \rst - A fixed-size memory buffer. For a dynamically growing buffer use - :class:`fmt::basic_memory_buffer`. - - Trying to increase the buffer size past the initial capacity will throw - ``std::runtime_error``. - \endrst - */ -template -class basic_fixed_buffer : public internal::basic_buffer { - public: - /** - \rst - Constructs a :class:`fmt::basic_fixed_buffer` object for *array* of the - given size. - \endrst - */ - basic_fixed_buffer(Char *array, std::size_t size) { - this->set(array, size); - } - - /** - \rst - Constructs a :class:`fmt::basic_fixed_buffer` object for *array* of the - size known at compile time. - \endrst - */ - template - explicit basic_fixed_buffer(Char (&array)[SIZE]) { - this->set(array, SIZE); - } - - protected: - FMT_API void grow(std::size_t size) FMT_OVERRIDE; -}; - namespace internal { template @@ -690,98 +609,6 @@ class null_terminating_iterator; template FMT_CONSTEXPR_DECL const Char *pointer_from(null_terminating_iterator it); -// An iterator that produces a null terminator on *end. This simplifies parsing -// and allows comparing the performance of processing a null-terminated string -// vs string_view. -template -class null_terminating_iterator { - public: - typedef std::ptrdiff_t difference_type; - typedef Char value_type; - typedef const Char* pointer; - typedef const Char& reference; - typedef std::random_access_iterator_tag iterator_category; - - null_terminating_iterator() : ptr_(0), end_(0) {} - - FMT_CONSTEXPR null_terminating_iterator(const Char *ptr, const Char *end) - : ptr_(ptr), end_(end) {} - - template - FMT_CONSTEXPR explicit null_terminating_iterator(const Range &r) - : ptr_(r.begin()), end_(r.end()) {} - - FMT_CONSTEXPR null_terminating_iterator &operator=(const Char *ptr) { - assert(ptr <= end_); - ptr_ = ptr; - return *this; - } - - FMT_CONSTEXPR Char operator*() const { - return ptr_ != end_ ? *ptr_ : 0; - } - - FMT_CONSTEXPR null_terminating_iterator operator++() { - ++ptr_; - return *this; - } - - FMT_CONSTEXPR null_terminating_iterator operator++(int) { - null_terminating_iterator result(*this); - ++ptr_; - return result; - } - - FMT_CONSTEXPR null_terminating_iterator operator--() { - --ptr_; - return *this; - } - - FMT_CONSTEXPR null_terminating_iterator operator+(difference_type n) { - return null_terminating_iterator(ptr_ + n, end_); - } - - FMT_CONSTEXPR null_terminating_iterator operator-(difference_type n) { - return null_terminating_iterator(ptr_ - n, end_); - } - - FMT_CONSTEXPR null_terminating_iterator operator+=(difference_type n) { - ptr_ += n; - return *this; - } - - FMT_CONSTEXPR difference_type operator-( - null_terminating_iterator other) const { - return ptr_ - other.ptr_; - } - - FMT_CONSTEXPR bool operator!=(null_terminating_iterator other) const { - return ptr_ != other.ptr_; - } - - bool operator>=(null_terminating_iterator other) const { - return ptr_ >= other.ptr_; - } - - // This should be a friend specialization pointer_from but the latter - // doesn't compile by gcc 5.1 due to a compiler bug. - template - friend FMT_CONSTEXPR_DECL const CharT *pointer_from( - null_terminating_iterator it); - - private: - const Char *ptr_; - const Char *end_; -}; - -template -FMT_CONSTEXPR const T *pointer_from(const T *p) { return p; } - -template -FMT_CONSTEXPR const Char *pointer_from(null_terminating_iterator it) { - return it.ptr_; -} - // An output iterator that counts the number of objects written to it and // discards them. template @@ -816,35 +643,49 @@ class counting_iterator { T &operator*() const { return blackhole_; } }; -// An output iterator that truncates the output and counts the number of objects -// written to it. template -class truncating_iterator { - private: - typedef std::iterator_traits traits; - +class truncating_iterator_base { + protected: OutputIt out_; std::size_t limit_; std::size_t count_; - mutable typename traits::value_type blackhole_; + + truncating_iterator_base(OutputIt out, std::size_t limit) + : out_(out), limit_(limit), count_(0) {} public: typedef std::output_iterator_tag iterator_category; - typedef typename traits::value_type value_type; - typedef typename traits::difference_type difference_type; - typedef typename traits::pointer pointer; - typedef typename traits::reference reference; - typedef truncating_iterator _Unchecked_type; // Mark iterator as checked. - - truncating_iterator(OutputIt out, std::size_t limit) - : out_(out), limit_(limit), count_(0) {} + typedef void difference_type; + typedef void pointer; + typedef void reference; + typedef truncating_iterator_base _Unchecked_type; // Mark iterator as checked. OutputIt base() const { return out_; } std::size_t count() const { return count_; } +}; + +// An output iterator that truncates the output and counts the number of objects +// written to it. +template ::value_type>::type> +class truncating_iterator; + +template +class truncating_iterator: + public truncating_iterator_base { + typedef std::iterator_traits traits; + + mutable typename traits::value_type blackhole_; + + public: + typedef typename traits::value_type value_type; + + truncating_iterator(OutputIt out, std::size_t limit) + : truncating_iterator_base(out, limit) {} truncating_iterator& operator++() { - if (count_++ < limit_) - ++out_; + if (this->count_++ < this->limit_) + ++this->out_; return *this; } @@ -854,7 +695,29 @@ class truncating_iterator { return it; } - reference operator*() const { return count_ < limit_ ? *out_ : blackhole_; } + value_type& operator*() const { + return this->count_ < this->limit_ ? *this->out_ : blackhole_; + } +}; + +template +class truncating_iterator: + public truncating_iterator_base { + public: + typedef typename OutputIt::container_type::value_type value_type; + + truncating_iterator(OutputIt out, std::size_t limit) + : truncating_iterator_base(out, limit) {} + + truncating_iterator& operator=(value_type val) { + if (this->count_++ < this->limit_) + this->out_ = val; + return *this; + } + + truncating_iterator& operator++() { return *this; } + truncating_iterator& operator++(int) { return *this; } + truncating_iterator& operator*() { return *this; } }; // Returns true if value is negative, false otherwise. @@ -888,6 +751,8 @@ struct FMT_API basic_data { static const uint64_t POW10_SIGNIFICANDS[]; static const int16_t POW10_EXPONENTS[]; static const char DIGITS[]; + static const char FOREGROUND_COLOR[]; + static const char BACKGROUND_COLOR[]; static const char RESET_COLOR[]; static const wchar_t WRESET_COLOR[]; }; @@ -901,16 +766,16 @@ typedef basic_data<> data; #ifdef FMT_BUILTIN_CLZLL // Returns the number of decimal digits in n. Leading zeros are not counted // except for n == 0 in which case count_digits returns 1. -inline unsigned count_digits(uint64_t n) { +inline int count_digits(uint64_t n) { // Based on http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10 // and the benchmark https://github.com/localvoid/cxx-benchmark-count-digits. int t = (64 - FMT_BUILTIN_CLZLL(n | 1)) * 1233 >> 12; - return to_unsigned(t) - (n < data::ZERO_OR_POWERS_OF_10_64[t]) + 1; + return t - (n < data::ZERO_OR_POWERS_OF_10_64[t]) + 1; } #else // Fallback version of count_digits used when __builtin_clz is not available. -inline unsigned count_digits(uint64_t n) { - unsigned count = 1; +inline int count_digits(uint64_t n) { + int count = 1; for (;;) { // Integer division is slow so do it for a group of four digits instead // of for every digit. The idea comes from the talk by Alexandrescu @@ -925,8 +790,33 @@ inline unsigned count_digits(uint64_t n) { } #endif +template +inline size_t count_code_points(basic_string_view s) { return s.size(); } + // Counts the number of code points in a UTF-8 string. -FMT_API size_t count_code_points(u8string_view s); +FMT_API size_t count_code_points(basic_string_view s); + +inline char8_t to_char8_t(char c) { return static_cast(c); } + +template +struct needs_conversion: std::integral_constant::value_type, char>::value && + std::is_same::value> {}; + +template +typename std::enable_if< + !needs_conversion::value, OutputIt>::type + copy_str(InputIt begin, InputIt end, OutputIt it) { + return std::copy(begin, end, it); +} + +template +typename std::enable_if< + needs_conversion::value, OutputIt>::type + copy_str(InputIt begin, InputIt end, OutputIt it) { + return std::transform(begin, end, it, to_char8_t); +} #if FMT_HAS_CPP_ATTRIBUTE(always_inline) # define FMT_ALWAYS_INLINE __attribute__((always_inline)) @@ -1006,9 +896,9 @@ class decimal_formatter_null : public decimal_formatter { #ifdef FMT_BUILTIN_CLZ // Optional version of count_digits for better performance on 32-bit platforms. -inline unsigned count_digits(uint32_t n) { +inline int count_digits(uint32_t n) { int t = (32 - FMT_BUILTIN_CLZ(n | 1)) * 1233 >> 12; - return to_unsigned(t) - (n < data::ZERO_OR_POWERS_OF_10_32[t]) + 1; + return t - (n < data::ZERO_OR_POWERS_OF_10_32[t]) + 1; } #endif @@ -1018,6 +908,8 @@ struct no_thousands_sep { template void operator()(Char *) {} + + enum { size = 0 }; }; // A functor that adds a thousands separator. @@ -1042,17 +934,30 @@ class add_thousands_sep { std::uninitialized_copy(sep_.data(), sep_.data() + sep_.size(), internal::make_checked(buffer, sep_.size())); } + + enum { size = 1 }; }; template -FMT_API Char thousands_sep(locale_provider *lp); +FMT_API Char thousands_sep_impl(locale_ref loc); + +template +inline Char thousands_sep(locale_ref loc) { + return Char(thousands_sep_impl(loc)); +} + +template <> +inline wchar_t thousands_sep(locale_ref loc) { + return thousands_sep_impl(loc); +} // Formats a decimal unsigned integer value writing into buffer. // thousands_sep is a functor that is called after writing each char to // add a thousands separator if necessary. template -inline Char *format_decimal(Char *buffer, UInt value, unsigned num_digits, +inline Char *format_decimal(Char *buffer, UInt value, int num_digits, ThousandsSep thousands_sep) { + FMT_ASSERT(num_digits >= 0, "invalid digit count"); buffer += num_digits; Char *end = buffer; while (value >= 100) { @@ -1061,58 +966,63 @@ inline Char *format_decimal(Char *buffer, UInt value, unsigned num_digits, // "Three Optimization Tips for C++". See speed-test for a comparison. unsigned index = static_cast((value % 100) * 2); value /= 100; - *--buffer = data::DIGITS[index + 1]; + *--buffer = static_cast(data::DIGITS[index + 1]); thousands_sep(buffer); - *--buffer = data::DIGITS[index]; + *--buffer = static_cast(data::DIGITS[index]); thousands_sep(buffer); } if (value < 10) { - *--buffer = static_cast('0' + value); + *--buffer = static_cast('0' + value); return end; } unsigned index = static_cast(value * 2); - *--buffer = data::DIGITS[index + 1]; + *--buffer = static_cast(data::DIGITS[index + 1]); thousands_sep(buffer); - *--buffer = data::DIGITS[index]; + *--buffer = static_cast(data::DIGITS[index]); return end; } -template +template inline Iterator format_decimal( - Iterator out, UInt value, unsigned num_digits, ThousandsSep sep) { + Iterator out, UInt value, int num_digits, ThousandsSep sep) { + FMT_ASSERT(num_digits >= 0, "invalid digit count"); typedef typename ThousandsSep::char_type char_type; - // Buffer should be large enough to hold all digits (digits10 + 1) and null. - char_type buffer[std::numeric_limits::digits10 + 2]; - format_decimal(buffer, value, num_digits, sep); - return std::copy_n(buffer, num_digits, out); + // Buffer should be large enough to hold all digits (<= digits10 + 1). + enum { max_size = std::numeric_limits::digits10 + 1 }; + FMT_ASSERT(ThousandsSep::size <= 1, "invalid separator"); + char_type buffer[max_size + max_size / 3]; + auto end = format_decimal(buffer, value, num_digits, sep); + return internal::copy_str(buffer, end, out); } -template -inline It format_decimal(It out, UInt value, unsigned num_digits) { - return format_decimal(out, value, num_digits, no_thousands_sep()); +template +inline It format_decimal(It out, UInt value, int num_digits) { + return format_decimal(out, value, num_digits, no_thousands_sep()); } template -inline Char *format_uint(Char *buffer, UInt value, unsigned num_digits, +inline Char *format_uint(Char *buffer, UInt value, int num_digits, bool upper = false) { buffer += num_digits; Char *end = buffer; do { const char *digits = upper ? "0123456789ABCDEF" : "0123456789abcdef"; unsigned digit = (value & ((1 << BASE_BITS) - 1)); - *--buffer = BASE_BITS < 4 ? static_cast('0' + digit) : digits[digit]; + *--buffer = static_cast(BASE_BITS < 4 ? static_cast('0' + digit) + : digits[digit]); } while ((value >>= BASE_BITS) != 0); return end; } -template -inline It format_uint(It out, UInt value, unsigned num_digits, +template +inline It format_uint(It out, UInt value, int num_digits, bool upper = false) { // Buffer should be large enough to hold all digits (digits / BASE_BITS + 1) // and null. char buffer[std::numeric_limits::digits / BASE_BITS + 2]; format_uint(buffer, value, num_digits, upper); - return std::copy_n(buffer, num_digits, out); + return internal::copy_str(buffer, buffer + num_digits, out); } #ifndef _WIN32 @@ -1171,72 +1081,35 @@ enum alignment { }; // Flags. -enum {SIGN_FLAG = 1, PLUS_FLAG = 2, MINUS_FLAG = 4, HASH_FLAG = 8}; - -enum format_spec_tag {fill_tag, align_tag, width_tag, type_tag}; - -// Format specifier. -template -class format_spec { - private: - T value_; - - public: - typedef T value_type; - - explicit format_spec(T value) : value_(value) {} - - T value() const { return value_; } -}; - -// template -// typedef format_spec fill_spec; -template -class fill_spec : public format_spec { - public: - explicit fill_spec(Char value) : format_spec(value) {} -}; - -typedef format_spec width_spec; -typedef format_spec type_spec; - -// An empty format specifier. -struct empty_spec {}; +enum { SIGN_FLAG = 1, PLUS_FLAG = 2, MINUS_FLAG = 4, HASH_FLAG = 8 }; // An alignment specifier. -struct align_spec : empty_spec { +struct align_spec { unsigned width_; // Fill is always wchar_t and cast to char if necessary to avoid having // two specialization of AlignSpec and its subclasses. wchar_t fill_; alignment align_; - FMT_CONSTEXPR align_spec( - unsigned width, wchar_t fill, alignment align = ALIGN_DEFAULT) - : width_(width), fill_(fill), align_(align) {} - + FMT_CONSTEXPR align_spec() : width_(0), fill_(' '), align_(ALIGN_DEFAULT) {} FMT_CONSTEXPR unsigned width() const { return width_; } FMT_CONSTEXPR wchar_t fill() const { return fill_; } FMT_CONSTEXPR alignment align() const { return align_; } +}; - int precision() const { return -1; } +struct core_format_specs { + int precision; + uint_least8_t flags; + char type; + + FMT_CONSTEXPR core_format_specs() : precision(-1), flags(0), type(0) {} + FMT_CONSTEXPR bool has(unsigned f) const { return (flags & f) != 0; } }; // Format specifiers. template -class basic_format_specs : public align_spec { - public: - unsigned flags_; - int precision_; - Char type_; - - FMT_CONSTEXPR basic_format_specs( - unsigned width = 0, char type = 0, wchar_t fill = ' ') - : align_spec(width, fill), flags_(0), precision_(-1), type_(type) {} - - FMT_CONSTEXPR bool flag(unsigned f) const { return (flags_ & f) != 0; } - FMT_CONSTEXPR int precision() const { return precision_; } - FMT_CONSTEXPR Char type() const { return type_; } +struct basic_format_specs : align_spec, core_format_specs { + FMT_CONSTEXPR basic_format_specs() {} }; typedef basic_format_specs format_specs; @@ -1251,13 +1124,20 @@ FMT_CONSTEXPR unsigned basic_parse_context::next_arg_id() { namespace internal { -template -struct format_string_traits< - S, typename std::enable_if::value>::type>: - format_string_traits_base {}; +// Formats value using Grisu2 algorithm: +// https://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf +template +FMT_API typename std::enable_if::type + grisu2_format(Double value, buffer &buf, core_format_specs); +template +inline typename std::enable_if::type + grisu2_format(Double, buffer &, core_format_specs) { return false; } -template -FMT_CONSTEXPR void handle_int_type_spec(Char spec, Handler &&handler) { +template +void sprintf_format(Double, internal::buffer &, core_format_specs); + +template +FMT_CONSTEXPR void handle_int_type_spec(char spec, Handler &&handler) { switch (spec) { case 0: case 'd': handler.on_dec(); @@ -1279,8 +1159,8 @@ FMT_CONSTEXPR void handle_int_type_spec(Char spec, Handler &&handler) { } } -template -FMT_CONSTEXPR void handle_float_type_spec(Char spec, Handler &&handler) { +template +FMT_CONSTEXPR void handle_float_type_spec(char spec, Handler &&handler) { switch (spec) { case 0: case 'g': case 'G': handler.on_general(); @@ -1304,8 +1184,8 @@ template FMT_CONSTEXPR void handle_char_specs( const basic_format_specs *specs, Handler &&handler) { if (!specs) return handler.on_char(); - if (specs->type() && specs->type() != 'c') return handler.on_int(); - if (specs->align() == ALIGN_NUMERIC || specs->flag(~0u) != 0) + if (specs->type && specs->type != 'c') return handler.on_int(); + if (specs->align() == ALIGN_NUMERIC || specs->flags != 0) handler.on_error("invalid format specifier for char"); handler.on_char(); } @@ -1364,13 +1244,13 @@ class float_type_checker : private ErrorHandler { } }; -template +template class char_specs_checker : public ErrorHandler { private: - CharType type_; + char type_; public: - FMT_CONSTEXPR char_specs_checker(CharType type, ErrorHandler eh) + FMT_CONSTEXPR char_specs_checker(char type, ErrorHandler eh) : ErrorHandler(eh), type_(type) {} FMT_CONSTEXPR void on_int() { @@ -1394,8 +1274,7 @@ void arg_map::init(const basic_format_args &args) { if (map_) return; map_ = new entry[args.max_size()]; - bool use_values = args.type(max_packed_args - 1) == internal::none_type; - if (use_values) { + if (args.is_packed()) { for (unsigned i = 0;/*nothing*/; ++i) { internal::type arg_type = args.type(i); switch (arg_type) { @@ -1436,21 +1315,25 @@ class arg_formatter_base { struct char_writer { char_type value; + + size_t size() const { return 1; } + size_t width() const { return 1; } + template void operator()(It &&it) const { *it++ = value; } }; void write_char(char_type value) { if (specs_) - writer_.write_padded(1, *specs_, char_writer{value}); + writer_.write_padded(*specs_, char_writer{value}); else writer_.write(value); } void write_pointer(const void *p) { format_specs specs = specs_ ? *specs_ : format_specs(); - specs.flags_ = HASH_FLAG; - specs.type_ = 'x'; + specs.flags = HASH_FLAG; + specs.type = 'x'; writer_.write_int(reinterpret_cast(p), specs); } @@ -1461,7 +1344,7 @@ class arg_formatter_base { void write(bool value) { string_view sv(value ? "true" : "false"); - specs_ ? writer_.write_str(sv, *specs_) : writer_.write(sv); + specs_ ? writer_.write(sv, *specs_) : writer_.write(sv); } void write(const char_type *value) { @@ -1469,11 +1352,12 @@ class arg_formatter_base { FMT_THROW(format_error("string pointer is null")); auto length = std::char_traits::length(value); basic_string_view sv(value, length); - specs_ ? writer_.write_str(sv, *specs_) : writer_.write(sv); + specs_ ? writer_.write(sv, *specs_) : writer_.write(sv); } public: - arg_formatter_base(Range r, format_specs *s): writer_(r), specs_(s) {} + arg_formatter_base(Range r, format_specs *s, locale_ref loc) + : writer_(r, loc), specs_(s) {} iterator operator()(monostate) { FMT_ASSERT(false, "invalid argument type"); @@ -1481,12 +1365,13 @@ class arg_formatter_base { } template - typename std::enable_if::value, iterator>::type - operator()(T value) { + typename std::enable_if< + std::is_integral::value || std::is_same::value, + iterator>::type operator()(T value) { // MSVC2013 fails to compile separate overloads for bool and char_type so // use std::is_same instead. if (std::is_same::value) { - if (specs_ && specs_->type_) + if (specs_ && specs_->type) return (*this)(value ? 1 : 0); write(value != 0); } else if (std::is_same::value) { @@ -1535,15 +1420,15 @@ class arg_formatter_base { iterator operator()(const char_type *value) { if (!specs_) return write(value), out(); internal::handle_cstring_type_spec( - specs_->type_, cstring_spec_handler(*this, value)); + specs_->type, cstring_spec_handler(*this, value)); return out(); } iterator operator()(basic_string_view value) { if (specs_) { internal::check_string_type_spec( - specs_->type_, internal::error_handler()); - writer_.write_str(value, *specs_); + specs_->type, internal::error_handler()); + writer_.write(value, *specs_); } else { writer_.write(value); } @@ -1552,7 +1437,7 @@ class arg_formatter_base { iterator operator()(const void *value) { if (specs_) - check_pointer_type_spec(specs_->type_, internal::error_handler()); + check_pointer_type_spec(specs_->type, internal::error_handler()); write_pointer(value); return out(); } @@ -1563,40 +1448,16 @@ FMT_CONSTEXPR bool is_name_start(Char c) { return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || '_' == c; } -// DEPRECATED: Parses the input as an unsigned integer. This function assumes -// that the first character is a digit and presence of a non-digit character at -// the end. -// it: an iterator pointing to the beginning of the input range. -template -FMT_CONSTEXPR unsigned parse_nonnegative_int(Iterator &it, ErrorHandler &&eh) { - assert('0' <= *it && *it <= '9'); - unsigned value = 0; - // Convert to unsigned to prevent a warning. - unsigned max_int = (std::numeric_limits::max)(); - unsigned big = max_int / 10; - do { - // Check for overflow. - if (value > big) { - value = max_int + 1; - break; - } - value = value * 10 + unsigned(*it - '0'); - // Workaround for MSVC "setup_exception stack overflow" error: - auto next = it; - ++next; - it = next; - } while ('0' <= *it && *it <= '9'); - if (value > max_int) - eh.on_error("number is too big"); - return value; -} - // Parses the range [begin, end) as an unsigned integer. This function assumes // that the range is non-empty and the first character is a digit. template FMT_CONSTEXPR unsigned parse_nonnegative_int( const Char *&begin, const Char *end, ErrorHandler &&eh) { assert(begin != end && '0' <= *begin && *begin <= '9'); + if (*begin == '0') { + ++begin; + return 0; + } unsigned value = 0; // Convert to unsigned to prevent a warning. unsigned max_int = (std::numeric_limits::max)(); @@ -1607,7 +1468,8 @@ FMT_CONSTEXPR unsigned parse_nonnegative_int( value = max_int + 1; break; } - value = value * 10 + unsigned(*begin++ - '0'); + value = value * 10 + unsigned(*begin - '0'); + ++begin; } while (begin != end && '0' <= *begin && *begin <= '9'); if (value > max_int) eh.on_error("number is too big"); @@ -1695,14 +1557,14 @@ class specs_setter { explicit FMT_CONSTEXPR specs_setter(basic_format_specs &specs): specs_(specs) {} - FMT_CONSTEXPR specs_setter(const specs_setter &other) : specs_(other.specs_) {} + FMT_CONSTEXPR specs_setter(const specs_setter &other): specs_(other.specs_) {} FMT_CONSTEXPR void on_align(alignment align) { specs_.align_ = align; } FMT_CONSTEXPR void on_fill(Char fill) { specs_.fill_ = fill; } - FMT_CONSTEXPR void on_plus() { specs_.flags_ |= SIGN_FLAG | PLUS_FLAG; } - FMT_CONSTEXPR void on_minus() { specs_.flags_ |= MINUS_FLAG; } - FMT_CONSTEXPR void on_space() { specs_.flags_ |= SIGN_FLAG; } - FMT_CONSTEXPR void on_hash() { specs_.flags_ |= HASH_FLAG; } + FMT_CONSTEXPR void on_plus() { specs_.flags |= SIGN_FLAG | PLUS_FLAG; } + FMT_CONSTEXPR void on_minus() { specs_.flags |= MINUS_FLAG; } + FMT_CONSTEXPR void on_space() { specs_.flags |= SIGN_FLAG; } + FMT_CONSTEXPR void on_hash() { specs_.flags |= HASH_FLAG; } FMT_CONSTEXPR void on_zero() { specs_.align_ = ALIGN_NUMERIC; @@ -1711,11 +1573,13 @@ class specs_setter { FMT_CONSTEXPR void on_width(unsigned width) { specs_.width_ = width; } FMT_CONSTEXPR void on_precision(unsigned precision) { - specs_.precision_ = static_cast(precision); + specs_.precision = static_cast(precision); } FMT_CONSTEXPR void end_precision() {} - FMT_CONSTEXPR void on_type(Char type) { specs_.type_ = type; } + FMT_CONSTEXPR void on_type(Char type) { + specs_.type = static_cast(type); + } protected: basic_format_specs &specs_; @@ -1789,8 +1653,9 @@ template