diff --git a/include/spdlog/fmt/bundled/chrono.h b/include/spdlog/fmt/bundled/chrono.h index 57ce9ef3..9abe7c4f 100644 --- a/include/spdlog/fmt/bundled/chrono.h +++ b/include/spdlog/fmt/bundled/chrono.h @@ -16,16 +16,291 @@ #include #include -// enable safe chrono durations, unless explicitly disabled +FMT_BEGIN_NAMESPACE + +// Enable safe chrono durations, unless explicitly disabled. #ifndef FMT_SAFE_DURATION_CAST # define FMT_SAFE_DURATION_CAST 1 #endif - #if FMT_SAFE_DURATION_CAST -# include "safe-duration-cast.h" -#endif -FMT_BEGIN_NAMESPACE +// For conversion between std::chrono::durations without undefined +// behaviour or erroneous results. +// This is a stripped down version of duration_cast, for inclusion in fmt. +// See https://github.com/pauldreik/safe_duration_cast +// +// Copyright Paul Dreik 2019 +namespace safe_duration_cast { + +template ::value && + std::numeric_limits::is_signed == + std::numeric_limits::is_signed)> +FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) { + ec = 0; + using F = std::numeric_limits; + using T = std::numeric_limits; + static_assert(F::is_integer, "From must be integral"); + static_assert(T::is_integer, "To must be integral"); + + // A and B are both signed, or both unsigned. + if (F::digits <= T::digits) { + // From fits in To without any problem. + } else { + // From does not always fit in To, resort to a dynamic check. + if (from < T::min() || from > T::max()) { + // outside range. + ec = 1; + return {}; + } + } + return static_cast(from); +} + +/** + * converts From to To, without loss. If the dynamic value of from + * can't be converted to To without loss, ec is set. + */ +template ::value && + std::numeric_limits::is_signed != + std::numeric_limits::is_signed)> +FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) { + ec = 0; + using F = std::numeric_limits; + using T = std::numeric_limits; + static_assert(F::is_integer, "From must be integral"); + static_assert(T::is_integer, "To must be integral"); + + if (F::is_signed && !T::is_signed) { + // From may be negative, not allowed! + if (fmt::internal::is_negative(from)) { + ec = 1; + return {}; + } + + // From is positive. Can it always fit in To? + if (F::digits <= T::digits) { + // yes, From always fits in To. + } else { + // from may not fit in To, we have to do a dynamic check + if (from > static_cast(T::max())) { + ec = 1; + return {}; + } + } + } + + if (!F::is_signed && T::is_signed) { + // can from be held in To? + if (F::digits < T::digits) { + // yes, From always fits in To. + } else { + // from may not fit in To, we have to do a dynamic check + if (from > static_cast(T::max())) { + // outside range. + ec = 1; + return {}; + } + } + } + + // reaching here means all is ok for lossless conversion. + return static_cast(from); + +} // function + +template ::value)> +FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) { + ec = 0; + return from; +} // function + +// clang-format off +/** + * converts From to To if possible, otherwise ec is set. + * + * input | output + * ---------------------------------|--------------- + * NaN | NaN + * Inf | Inf + * normal, fits in output | converted (possibly lossy) + * normal, does not fit in output | ec is set + * subnormal | best effort + * -Inf | -Inf + */ +// clang-format on +template ::value)> +FMT_CONSTEXPR To safe_float_conversion(const From from, int& ec) { + ec = 0; + using T = std::numeric_limits; + static_assert(std::is_floating_point::value, "From must be floating"); + static_assert(std::is_floating_point::value, "To must be floating"); + + // catch the only happy case + if (std::isfinite(from)) { + if (from >= T::lowest() && from <= T::max()) { + return static_cast(from); + } + // not within range. + ec = 1; + return {}; + } + + // nan and inf will be preserved + return static_cast(from); +} // function + +template ::value)> +FMT_CONSTEXPR To safe_float_conversion(const From from, int& ec) { + ec = 0; + static_assert(std::is_floating_point::value, "From must be floating"); + return from; +} + +/** + * safe duration cast between integral durations + */ +template ::value), + FMT_ENABLE_IF(std::is_integral::value)> +To safe_duration_cast(std::chrono::duration from, + int& ec) { + using From = std::chrono::duration; + ec = 0; + // the basic idea is that we need to convert from count() in the from type + // to count() in the To type, by multiplying it with this: + struct Factor + : std::ratio_divide {}; + + static_assert(Factor::num > 0, "num must be positive"); + static_assert(Factor::den > 0, "den must be positive"); + + // the conversion is like this: multiply from.count() with Factor::num + // /Factor::den and convert it to To::rep, all this without + // overflow/underflow. let's start by finding a suitable type that can hold + // both To, From and Factor::num + using IntermediateRep = + typename std::common_type::type; + + // safe conversion to IntermediateRep + IntermediateRep count = + lossless_integral_conversion(from.count(), ec); + if (ec) { + return {}; + } + // multiply with Factor::num without overflow or underflow + if (Factor::num != 1) { + const auto max1 = internal::max_value() / Factor::num; + if (count > max1) { + ec = 1; + return {}; + } + const auto min1 = std::numeric_limits::min() / Factor::num; + if (count < min1) { + ec = 1; + return {}; + } + count *= Factor::num; + } + + // this can't go wrong, right? den>0 is checked earlier. + if (Factor::den != 1) { + count /= Factor::den; + } + // convert to the to type, safely + using ToRep = typename To::rep; + const ToRep tocount = lossless_integral_conversion(count, ec); + if (ec) { + return {}; + } + return To{tocount}; +} + +/** + * safe duration_cast between floating point durations + */ +template ::value), + FMT_ENABLE_IF(std::is_floating_point::value)> +To safe_duration_cast(std::chrono::duration from, + int& ec) { + using From = std::chrono::duration; + ec = 0; + if (std::isnan(from.count())) { + // nan in, gives nan out. easy. + return To{std::numeric_limits::quiet_NaN()}; + } + // maybe we should also check if from is denormal, and decide what to do about + // it. + + // +-inf should be preserved. + if (std::isinf(from.count())) { + return To{from.count()}; + } + + // the basic idea is that we need to convert from count() in the from type + // to count() in the To type, by multiplying it with this: + struct Factor + : std::ratio_divide {}; + + static_assert(Factor::num > 0, "num must be positive"); + static_assert(Factor::den > 0, "den must be positive"); + + // the conversion is like this: multiply from.count() with Factor::num + // /Factor::den and convert it to To::rep, all this without + // overflow/underflow. let's start by finding a suitable type that can hold + // both To, From and Factor::num + using IntermediateRep = + typename std::common_type::type; + + // force conversion of From::rep -> IntermediateRep to be safe, + // even if it will never happen be narrowing in this context. + IntermediateRep count = + safe_float_conversion(from.count(), ec); + if (ec) { + return {}; + } + + // multiply with Factor::num without overflow or underflow + if (Factor::num != 1) { + constexpr auto max1 = internal::max_value() / + static_cast(Factor::num); + if (count > max1) { + ec = 1; + return {}; + } + constexpr auto min1 = std::numeric_limits::lowest() / + static_cast(Factor::num); + if (count < min1) { + ec = 1; + return {}; + } + count *= static_cast(Factor::num); + } + + // this can't go wrong, right? den>0 is checked earlier. + if (Factor::den != 1) { + using common_t = typename std::common_type::type; + count /= static_cast(Factor::den); + } + + // convert to the to type, safely + using ToRep = typename To::rep; + + const ToRep tocount = safe_float_conversion(count, ec); + if (ec) { + return {}; + } + return To{tocount}; +} +} // namespace safe_duration_cast +#endif // Prevents expansion of a preceding token as a function-style macro. // Usage: f FMT_NOMACRO() @@ -403,7 +678,7 @@ inline bool isfinite(T value) { return std::isfinite(value); } -// Convers value to int and checks that it's in the range [0, upper). +// Converts value to int and checks that it's in the range [0, upper). template ::value)> inline int to_nonnegative_int(T value, int upper) { FMT_ASSERT(value >= 0 && value <= upper, "invalid value"); @@ -582,8 +857,8 @@ struct chrono_formatter { void write(Rep value, int width) { write_sign(); if (isnan(value)) return write_nan(); - uint32_or_64_t n = to_unsigned( - to_nonnegative_int(value, (std::numeric_limits::max)())); + uint32_or_64_or_128_t n = + to_unsigned(to_nonnegative_int(value, max_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); @@ -728,7 +1003,7 @@ struct formatter, Char> { struct spec_handler { formatter& f; - basic_parse_context& context; + basic_format_parse_context& context; basic_string_view format_str; template FMT_CONSTEXPR arg_ref_type make_arg_ref(Id arg_id) { @@ -738,8 +1013,7 @@ struct formatter, Char> { FMT_CONSTEXPR arg_ref_type make_arg_ref(basic_string_view arg_id) { context.check_arg_id(arg_id); - const auto str_val = internal::string_view_metadata(format_str, arg_id); - return arg_ref_type(str_val); + return arg_ref_type(arg_id); } FMT_CONSTEXPR arg_ref_type make_arg_ref(internal::auto_id) { @@ -750,7 +1024,7 @@ struct formatter, Char> { void on_fill(Char fill) { f.specs.fill[0] = fill; } void on_align(align_t align) { f.specs.align = align; } void on_width(unsigned width) { f.specs.width = width; } - void on_precision(unsigned precision) { f.precision = precision; } + void on_precision(unsigned _precision) { f.precision = _precision; } void end_precision() {} template void on_dynamic_width(Id arg_id) { @@ -762,13 +1036,13 @@ struct formatter, Char> { } }; - using iterator = typename basic_parse_context::iterator; + using iterator = typename basic_format_parse_context::iterator; struct parse_range { iterator begin; iterator end; }; - FMT_CONSTEXPR parse_range do_parse(basic_parse_context& ctx) { + FMT_CONSTEXPR parse_range do_parse(basic_format_parse_context& ctx) { auto begin = ctx.begin(), end = ctx.end(); if (begin == end || *begin == '}') return {begin, begin}; spec_handler handler{*this, ctx, format_str}; @@ -789,7 +1063,7 @@ struct formatter, Char> { public: formatter() : precision(-1) {} - FMT_CONSTEXPR auto parse(basic_parse_context& ctx) + FMT_CONSTEXPR auto parse(basic_format_parse_context& ctx) -> decltype(ctx.begin()) { auto range = do_parse(ctx); format_str = basic_string_view( @@ -806,10 +1080,10 @@ struct formatter, Char> { auto out = std::back_inserter(buf); using range = internal::output_range; internal::basic_writer w(range(ctx.out())); - internal::handle_dynamic_spec( - specs.width, width_ref, ctx, format_str.begin()); + internal::handle_dynamic_spec(specs.width, + width_ref, ctx); internal::handle_dynamic_spec( - precision, precision_ref, ctx, format_str.begin()); + precision, precision_ref, ctx); if (begin == end || *begin == '}') { out = internal::format_chrono_duration_value(out, d.count(), precision); internal::format_chrono_duration_unit(out); diff --git a/include/spdlog/fmt/bundled/color.h b/include/spdlog/fmt/bundled/color.h index d9d31559..362a95e1 100644 --- a/include/spdlog/fmt/bundled/color.h +++ b/include/spdlog/fmt/bundled/color.h @@ -299,15 +299,15 @@ class text_style { return static_cast(ems) != 0; } FMT_CONSTEXPR internal::color_type get_foreground() const FMT_NOEXCEPT { - assert(has_foreground() && "no foreground specified for this style"); + FMT_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"); + FMT_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"); + FMT_ASSERT(has_emphasis(), "no emphasis specified for this style"); return ems; } @@ -470,58 +470,41 @@ inline void reset_color(basic_memory_buffer& buffer) FMT_NOEXCEPT { } template -std::basic_string vformat(const text_style& ts, - basic_string_view format_str, - basic_format_args > args) { - basic_memory_buffer buffer; +void vformat_to(basic_memory_buffer& buf, const text_style& ts, + basic_string_view format_str, + basic_format_args> args) { bool has_style = false; if (ts.has_emphasis()) { has_style = true; - ansi_color_escape escape = make_emphasis(ts.get_emphasis()); - buffer.append(escape.begin(), escape.end()); + auto emphasis = internal::make_emphasis(ts.get_emphasis()); + buf.append(emphasis.begin(), emphasis.end()); } if (ts.has_foreground()) { has_style = true; - ansi_color_escape escape = - make_foreground_color(ts.get_foreground()); - buffer.append(escape.begin(), escape.end()); + auto foreground = + internal::make_foreground_color(ts.get_foreground()); + buf.append(foreground.begin(), foreground.end()); } if (ts.has_background()) { has_style = true; - ansi_color_escape escape = - make_background_color(ts.get_background()); - buffer.append(escape.begin(), escape.end()); + auto background = + internal::make_background_color(ts.get_background()); + buf.append(background.begin(), background.end()); } - internal::vformat_to(buffer, format_str, args); + vformat_to(buf, format_str, args); if (has_style) { - reset_color(buffer); + internal::reset_color(buf); } - return fmt::to_string(buffer); } } // namespace internal -template > +template > void vprint(std::FILE* f, const text_style& ts, const S& format, - basic_format_args > 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); - } + basic_format_args> args) { + basic_memory_buffer buf; + internal::vformat_to(buf, ts, to_string_view(format), args); + buf.push_back(Char(0)); + internal::fputs(buf.data(), f); } /** @@ -536,7 +519,7 @@ template (format_str); - using context = buffer_context >; + using context = buffer_context>; format_arg_store as{args...}; vprint(f, ts, format_str, basic_format_args(as)); } @@ -554,11 +537,13 @@ void print(const text_style& ts, const S& format_str, const Args&... args) { return print(stdout, ts, format_str, args...); } -template > +template > inline std::basic_string vformat( const text_style& ts, const S& format_str, - basic_format_args > args) { - return internal::vformat(ts, to_string_view(format_str), args); + basic_format_args> args) { + basic_memory_buffer buf; + internal::vformat_to(buf, ts, to_string_view(format_str), args); + return fmt::to_string(buf); } /** @@ -573,11 +558,11 @@ inline std::basic_string vformat( "The answer is {}", 42); \endrst */ -template > +template > inline std::basic_string format(const text_style& ts, const S& format_str, const Args&... args) { - return internal::vformat(ts, to_string_view(format_str), - {internal::make_args_checked(format_str, args...)}); + return vformat(ts, to_string_view(format_str), + {internal::make_args_checked(format_str, args...)}); } FMT_END_NAMESPACE diff --git a/include/spdlog/fmt/bundled/compile.h b/include/spdlog/fmt/bundled/compile.h index 82625bbc..f65f5a74 100644 --- a/include/spdlog/fmt/bundled/compile.h +++ b/include/spdlog/fmt/bundled/compile.h @@ -14,250 +14,44 @@ FMT_BEGIN_NAMESPACE namespace internal { +// Part of a compiled format string. It can be either literal text or a +// replacement field. template struct format_part { - public: - struct named_argument_id { - FMT_CONSTEXPR named_argument_id(internal::string_view_metadata id) - : id(id) {} - internal::string_view_metadata id; + enum class kind { arg_index, arg_name, text, replacement }; + + struct replacement { + arg_ref arg_id; + dynamic_format_specs specs; }; - struct argument_id { - FMT_CONSTEXPR argument_id() : argument_id(0u) {} - - FMT_CONSTEXPR argument_id(unsigned id) - : which(which_arg_id::index), val(id) {} - - FMT_CONSTEXPR argument_id(internal::string_view_metadata id) - : which(which_arg_id::named_index), val(id) {} - - enum class which_arg_id { index, named_index }; - - which_arg_id which; - - union value { - FMT_CONSTEXPR value() : index(0u) {} - FMT_CONSTEXPR value(unsigned id) : index(id) {} - FMT_CONSTEXPR value(internal::string_view_metadata id) - : named_index(id) {} - - unsigned index; - internal::string_view_metadata named_index; - } val; - }; - - struct specification { - FMT_CONSTEXPR specification() : arg_id(0u) {} - FMT_CONSTEXPR specification(unsigned id) : arg_id(id) {} - - FMT_CONSTEXPR specification(internal::string_view_metadata id) - : arg_id(id) {} - - argument_id arg_id; - internal::dynamic_format_specs parsed_specs; - }; - - FMT_CONSTEXPR format_part() - : which(kind::argument_id), end_of_argument_id(0u), val(0u) {} - - FMT_CONSTEXPR format_part(internal::string_view_metadata text) - : which(kind::text), end_of_argument_id(0u), val(text) {} - - FMT_CONSTEXPR format_part(unsigned id) - : which(kind::argument_id), end_of_argument_id(0u), val(id) {} - - FMT_CONSTEXPR format_part(named_argument_id arg_id) - : which(kind::named_argument_id), end_of_argument_id(0u), val(arg_id) {} - - FMT_CONSTEXPR format_part(specification spec) - : which(kind::specification), end_of_argument_id(0u), val(spec) {} - - enum class kind { argument_id, named_argument_id, text, specification }; - - kind which; - std::size_t end_of_argument_id; + kind part_kind; union value { - FMT_CONSTEXPR value() : arg_id(0u) {} - FMT_CONSTEXPR value(unsigned id) : arg_id(id) {} - FMT_CONSTEXPR value(named_argument_id named_id) - : named_arg_id(named_id.id) {} - FMT_CONSTEXPR value(internal::string_view_metadata t) : text(t) {} - FMT_CONSTEXPR value(specification s) : spec(s) {} - unsigned arg_id; - internal::string_view_metadata named_arg_id; - internal::string_view_metadata text; - specification spec; + unsigned arg_index; + basic_string_view str; + replacement repl; + + FMT_CONSTEXPR value(unsigned index = 0) : arg_index(index) {} + FMT_CONSTEXPR value(basic_string_view s) : str(s) {} + FMT_CONSTEXPR value(replacement r) : repl(r) {} } val; -}; + // Position past the end of the argument id. + const Char* arg_id_end = nullptr; -template -class format_preparation_handler : public internal::error_handler { - private: - using part = format_part; + FMT_CONSTEXPR format_part(kind k = kind::arg_index, value v = {}) + : part_kind(k), val(v) {} - public: - using iterator = typename basic_string_view::iterator; - - FMT_CONSTEXPR format_preparation_handler(basic_string_view format, - PartsContainer& parts) - : parts_(parts), format_(format), parse_context_(format) {} - - FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) { - if (begin == end) return; - const auto offset = begin - format_.data(); - const auto size = end - begin; - parts_.push_back(part(string_view_metadata(offset, size))); + static FMT_CONSTEXPR format_part make_arg_index(unsigned index) { + return format_part(kind::arg_index, index); } - - FMT_CONSTEXPR void on_arg_id() { - parts_.push_back(part(parse_context_.next_arg_id())); + static FMT_CONSTEXPR format_part make_arg_name(basic_string_view name) { + return format_part(kind::arg_name, name); } - - FMT_CONSTEXPR void on_arg_id(unsigned id) { - parse_context_.check_arg_id(id); - parts_.push_back(part(id)); + static FMT_CONSTEXPR format_part make_text(basic_string_view text) { + return format_part(kind::text, text); } - - FMT_CONSTEXPR void on_arg_id(basic_string_view id) { - const auto view = string_view_metadata(format_, id); - const auto arg_id = typename part::named_argument_id(view); - parts_.push_back(part(arg_id)); + static FMT_CONSTEXPR format_part make_replacement(replacement repl) { + return format_part(kind::replacement, repl); } - - FMT_CONSTEXPR void on_replacement_field(const Char* ptr) { - parts_.back().end_of_argument_id = ptr - format_.begin(); - } - - FMT_CONSTEXPR const Char* on_format_specs(const Char* begin, - const Char* end) { - const auto specs_offset = to_unsigned(begin - format_.begin()); - - using parse_context = basic_parse_context; - internal::dynamic_format_specs parsed_specs; - dynamic_specs_handler handler(parsed_specs, parse_context_); - begin = parse_format_specs(begin, end, handler); - - if (*begin != '}') on_error("missing '}' in format string"); - - auto& last_part = parts_.back(); - auto specs = last_part.which == part::kind::argument_id - ? typename part::specification(last_part.val.arg_id) - : typename part::specification(last_part.val.named_arg_id); - specs.parsed_specs = parsed_specs; - last_part = part(specs); - last_part.end_of_argument_id = specs_offset; - return begin; - } - - private: - PartsContainer& parts_; - basic_string_view format_; - basic_parse_context parse_context_; -}; - -template -class prepared_format { - public: - using char_type = char_t; - using format_part_t = format_part; - - constexpr prepared_format(Format f) - : format_(std::move(f)), parts_provider_(to_string_view(format_)) {} - - prepared_format() = delete; - - using context = buffer_context; - - template - auto vformat_to(Range out, basic_format_args args) const -> - typename Context::iterator { - const auto format_view = internal::to_string_view(format_); - basic_parse_context parse_ctx(format_view); - Context ctx(out.begin(), args); - - const auto& parts = parts_provider_.parts(); - for (auto part_it = parts.begin(); part_it != parts.end(); ++part_it) { - const auto& part = *part_it; - const auto& value = part.val; - - switch (part.which) { - case format_part_t::kind::text: { - const auto text = value.text.to_view(format_view.data()); - auto output = ctx.out(); - auto&& it = internal::reserve(output, text.size()); - it = std::copy_n(text.begin(), text.size(), it); - ctx.advance_to(output); - } break; - - case format_part_t::kind::argument_id: { - advance_parse_context_to_specification(parse_ctx, part); - format_arg(parse_ctx, ctx, value.arg_id); - } break; - - case format_part_t::kind::named_argument_id: { - advance_parse_context_to_specification(parse_ctx, part); - const auto named_arg_id = - value.named_arg_id.to_view(format_view.data()); - format_arg(parse_ctx, ctx, named_arg_id); - } break; - case format_part_t::kind::specification: { - const auto& arg_id_value = value.spec.arg_id.val; - const auto arg = value.spec.arg_id.which == - format_part_t::argument_id::which_arg_id::index - ? ctx.arg(arg_id_value.index) - : ctx.arg(arg_id_value.named_index.to_view( - to_string_view(format_).data())); - - auto specs = value.spec.parsed_specs; - - handle_dynamic_spec( - specs.width, specs.width_ref, ctx, format_view.begin()); - handle_dynamic_spec( - specs.precision, specs.precision_ref, ctx, format_view.begin()); - - check_prepared_specs(specs, arg.type()); - advance_parse_context_to_specification(parse_ctx, part); - ctx.advance_to( - visit_format_arg(arg_formatter(ctx, nullptr, &specs), arg)); - } break; - } - } - - return ctx.out(); - } - - private: - void advance_parse_context_to_specification( - basic_parse_context& parse_ctx, - const format_part_t& part) const { - const auto view = to_string_view(format_); - const auto specification_begin = view.data() + part.end_of_argument_id; - advance_to(parse_ctx, specification_begin); - } - - template - void format_arg(basic_parse_context& parse_ctx, Context& ctx, - Id arg_id) const { - parse_ctx.check_arg_id(arg_id); - const auto stopped_at = - visit_format_arg(arg_formatter(ctx), ctx.arg(arg_id)); - ctx.advance_to(stopped_at); - } - - template - void check_prepared_specs(const basic_format_specs& specs, - internal::type arg_type) const { - internal::error_handler h; - numeric_specs_checker checker(h, arg_type); - if (specs.align == align::numeric) checker.require_numeric_argument(); - if (specs.sign != sign::none) checker.check_sign(); - if (specs.alt) checker.require_numeric_argument(); - if (specs.precision >= 0) checker.check_precision(); - } - - private: - Format format_; - PreparedPartsProvider parts_provider_; }; template struct part_counter { @@ -276,13 +70,13 @@ template struct part_counter { FMT_CONSTEXPR const Char* on_format_specs(const Char* begin, const Char* end) { // Find the matching brace. - unsigned braces_counter = 0; + unsigned brace_counter = 0; for (; begin != end; ++begin) { if (*begin == '{') { - ++braces_counter; + ++brace_counter; } else if (*begin == '}') { - if (braces_counter == 0u) break; - --braces_counter; + if (brace_counter == 0u) break; + --brace_counter; } } return begin; @@ -291,156 +85,486 @@ template struct part_counter { FMT_CONSTEXPR void on_error(const char*) {} }; -template class compiletime_prepared_parts_type_provider { - private: - using char_type = char_t; +// Counts the number of parts in a format string. +template +FMT_CONSTEXPR unsigned count_parts(basic_string_view format_str) { + part_counter counter; + parse_format_string(format_str, counter); + return counter.num_parts; +} - static FMT_CONSTEXPR unsigned count_parts() { - FMT_CONSTEXPR_DECL const auto text = to_string_view(Format{}); - part_counter counter; - internal::parse_format_string(text, counter); - return counter.num_parts; +template +class format_string_compiler : public error_handler { + private: + using part = format_part; + + PartHandler handler_; + part part_; + basic_string_view format_str_; + basic_format_parse_context parse_context_; + + public: + FMT_CONSTEXPR format_string_compiler(basic_string_view format_str, + PartHandler handler) + : handler_(handler), + format_str_(format_str), + parse_context_(format_str) {} + + FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) { + if (begin != end) + handler_(part::make_text({begin, to_unsigned(end - begin)})); } -// Workaround for old compilers. Compiletime parts preparation will not be -// performed with them anyway. + FMT_CONSTEXPR void on_arg_id() { + part_ = part::make_arg_index(parse_context_.next_arg_id()); + } + + FMT_CONSTEXPR void on_arg_id(unsigned id) { + parse_context_.check_arg_id(id); + part_ = part::make_arg_index(id); + } + + FMT_CONSTEXPR void on_arg_id(basic_string_view id) { + part_ = part::make_arg_name(id); + } + + FMT_CONSTEXPR void on_replacement_field(const Char* ptr) { + part_.arg_id_end = ptr; + handler_(part_); + } + + FMT_CONSTEXPR const Char* on_format_specs(const Char* begin, + const Char* end) { + auto repl = typename part::replacement(); + dynamic_specs_handler> handler( + repl.specs, parse_context_); + auto it = parse_format_specs(begin, end, handler); + if (*it != '}') on_error("missing '}' in format string"); + repl.arg_id = part_.part_kind == part::kind::arg_index + ? arg_ref(part_.val.arg_index) + : arg_ref(part_.val.str); + auto part = part::make_replacement(repl); + part.arg_id_end = begin; + handler_(part); + return it; + } +}; + +// Compiles a format string and invokes handler(part) for each parsed part. +template +FMT_CONSTEXPR void compile_format_string(basic_string_view format_str, + PartHandler handler) { + parse_format_string( + format_str, + format_string_compiler(format_str, handler)); +} + +template +void format_arg( + basic_format_parse_context& parse_ctx, + Context& ctx, Id arg_id) { + ctx.advance_to( + visit_format_arg(arg_formatter(ctx, &parse_ctx), ctx.arg(arg_id))); +} + +// vformat_to is defined in a subnamespace to prevent ADL. +namespace cf { +template +auto vformat_to(Range out, CompiledFormat& cf, basic_format_args args) + -> typename Context::iterator { + using char_type = typename Context::char_type; + basic_format_parse_context parse_ctx( + to_string_view(cf.format_str_)); + Context ctx(out.begin(), args); + + const auto& parts = cf.parts(); + for (auto part_it = std::begin(parts); part_it != std::end(parts); + ++part_it) { + const auto& part = *part_it; + const auto& value = part.val; + + using format_part_t = format_part; + switch (part.part_kind) { + case format_part_t::kind::text: { + const auto text = value.str; + auto output = ctx.out(); + auto&& it = reserve(output, text.size()); + it = std::copy_n(text.begin(), text.size(), it); + ctx.advance_to(output); + break; + } + + case format_part_t::kind::arg_index: + advance_to(parse_ctx, part.arg_id_end); + internal::format_arg(parse_ctx, ctx, value.arg_index); + break; + + case format_part_t::kind::arg_name: + advance_to(parse_ctx, part.arg_id_end); + internal::format_arg(parse_ctx, ctx, value.str); + break; + + case format_part_t::kind::replacement: { + const auto& arg_id_value = value.repl.arg_id.val; + const auto arg = value.repl.arg_id.kind == arg_id_kind::index + ? ctx.arg(arg_id_value.index) + : ctx.arg(arg_id_value.name); + + auto specs = value.repl.specs; + + handle_dynamic_spec(specs.width, specs.width_ref, ctx); + handle_dynamic_spec(specs.precision, + specs.precision_ref, ctx); + + error_handler h; + numeric_specs_checker checker(h, arg.type()); + if (specs.align == align::numeric) checker.require_numeric_argument(); + if (specs.sign != sign::none) checker.check_sign(); + if (specs.alt) checker.require_numeric_argument(); + if (specs.precision >= 0) checker.check_precision(); + + advance_to(parse_ctx, part.arg_id_end); + ctx.advance_to( + visit_format_arg(arg_formatter(ctx, nullptr, &specs), arg)); + break; + } + } + } + return ctx.out(); +} +} // namespace cf + +struct basic_compiled_format {}; + +template +struct compiled_format_base : basic_compiled_format { + using char_type = char_t; + using parts_container = std::vector>; + + parts_container compiled_parts; + + explicit compiled_format_base(basic_string_view format_str) { + compile_format_string(format_str, + [this](const format_part& part) { + compiled_parts.push_back(part); + }); + } + + const parts_container& parts() const { return compiled_parts; } +}; + +template struct format_part_array { + format_part data[N] = {}; + FMT_CONSTEXPR format_part_array() = default; +}; + +template +FMT_CONSTEXPR format_part_array compile_to_parts( + basic_string_view format_str) { + format_part_array parts; + unsigned counter = 0; + // This is not a lambda for compatibility with older compilers. + struct { + format_part* parts; + unsigned* counter; + FMT_CONSTEXPR void operator()(const format_part& part) { + parts[(*counter)++] = part; + } + } collector{parts.data, &counter}; + compile_format_string(format_str, collector); + if (counter < N) { + parts.data[counter] = + format_part::make_text(basic_string_view()); + } + return parts; +} + +template constexpr const T& constexpr_max(const T& a, const T& b) { + return (a < b) ? b : a; +} + +template +struct compiled_format_base::value>> + : basic_compiled_format { + using char_type = char_t; + + FMT_CONSTEXPR explicit compiled_format_base(basic_string_view) {} + +// Workaround for old compilers. Format string compilation will not be +// performed there anyway. #if FMT_USE_CONSTEXPR - static FMT_CONSTEXPR_DECL const unsigned number_of_format_parts = - compiletime_prepared_parts_type_provider::count_parts(); + static FMT_CONSTEXPR_DECL const unsigned num_format_parts = + constexpr_max(count_parts(to_string_view(S())), 1u); #else - static const unsigned number_of_format_parts = 0u; + static const unsigned num_format_parts = 1; #endif - public: - template struct format_parts_array { - using value_type = format_part; + using parts_container = format_part[num_format_parts]; - FMT_CONSTEXPR format_parts_array() : arr{} {} - - FMT_CONSTEXPR value_type& operator[](unsigned ind) { return arr[ind]; } - - FMT_CONSTEXPR const value_type* begin() const { return arr; } - FMT_CONSTEXPR const value_type* end() const { return begin() + N; } - - private: - value_type arr[N]; - }; - - struct empty { - // Parts preparator will search for it - using value_type = format_part; - }; - - using type = conditional_t, empty>; -}; - -template class compiletime_prepared_parts_collector { - private: - using format_part = typename Parts::value_type; - - public: - FMT_CONSTEXPR explicit compiletime_prepared_parts_collector(Parts& parts) - : parts_{parts}, counter_{0u} {} - - FMT_CONSTEXPR void push_back(format_part part) { parts_[counter_++] = part; } - - FMT_CONSTEXPR format_part& back() { return parts_[counter_ - 1]; } - - private: - Parts& parts_; - unsigned counter_; -}; - -template -FMT_CONSTEXPR PartsContainer prepare_parts(basic_string_view format) { - PartsContainer parts; - internal::parse_format_string( - format, format_preparation_handler(format, parts)); - return parts; -} - -template -FMT_CONSTEXPR PartsContainer -prepare_compiletime_parts(basic_string_view format) { - using collector = compiletime_prepared_parts_collector; - - PartsContainer parts; - collector c(parts); - internal::parse_format_string( - format, format_preparation_handler(format, c)); - return parts; -} - -template class runtime_parts_provider { - public: - runtime_parts_provider() = delete; - template - runtime_parts_provider(basic_string_view format) - : parts_(prepare_parts(format)) {} - - const PartsContainer& parts() const { return parts_; } - - private: - PartsContainer parts_; -}; - -template -struct compiletime_parts_provider { - compiletime_parts_provider() = delete; - template - FMT_CONSTEXPR compiletime_parts_provider(basic_string_view) {} - - const PartsContainer& parts() const { - static FMT_CONSTEXPR_DECL const PartsContainer prepared_parts = - prepare_compiletime_parts( - internal::to_string_view(Format{})); - - return prepared_parts; + const parts_container& parts() const { + static FMT_CONSTEXPR_DECL const auto compiled_parts = + compile_to_parts( + internal::to_string_view(S())); + return compiled_parts.data; } }; + +template +class compiled_format : private compiled_format_base { + public: + using typename compiled_format_base::char_type; + + private: + basic_string_view format_str_; + + template + friend auto cf::vformat_to(Range out, CompiledFormat& cf, + basic_format_args args) -> + typename Context::iterator; + + public: + compiled_format() = delete; + explicit constexpr compiled_format(basic_string_view format_str) + : compiled_format_base(format_str), format_str_(format_str) {} +}; + +#ifdef __cpp_if_constexpr +template struct type_list {}; + +// Returns a reference to the argument at index N from [first, rest...]. +template +constexpr const auto& get(const T& first, const Args&... rest) { + static_assert(N < 1 + sizeof...(Args), "index is out of bounds"); + if constexpr (N == 0) + return first; + else + return get(rest...); +} + +template struct get_type_impl; + +template struct get_type_impl> { + using type = remove_cvref_t(std::declval()...))>; +}; + +template +using get_type = typename get_type_impl::type; + +template struct text { + basic_string_view data; + using char_type = Char; + + template + OutputIt format(OutputIt out, const Args&...) const { + // TODO: reserve + return copy_str(data.begin(), data.end(), out); + } +}; + +template +constexpr text make_text(basic_string_view s, size_t pos, + size_t size) { + return {{&s[pos], size}}; +} + +template , int> = 0> +OutputIt format_default(OutputIt out, T value) { + // TODO: reserve + format_int fi(value); + return std::copy(fi.data(), fi.data() + fi.size(), out); +} + +template +OutputIt format_default(OutputIt out, double value) { + writer w(out); + w.write(value); + return w.out(); +} + +template +OutputIt format_default(OutputIt out, Char value) { + *out++ = value; + return out; +} + +template +OutputIt format_default(OutputIt out, const Char* value) { + auto length = std::char_traits::length(value); + return copy_str(value, value + length, out); +} + +// A replacement field that refers to argument N. +template struct field { + using char_type = Char; + + template + OutputIt format(OutputIt out, const Args&... args) const { + // This ensures that the argument type is convertile to `const T&`. + const T& arg = get(args...); + return format_default(out, arg); + } +}; + +template struct concat { + L lhs; + R rhs; + using char_type = typename L::char_type; + + template + OutputIt format(OutputIt out, const Args&... args) const { + out = lhs.format(out, args...); + return rhs.format(out, args...); + } +}; + +template +constexpr concat make_concat(L lhs, R rhs) { + return {lhs, rhs}; +} + +struct unknown_format {}; + +template +constexpr size_t parse_text(basic_string_view str, size_t pos) { + for (size_t size = str.size(); pos != size; ++pos) { + if (str[pos] == '{' || str[pos] == '}') break; + } + return pos; +} + +template +constexpr auto compile_format_string(S format_str); + +template +constexpr auto parse_tail(T head, S format_str) { + if constexpr (POS != to_string_view(format_str).size()) { + constexpr auto tail = compile_format_string(format_str); + if constexpr (std::is_same, + unknown_format>()) + return tail; + else + return make_concat(head, tail); + } else { + return head; + } +} + +// Compiles a non-empty format string and returns the compiled representation +// or unknown_format() on unrecognized input. +template +constexpr auto compile_format_string(S format_str) { + using char_type = typename S::char_type; + constexpr basic_string_view str = format_str; + if constexpr (str[POS] == '{') { + if (POS + 1 == str.size()) + throw format_error("unmatched '{' in format string"); + if constexpr (str[POS + 1] == '{') { + return parse_tail(make_text(str, POS, 1), format_str); + } else if constexpr (str[POS + 1] == '}') { + using type = get_type; + if constexpr (std::is_same::value) { + return parse_tail(field(), + format_str); + } else { + return unknown_format(); + } + } else { + return unknown_format(); + } + } else if constexpr (str[POS] == '}') { + if (POS + 1 == str.size()) + throw format_error("unmatched '}' in format string"); + return parse_tail(make_text(str, POS, 1), format_str); + } else { + constexpr auto end = parse_text(str, POS + 1); + return parse_tail(make_text(str, POS, end - POS), + format_str); + } +} +#endif // __cpp_if_constexpr } // namespace internal #if FMT_USE_CONSTEXPR +# ifdef __cpp_if_constexpr template ::value)> -FMT_CONSTEXPR auto compile(S format_str) -> internal::prepared_format< - S, - internal::compiletime_parts_provider< - S, - typename internal::compiletime_prepared_parts_type_provider::type>, - Args...> { - return format_str; -} -#endif - -template -auto compile(const Char (&format_str)[N]) -> internal::prepared_format< - std::basic_string, - internal::runtime_parts_provider>>, - Args...> { - return std::basic_string(format_str, N - 1); +constexpr auto compile(S format_str) { + constexpr basic_string_view str = format_str; + if constexpr (str.size() == 0) { + return internal::make_text(str, 0, 0); + } else { + constexpr auto result = + internal::compile_format_string, 0, 0>( + format_str); + if constexpr (std::is_same, + internal::unknown_format>()) { + return internal::compiled_format(to_string_view(format_str)); + } else { + return result; + } + } } template + typename Char = typename CompiledFormat::char_type, + FMT_ENABLE_IF(!std::is_base_of::value)> std::basic_string format(const CompiledFormat& cf, const Args&... args) { basic_memory_buffer buffer; - using range = internal::buffer_range; + using range = buffer_range; using context = buffer_context; - cf.template vformat_to(range(buffer), - {make_format_args(args...)}); + cf.format(std::back_inserter(buffer), args...); return to_string(buffer); } -template +template ::value)> +OutputIt format_to(OutputIt out, const CompiledFormat& cf, + const Args&... args) { + return cf.format(out, args...); +} +# else +template ::value)> +constexpr auto compile(S format_str) -> internal::compiled_format { + return internal::compiled_format(to_string_view(format_str)); +} +# endif // __cpp_if_constexpr +#endif // FMT_USE_CONSTEXPR + +// Compiles the format string which must be a string literal. +template +auto compile(const Char (&format_str)[N]) + -> internal::compiled_format { + return internal::compiled_format( + basic_string_view(format_str, N - 1)); +} + +template ::value)> +std::basic_string format(const CompiledFormat& cf, const Args&... args) { + basic_memory_buffer buffer; + using range = buffer_range; + using context = buffer_context; + internal::cf::vformat_to(range(buffer), cf, + {make_format_args(args...)}); + return to_string(buffer); +} + +template ::value)> OutputIt format_to(OutputIt out, const CompiledFormat& cf, const Args&... args) { using char_type = typename CompiledFormat::char_type; using range = internal::output_range; using context = format_context_t; - return cf.template vformat_to( - range(out), {make_format_args(args...)}); + return internal::cf::vformat_to( + range(out), cf, {make_format_args(args...)}); } template format_to_n(OutputIt out, size_t n, template std::size_t formatted_size(const CompiledFormat& cf, const Args&... args) { - return fmt::format_to( - internal::counting_iterator(), - cf, args...) - .count(); + return format_to(internal::counting_iterator(), cf, args...).count(); } FMT_END_NAMESPACE diff --git a/include/spdlog/fmt/bundled/core.h b/include/spdlog/fmt/bundled/core.h index bcce2f50..6a0846fc 100644 --- a/include/spdlog/fmt/bundled/core.h +++ b/include/spdlog/fmt/bundled/core.h @@ -8,7 +8,6 @@ #ifndef FMT_CORE_H_ #define FMT_CORE_H_ -#include #include // std::FILE #include #include @@ -16,7 +15,7 @@ #include // The fmt library version in the form major * 10000 + minor * 100 + patch. -#define FMT_VERSION 60000 +#define FMT_VERSION 60100 #ifdef __has_feature # define FMT_HAS_FEATURE(x) __has_feature(x) @@ -49,6 +48,12 @@ # define FMT_HAS_GXX_CXX11 0 #endif +#ifdef __NVCC__ +# define FMT_NVCC __NVCC__ +#else +# define FMT_NVCC 0 +#endif + #ifdef _MSC_VER # define FMT_MSC_VER _MSC_VER #else @@ -60,7 +65,8 @@ #ifndef FMT_USE_CONSTEXPR # define FMT_USE_CONSTEXPR \ (FMT_HAS_FEATURE(cxx_relaxed_constexpr) || FMT_MSC_VER >= 1910 || \ - (FMT_GCC_VERSION >= 600 && __cplusplus >= 201402L)) + (FMT_GCC_VERSION >= 600 && __cplusplus >= 201402L)) && \ + !FMT_NVCC #endif #if FMT_USE_CONSTEXPR # define FMT_CONSTEXPR constexpr @@ -133,6 +139,13 @@ # endif #endif +// Workaround broken [[deprecated]] in the Intel compiler and NVCC. +#if defined(__INTEL_COMPILER) || FMT_NVCC +# define FMT_DEPRECATED_ALIAS +#else +# define FMT_DEPRECATED_ALIAS FMT_DEPRECATED +#endif + #ifndef FMT_BEGIN_NAMESPACE # if FMT_HAS_FEATURE(cxx_inline_namespaces) || FMT_GCC_VERSION >= 404 || \ FMT_MSC_VER >= 1900 @@ -154,9 +167,9 @@ #if !defined(FMT_HEADER_ONLY) && defined(_WIN32) # ifdef FMT_EXPORT -# define FMT_API __declspec(dllexport) +# define FMT_API __pragma(warning(suppress : 4275)) __declspec(dllexport) # elif defined(FMT_SHARED) -# define FMT_API __declspec(dllimport) +# define FMT_API __pragma(warning(suppress : 4275)) __declspec(dllimport) # define FMT_EXTERN_TEMPLATE_API FMT_API # endif #endif @@ -173,10 +186,6 @@ # define FMT_EXTERN #endif -#ifndef FMT_ASSERT -# define FMT_ASSERT(condition, message) assert((condition) && message) -#endif - // libc++ supports string_view in pre-c++17. #if (FMT_HAS_INCLUDE() && \ (__cplusplus > 201402L || defined(_LIBCPP_VERSION))) || \ @@ -200,6 +209,8 @@ template using remove_reference_t = typename std::remove_reference::type; template using remove_const_t = typename std::remove_const::type; +template +using remove_cvref_t = typename std::remove_cv>::type; struct monostate {}; @@ -213,6 +224,19 @@ namespace internal { // A workaround for gcc 4.8 to make void_t work in a SFINAE context. template struct void_t_impl { using type = void; }; +void assert_fail(const char* file, int line, const char* message); + +#ifndef FMT_ASSERT +# ifdef NDEBUG +# define FMT_ASSERT(condition, message) +# else +# define FMT_ASSERT(condition, message) \ + ((condition) \ + ? void() \ + : fmt::internal::assert_fail(__FILE__, __LINE__, (message))) +# endif +#endif + #if defined(FMT_USE_STRING_VIEW) template using std_string_view = std::basic_string_view; #elif defined(FMT_USE_EXPERIMENTAL_STRING_VIEW) @@ -222,7 +246,21 @@ using std_string_view = std::experimental::basic_string_view; template struct std_string_view {}; #endif -// Casts nonnegative integer to unsigned. +#ifdef FMT_USE_INT128 +// Do nothing. +#elif defined(__SIZEOF_INT128__) +# define FMT_USE_INT128 1 +using int128_t = __int128_t; +using uint128_t = __uint128_t; +#else +# define FMT_USE_INT128 0 +#endif +#if !FMT_USE_INT128 +struct int128_t {}; +struct uint128_t {}; +#endif + +// Casts a nonnegative integer to unsigned. template FMT_CONSTEXPR typename std::make_unsigned::type to_unsigned(Int value) { FMT_ASSERT(value >= 0, "negative value"); @@ -266,10 +304,11 @@ template class basic_string_view { : 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()) {} + template + FMT_CONSTEXPR basic_string_view( + const std::basic_string& s) FMT_NOEXCEPT + : data_(s.data()), + size_(s.size()) {} template < typename S, @@ -286,6 +325,8 @@ template class basic_string_view { FMT_CONSTEXPR iterator begin() const { return data_; } FMT_CONSTEXPR iterator end() const { return data_ + size_; } + FMT_CONSTEXPR const Char& operator[](size_t pos) const { return data_[pos]; } + FMT_CONSTEXPR void remove_prefix(size_t n) { data_ += n; size_ -= n; @@ -357,10 +398,10 @@ inline basic_string_view to_string_view(const Char* s) { return s; } -template +template inline basic_string_view to_string_view( - const std::basic_string& s) { - return {s.data(), s.size()}; + const std::basic_string& s) { + return s; } template @@ -405,8 +446,8 @@ template struct char_t_impl::value>> { }; struct error_handler { - FMT_CONSTEXPR error_handler() {} - FMT_CONSTEXPR error_handler(const error_handler&) {} + FMT_CONSTEXPR error_handler() = default; + FMT_CONSTEXPR error_handler(const error_handler&) = default; // This function is intentionally not constexpr to give a compile-time error. FMT_NORETURN FMT_API void on_error(const char* message); @@ -416,10 +457,24 @@ struct error_handler { /** String's character type. */ template using char_t = typename internal::char_t_impl::type; -// Parsing context consisting of a format string range being parsed and an -// argument counter for automatic indexing. +/** + \rst + Parsing context consisting of a format string range being parsed and an + argument counter for automatic indexing. + + You can use one of the following type aliases for common character types: + + +-----------------------+-------------------------------------+ + | Type | Definition | + +=======================+=====================================+ + | format_parse_context | basic_format_parse_context | + +-----------------------+-------------------------------------+ + | wformat_parse_context | basic_format_parse_context | + +-----------------------+-------------------------------------+ + \endrst + */ template -class basic_parse_context : private ErrorHandler { +class basic_format_parse_context : private ErrorHandler { private: basic_string_view format_str_; int next_arg_id_; @@ -428,38 +483,47 @@ class basic_parse_context : private ErrorHandler { using char_type = Char; using iterator = typename basic_string_view::iterator; - explicit FMT_CONSTEXPR basic_parse_context(basic_string_view format_str, - ErrorHandler eh = ErrorHandler()) + explicit FMT_CONSTEXPR basic_format_parse_context( + basic_string_view format_str, ErrorHandler eh = ErrorHandler()) : ErrorHandler(eh), format_str_(format_str), next_arg_id_(0) {} - // Returns an iterator to the beginning of the format string range being - // parsed. + /** + Returns an iterator to the beginning of the format string range being + parsed. + */ FMT_CONSTEXPR iterator begin() const FMT_NOEXCEPT { return format_str_.begin(); } - // Returns an iterator past the end of the format string range being parsed. + /** + Returns an iterator past the end of the format string range being parsed. + */ FMT_CONSTEXPR iterator end() const FMT_NOEXCEPT { return format_str_.end(); } - // Advances the begin iterator to ``it``. + /** Advances the begin iterator to ``it``. */ FMT_CONSTEXPR void advance_to(iterator it) { format_str_.remove_prefix(internal::to_unsigned(it - begin())); } - // Returns the next argument index. + /** + Reports an error if using the manual argument indexing; otherwise returns + the next argument index and switches to the automatic indexing. + */ FMT_CONSTEXPR int next_arg_id() { if (next_arg_id_ >= 0) return next_arg_id_++; on_error("cannot switch from manual to automatic argument indexing"); return 0; } - FMT_CONSTEXPR bool check_arg_id(int) { - if (next_arg_id_ > 0) { + /** + Reports an error if using the automatic argument indexing; otherwise + switches to the manual indexing. + */ + FMT_CONSTEXPR void check_arg_id(int) { + if (next_arg_id_ > 0) on_error("cannot switch from automatic to manual argument indexing"); - return false; - } - next_arg_id_ = -1; - return true; + else + next_arg_id_ = -1; } FMT_CONSTEXPR void check_arg_id(basic_string_view) {} @@ -471,11 +535,14 @@ class basic_parse_context : private ErrorHandler { FMT_CONSTEXPR ErrorHandler error_handler() const { return *this; } }; -using format_parse_context = basic_parse_context; -using wformat_parse_context = basic_parse_context; +using format_parse_context = basic_format_parse_context; +using wformat_parse_context = basic_format_parse_context; -using parse_context FMT_DEPRECATED = basic_parse_context; -using wparse_context FMT_DEPRECATED = basic_parse_context; +template +using basic_parse_context FMT_DEPRECATED_ALIAS = + basic_format_parse_context; +using parse_context FMT_DEPRECATED_ALIAS = basic_format_parse_context; +using wparse_context FMT_DEPRECATED_ALIAS = basic_format_parse_context; template class basic_format_arg; template class basic_format_args; @@ -492,20 +559,17 @@ struct FMT_DEPRECATED convert_to_int : bool_constant::value && std::is_convertible::value> {}; -namespace internal { - // Specifies if T has an enabled formatter specialization. A type can be // formattable even if it doesn't have a formatter e.g. via a conversion. template using has_formatter = std::is_constructible>; +namespace internal { + /** A contiguous memory buffer with an optional growing ability. */ template class buffer { private: - buffer(const buffer&) = delete; - void operator=(const buffer&) = delete; - T* ptr_; std::size_t size_; std::size_t capacity_; @@ -532,7 +596,9 @@ template class buffer { using value_type = T; using const_reference = const T&; - virtual ~buffer() {} + buffer(const buffer&) = delete; + void operator=(const buffer&) = delete; + virtual ~buffer() = default; T* begin() FMT_NOEXCEPT { return ptr_; } T* end() FMT_NOEXCEPT { return ptr_ + size_; } @@ -626,10 +692,13 @@ enum type { uint_type, long_long_type, ulong_long_type, + int128_type, + uint128_type, bool_type, char_type, last_integer_type = char_type, // followed by floating-point types. + float_type, double_type, long_double_type, last_numeric_type = long_double_type, @@ -652,20 +721,23 @@ FMT_TYPE_CONSTANT(int, int_type); FMT_TYPE_CONSTANT(unsigned, uint_type); FMT_TYPE_CONSTANT(long long, long_long_type); FMT_TYPE_CONSTANT(unsigned long long, ulong_long_type); +FMT_TYPE_CONSTANT(int128_t, int128_type); +FMT_TYPE_CONSTANT(uint128_t, uint128_type); FMT_TYPE_CONSTANT(bool, bool_type); FMT_TYPE_CONSTANT(Char, char_type); +FMT_TYPE_CONSTANT(float, float_type); FMT_TYPE_CONSTANT(double, double_type); FMT_TYPE_CONSTANT(long double, long_double_type); FMT_TYPE_CONSTANT(const Char*, cstring_type); FMT_TYPE_CONSTANT(basic_string_view, string_type); FMT_TYPE_CONSTANT(const void*, pointer_type); -FMT_CONSTEXPR bool is_integral(type t) { +FMT_CONSTEXPR bool is_integral_type(type t) { FMT_ASSERT(t != named_arg_type, "invalid argument type"); return t > none_type && t <= last_integer_type; } -FMT_CONSTEXPR bool is_arithmetic(type t) { +FMT_CONSTEXPR bool is_arithmetic_type(type t) { FMT_ASSERT(t != named_arg_type, "invalid argument type"); return t > none_type && t <= last_numeric_type; } @@ -676,7 +748,7 @@ template struct string_value { }; template struct custom_value { - using parse_context = basic_parse_context; + using parse_context = basic_format_parse_context; const void* value; void (*format)(const void* arg, parse_context& parse_ctx, Context& ctx); }; @@ -691,8 +763,11 @@ template class value { unsigned uint_value; long long long_long_value; unsigned long long ulong_long_value; + int128_t int128_value; + uint128_t uint128_value; bool bool_value; char_type char_value; + float float_value; double double_value; long double long_double_value; const void* pointer; @@ -705,6 +780,9 @@ template class value { FMT_CONSTEXPR value(unsigned val) : uint_value(val) {} value(long long val) : long_long_value(val) {} value(unsigned long long val) : ulong_long_value(val) {} + value(int128_t val) : int128_value(val) {} + value(uint128_t val) : uint128_value(val) {} + value(float val) : float_value(val) {} value(double val) : double_value(val) {} value(long double val) : long_double_value(val) {} value(bool val) : bool_value(val) {} @@ -732,9 +810,9 @@ template class value { private: // Formats an argument of a custom type, such as a user-defined class. template - static void format_custom_arg(const void* arg, - basic_parse_context& parse_ctx, - Context& ctx) { + static void format_custom_arg( + const void* arg, basic_format_parse_context& parse_ctx, + Context& ctx) { Formatter f; parse_ctx.advance_to(f.parse(parse_ctx)); ctx.advance_to(f.format(*static_cast(arg), ctx)); @@ -764,6 +842,8 @@ template struct arg_mapper { FMT_CONSTEXPR ulong_type map(unsigned long val) { return val; } FMT_CONSTEXPR long long map(long long val) { return val; } FMT_CONSTEXPR unsigned long long map(unsigned long long val) { return val; } + FMT_CONSTEXPR int128_t map(int128_t val) { return val; } + FMT_CONSTEXPR uint128_t map(uint128_t val) { return val; } FMT_CONSTEXPR bool map(bool val) { return val; } template ::value)> @@ -774,7 +854,7 @@ template struct arg_mapper { return val; } - FMT_CONSTEXPR double map(float val) { return static_cast(val); } + FMT_CONSTEXPR float map(float val) { return val; } FMT_CONSTEXPR double map(double val) { return val; } FMT_CONSTEXPR long double map(long double val) { return val; } @@ -793,6 +873,15 @@ template struct arg_mapper { FMT_CONSTEXPR basic_string_view map(const T& val) { return basic_string_view(val); } + template < + typename T, + FMT_ENABLE_IF( + std::is_constructible, T>::value && + !std::is_constructible, T>::value && + !is_string::value)> + FMT_CONSTEXPR basic_string_view map(const T& val) { + return std_string_view(val); + } FMT_CONSTEXPR const char* map(const signed char* val) { static_assert(std::is_same::value, "invalid string type"); return reinterpret_cast(val); @@ -818,11 +907,14 @@ template struct arg_mapper { FMT_ENABLE_IF(std::is_enum::value && !has_formatter::value && !has_fallback_formatter::value)> - FMT_CONSTEXPR int map(const T& val) { - return static_cast(val); + FMT_CONSTEXPR auto map(const T& val) -> decltype( + map(static_cast::type>(val))) { + return map(static_cast::type>(val)); } template ::value && !is_char::value && + !std::is_constructible, + T>::value && (has_formatter::value || has_fallback_formatter::value))> FMT_CONSTEXPR const T& map(const T& val) { @@ -841,12 +933,13 @@ template struct arg_mapper { // A type constant after applying arg_mapper. template using mapped_type_constant = - type_constant().map(std::declval())), + type_constant().map(std::declval())), typename Context::char_type>; +enum { packed_arg_bits = 5 }; // Maximum number of arguments with packed types. -enum { max_packed_args = 15 }; -enum : unsigned long long { is_unpacked_bit = 1ull << 63 }; +enum { max_packed_args = 63 / packed_arg_bits }; +enum : unsigned long long { is_unpacked_bit = 1ULL << 63 }; template class arg_map; } // namespace internal @@ -877,7 +970,8 @@ template class basic_format_arg { public: explicit handle(internal::custom_value custom) : custom_(custom) {} - void format(basic_parse_context& parse_ctx, Context& ctx) const { + void format(basic_format_parse_context& parse_ctx, + Context& ctx) const { custom_.format(custom_.value, parse_ctx, ctx); } @@ -893,8 +987,8 @@ template class basic_format_arg { internal::type type() const { return type_; } - bool is_integral() const { return internal::is_integral(type_); } - bool is_arithmetic() const { return internal::is_arithmetic(type_); } + bool is_integral() const { return internal::is_integral_type(type_); } + bool is_arithmetic() const { return internal::is_arithmetic_type(type_); } }; /** @@ -923,10 +1017,22 @@ FMT_CONSTEXPR auto visit_format_arg(Visitor&& vis, return vis(arg.value_.long_long_value); case internal::ulong_long_type: return vis(arg.value_.ulong_long_value); +#if FMT_USE_INT128 + case internal::int128_type: + return vis(arg.value_.int128_value); + case internal::uint128_type: + return vis(arg.value_.uint128_value); +#else + case internal::int128_type: + case internal::uint128_type: + break; +#endif case internal::bool_type: return vis(arg.value_.bool_value); case internal::char_type: return vis(arg.value_.char_value); + case internal::float_type: + return vis(arg.value_.float_value); case internal::double_type: return vis(arg.value_.double_value); case internal::long_double_type: @@ -948,9 +1054,6 @@ namespace internal { // A map from argument names to their values for named arguments. template class arg_map { private: - arg_map(const arg_map&) = delete; - void operator=(const arg_map&) = delete; - using char_type = typename Context::char_type; struct entry { @@ -968,6 +1071,8 @@ template class arg_map { } public: + arg_map(const arg_map&) = delete; + void operator=(const arg_map&) = delete; arg_map() : map_(nullptr), size_(0) {} void init(const basic_format_args& args); ~arg_map() { delete[] map_; } @@ -990,6 +1095,8 @@ class locale_ref { locale_ref() : locale_(nullptr) {} template explicit locale_ref(const Locale& loc); + explicit operator bool() const FMT_NOEXCEPT { return locale_ != nullptr; } + template Locale get() const; }; @@ -998,7 +1105,7 @@ template constexpr unsigned long long encode_types() { return 0; } template constexpr unsigned long long encode_types() { return mapped_type_constant::value | - (encode_types() << 4); + (encode_types() << packed_arg_bits); } template @@ -1034,14 +1141,13 @@ template class basic_format_context { internal::arg_map map_; internal::locale_ref loc_; - basic_format_context(const basic_format_context&) = delete; - void operator=(const basic_format_context&) = delete; - public: using iterator = OutputIt; using format_arg = basic_format_arg; template using formatter_type = formatter; + basic_format_context(const basic_format_context&) = delete; + void operator=(const basic_format_context&) = delete; /** Constructs a ``basic_format_context`` object. References to the arguments are stored in the object so make sure they have appropriate lifetimes. @@ -1143,8 +1249,9 @@ template class basic_format_args { bool is_packed() const { return (types_ & internal::is_unpacked_bit) == 0; } internal::type type(int index) const { - int shift = index * 4; - return static_cast((types_ & (0xfull << shift)) >> shift); + int shift = index * internal::packed_arg_bits; + unsigned int mask = (1 << internal::packed_arg_bits) - 1; + return static_cast((types_ >> shift) & mask); } friend class internal::arg_map; @@ -1371,7 +1478,7 @@ inline std::basic_string format(const S& format_str, Args&&... args) { } FMT_API void vprint(std::FILE* f, string_view format_str, format_args args); -FMT_API void vprint(std::FILE* f, wstring_view format_str, wformat_args args); +FMT_API void vprint(string_view format_str, format_args args); /** \rst @@ -1391,9 +1498,6 @@ inline void print(std::FILE* f, const S& format_str, Args&&... args) { internal::make_args_checked(format_str, args...)); } -FMT_API void vprint(string_view format_str, format_args args); -FMT_API void vprint(wstring_view format_str, wformat_args args); - /** \rst Prints formatted data to ``stdout``. diff --git a/include/spdlog/fmt/bundled/format-inl.h b/include/spdlog/fmt/bundled/format-inl.h index 3fbb8060..72b30466 100644 --- a/include/spdlog/fmt/bundled/format-inl.h +++ b/include/spdlog/fmt/bundled/format-inl.h @@ -1,4 +1,4 @@ -// Formatting library for C++ +// Formatting library for C++ - implementation // // Copyright (c) 2012 - 2016, Victor Zverovich // All rights reserved. @@ -10,14 +10,11 @@ #include "format.h" -#include - +#include #include -#include #include #include #include -#include // for std::ptrdiff_t #include // for std::memmove #include #if !defined(FMT_STATIC_THOUSANDS_SEPARATOR) @@ -47,25 +44,22 @@ #ifdef _MSC_VER # pragma warning(push) -# pragma warning(disable : 4127) // conditional expression is constant # pragma warning(disable : 4702) // unreachable code -// Disable deprecation warning for strerror. The latter is not called but -// MSVC fails to detect it. -# pragma warning(disable : 4996) #endif // Dummy implementations of strerror_r and strerror_s called if corresponding // system functions are not available. -inline fmt::internal::null<> strerror_r(int, char*, ...) { - return fmt::internal::null<>(); -} -inline fmt::internal::null<> strerror_s(char*, std::size_t, ...) { - return fmt::internal::null<>(); -} +inline fmt::internal::null<> strerror_r(int, char*, ...) { return {}; } +inline fmt::internal::null<> strerror_s(char*, std::size_t, ...) { return {}; } FMT_BEGIN_NAMESPACE namespace internal { +FMT_FUNC void assert_fail(const char* file, int line, const char* message) { + print(stderr, "{}:{}: assertion failed: {}", file, line, message); + std::abort(); +} + #ifndef _MSC_VER # define FMT_SNPRINTF snprintf #else // _MSC_VER @@ -81,7 +75,7 @@ inline int fmt_snprintf(char* buffer, size_t size, const char* format, ...) { using format_func = void (*)(internal::buffer&, int, string_view); -// Portable thread-safe version of strerror. +// A portable thread-safe version of strerror. // Sets buffer to point to a string describing the error code. // This can be either a pointer to a string stored in buffer, // or a pointer to some static immutable string. @@ -158,7 +152,7 @@ FMT_FUNC void format_error_code(internal::buffer& out, int error_code, static const char ERROR_STR[] = "error "; // Subtract 2 to account for terminating null characters in SEP and ERROR_STR. std::size_t error_code_size = sizeof(SEP) + sizeof(ERROR_STR) - 2; - auto abs_value = static_cast>(error_code); + auto abs_value = static_cast>(error_code); if (internal::is_negative(error_code)) { abs_value = 0 - abs_value; ++error_code_size; @@ -206,6 +200,9 @@ template Locale locale_ref::get() const { return locale_ ? *static_cast(locale_) : std::locale(); } +template FMT_FUNC std::string grouping_impl(locale_ref loc) { + return std::use_facet>(loc.get()).grouping(); +} template FMT_FUNC Char thousands_sep_impl(locale_ref loc) { return std::use_facet>(loc.get()) .thousands_sep(); @@ -217,6 +214,10 @@ template FMT_FUNC Char decimal_point_impl(locale_ref loc) { } // namespace internal #else template +FMT_FUNC std::string internal::grouping_impl(locale_ref) { + return "\03"; +} +template FMT_FUNC Char internal::thousands_sep_impl(locale_ref) { return FMT_STATIC_THOUSANDS_SEPARATOR; } @@ -226,8 +227,8 @@ FMT_FUNC Char internal::decimal_point_impl(locale_ref) { } #endif -FMT_API FMT_FUNC format_error::~format_error() FMT_NOEXCEPT {} -FMT_API FMT_FUNC system_error::~system_error() FMT_NOEXCEPT {} +FMT_API FMT_FUNC format_error::~format_error() FMT_NOEXCEPT = default; +FMT_API FMT_FUNC system_error::~system_error() FMT_NOEXCEPT = default; FMT_FUNC void system_error::init(int err_code, string_view format_str, format_args args) { @@ -241,27 +242,13 @@ FMT_FUNC void system_error::init(int err_code, string_view format_str, namespace internal { template <> FMT_FUNC int count_digits<4>(internal::fallback_uintptr n) { - // Assume little endian; pointer formatting is implementation-defined anyway. + // fallback_uintptr is always stored in little endian. int i = static_cast(sizeof(void*)) - 1; while (i > 0 && n.value[i] == 0) --i; auto char_digits = std::numeric_limits::digits / 4; return i >= 0 ? i * char_digits + count_digits<4, unsigned>(n.value[i]) : 1; } -template -int format_float(char* buf, std::size_t size, const char* format, int precision, - T value) { -#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION - if (precision > 100000) - throw std::runtime_error( - "fuzz mode - avoid large allocation inside snprintf"); -#endif - // Suppress the warning about nonliteral format string. - auto snprintf_ptr = FMT_SNPRINTF; - return precision < 0 ? snprintf_ptr(buf, size, format, value) - : snprintf_ptr(buf, size, format, precision, value); -} - template const char basic_data::digits[] = "0001020304050607080910111213141516171819" @@ -274,14 +261,14 @@ template const char basic_data::hex_digits[] = "0123456789abcdef"; #define FMT_POWERS_OF_10(factor) \ - factor * 10, factor * 100, factor * 1000, factor * 10000, factor * 100000, \ - factor * 1000000, factor * 10000000, factor * 100000000, \ - factor * 1000000000 + factor * 10, (factor)*100, (factor)*1000, (factor)*10000, (factor)*100000, \ + (factor)*1000000, (factor)*10000000, (factor)*100000000, \ + (factor)*1000000000 template const uint64_t basic_data::powers_of_10_64[] = { - 1, FMT_POWERS_OF_10(1), FMT_POWERS_OF_10(1000000000ull), - 10000000000000000000ull}; + 1, FMT_POWERS_OF_10(1), FMT_POWERS_OF_10(1000000000ULL), + 10000000000000000000ULL}; template const uint32_t basic_data::zero_or_powers_of_10_32[] = {0, @@ -289,8 +276,8 @@ const uint32_t basic_data::zero_or_powers_of_10_32[] = {0, template const uint64_t basic_data::zero_or_powers_of_10_64[] = { - 0, FMT_POWERS_OF_10(1), FMT_POWERS_OF_10(1000000000ull), - 10000000000000000000ull}; + 0, FMT_POWERS_OF_10(1), FMT_POWERS_OF_10(1000000000ULL), + 10000000000000000000ULL}; // Normalized 64-bit significands of pow(10, k), for k = -348, -340, ..., 340. // These are generated by support/compute-powers.py. @@ -346,12 +333,24 @@ 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"; +template const char basic_data::signs[] = {0, '-', '+', ' '}; template struct bits { static FMT_CONSTEXPR_DECL const int value = static_cast(sizeof(T) * std::numeric_limits::digits); }; +class fp; +template fp normalize(fp value); + +// Lower (upper) boundary is a value half way between a floating-point value +// and its predecessor (successor). Boundaries have the same exponent as the +// value so only significands are stored. +struct boundaries { + uint64_t lower; + uint64_t upper; +}; + // A handmade floating-point number f * pow(2, e). class fp { private: @@ -363,7 +362,7 @@ class fp { static FMT_CONSTEXPR_DECL const int double_significand_size = std::numeric_limits::digits - 1; static FMT_CONSTEXPR_DECL const uint64_t implicit_bit = - 1ull << double_significand_size; + 1ULL << double_significand_size; public: significand_type f; @@ -377,95 +376,377 @@ class fp { // Constructs fp from an IEEE754 double. It is a template to prevent compile // errors on platforms where double is not IEEE754. - template explicit fp(Double d) { + template explicit fp(Double d) { assign(d); } + + // Normalizes the value converted from double and multiplied by (1 << SHIFT). + template friend fp normalize(fp value) { + // Handle subnormals. + const auto shifted_implicit_bit = fp::implicit_bit << SHIFT; + while ((value.f & shifted_implicit_bit) == 0) { + value.f <<= 1; + --value.e; + } + // Subtract 1 to account for hidden bit. + const auto offset = + fp::significand_size - fp::double_significand_size - SHIFT - 1; + value.f <<= offset; + value.e -= offset; + return value; + } + + // Assigns d to this and return true iff predecessor is closer than successor. + template + bool assign(Double d) { // Assume double is in the format [sign][exponent][significand]. using limits = std::numeric_limits; const int exponent_size = bits::value - double_significand_size - 1; // -1 for sign const uint64_t significand_mask = implicit_bit - 1; - const uint64_t exponent_mask = (~0ull >> 1) & ~significand_mask; + const uint64_t exponent_mask = (~0ULL >> 1) & ~significand_mask; const int exponent_bias = (1 << exponent_size) - limits::max_exponent - 1; auto u = bit_cast(d); - auto biased_e = (u & exponent_mask) >> double_significand_size; f = u & significand_mask; + auto biased_e = (u & exponent_mask) >> double_significand_size; + // Predecessor is closer if d is a normalized power of 2 (f == 0) other than + // the smallest normalized number (biased_e > 1). + bool is_predecessor_closer = f == 0 && biased_e > 1; if (biased_e != 0) f += implicit_bit; else biased_e = 1; // Subnormals use biased exponent 1 (min exponent). e = static_cast(biased_e - exponent_bias - double_significand_size); + return is_predecessor_closer; } - // Normalizes the value converted from double and multiplied by (1 << SHIFT). - template void normalize() { - // Handle subnormals. - auto shifted_implicit_bit = implicit_bit << SHIFT; - while ((f & shifted_implicit_bit) == 0) { - f <<= 1; - --e; - } - // Subtract 1 to account for hidden bit. - auto offset = significand_size - double_significand_size - SHIFT - 1; - f <<= offset; - e -= offset; + template + bool assign(Double) { + *this = fp(); + return false; } - // Compute lower and upper boundaries (m^- and m^+ in the Grisu paper), where - // a boundary is a value half way between the number and its predecessor + // Assigns d to this together with computing lower and upper boundaries, + // where a boundary is a value half way between the number and its predecessor // (lower) or successor (upper). The upper boundary is normalized and lower // has the same exponent but may be not normalized. - void compute_boundaries(fp& lower, fp& upper) const { - lower = - f == implicit_bit ? fp((f << 2) - 1, e - 2) : fp((f << 1) - 1, e - 1); - upper = fp((f << 1) + 1, e - 1); - upper.normalize<1>(); // 1 is to account for the exponent shift above. + template boundaries assign_with_boundaries(Double d) { + bool is_lower_closer = assign(d); + fp lower = + is_lower_closer ? fp((f << 2) - 1, e - 2) : fp((f << 1) - 1, e - 1); + // 1 in normalize accounts for the exponent shift above. + fp upper = normalize<1>(fp((f << 1) + 1, e - 1)); lower.f <<= lower.e - upper.e; - lower.e = upper.e; + return boundaries{lower.f, upper.f}; + } + + template boundaries assign_float_with_boundaries(Double d) { + assign(d); + constexpr int min_normal_e = std::numeric_limits::min_exponent - + std::numeric_limits::digits; + significand_type half_ulp = 1 << (std::numeric_limits::digits - + std::numeric_limits::digits - 1); + if (min_normal_e > e) half_ulp <<= min_normal_e - e; + fp upper = normalize<0>(fp(f + half_ulp, e)); + fp lower = fp( + f - (half_ulp >> ((f == implicit_bit && e > min_normal_e) ? 1 : 0)), e); + lower.f <<= lower.e - upper.e; + return boundaries{lower.f, upper.f}; } }; -// Returns an fp number representing x - y. Result may not be normalized. -inline fp operator-(fp x, fp y) { - FMT_ASSERT(x.f >= y.f && x.e == y.e, "invalid operands"); - return fp(x.f - y.f, x.e); -} +inline bool operator==(fp x, fp y) { return x.f == y.f && x.e == y.e; } -// Computes an fp number r with r.f = x.f * y.f / pow(2, 64) rounded to nearest -// with half-up tie breaking, r.e = x.e + y.e + 64. Result may not be -// normalized. -FMT_FUNC fp operator*(fp x, fp y) { - int exp = x.e + y.e + 64; +// Computes lhs * rhs / pow(2, 64) rounded to nearest with half-up tie breaking. +inline uint64_t multiply(uint64_t lhs, uint64_t rhs) { #if FMT_USE_INT128 - auto product = static_cast<__uint128_t>(x.f) * y.f; + auto product = static_cast<__uint128_t>(lhs) * rhs; auto f = static_cast(product >> 64); - if ((static_cast(product) & (1ULL << 63)) != 0) ++f; - return fp(f, exp); + return (static_cast(product) & (1ULL << 63)) != 0 ? f + 1 : f; #else // Multiply 32-bit parts of significands. uint64_t mask = (1ULL << 32) - 1; - uint64_t a = x.f >> 32, b = x.f & mask; - uint64_t c = y.f >> 32, d = y.f & mask; + uint64_t a = lhs >> 32, b = lhs & mask; + uint64_t c = rhs >> 32, d = rhs & mask; uint64_t ac = a * c, bc = b * c, ad = a * d, bd = b * d; // Compute mid 64-bit of result and round. uint64_t mid = (bd >> 32) + (ad & mask) + (bc & mask) + (1U << 31); - return fp(ac + (ad >> 32) + (bc >> 32) + (mid >> 32), exp); + return ac + (ad >> 32) + (bc >> 32) + (mid >> 32); #endif } -// Returns cached power (of 10) c_k = c_k.f * pow(2, c_k.e) such that its -// (binary) exponent satisfies min_exponent <= c_k.e <= min_exponent + 28. +inline fp operator*(fp x, fp y) { return {multiply(x.f, y.f), x.e + y.e + 64}; } + +// Returns a cached power of 10 `c_k = c_k.f * pow(2, c_k.e)` such that its +// (binary) exponent satisfies `min_exponent <= c_k.e <= min_exponent + 28`. FMT_FUNC fp get_cached_power(int min_exponent, int& pow10_exponent) { - const double one_over_log2_10 = 0.30102999566398114; // 1 / log2(10) + const uint64_t one_over_log2_10 = 0x4d104d42; // round(pow(2, 32) / log2(10)) int index = static_cast( - std::ceil((min_exponent + fp::significand_size - 1) * one_over_log2_10)); + static_cast( + (min_exponent + fp::significand_size - 1) * one_over_log2_10 + + ((uint64_t(1) << 32) - 1) // ceil + ) >> + 32 // arithmetic shift + ); // Decimal exponent of the first (smallest) cached power of 10. const int first_dec_exp = -348; // Difference between 2 consecutive decimal exponents in cached powers of 10. const int dec_exp_step = 8; index = (index - first_dec_exp - 1) / dec_exp_step + 1; pow10_exponent = first_dec_exp + index * dec_exp_step; - return fp(data::pow10_significands[index], data::pow10_exponents[index]); + return {data::pow10_significands[index], data::pow10_exponents[index]}; } +// A simple accumulator to hold the sums of terms in bigint::square if uint128_t +// is not available. +struct accumulator { + uint64_t lower; + uint64_t upper; + + accumulator() : lower(0), upper(0) {} + explicit operator uint32_t() const { return static_cast(lower); } + + void operator+=(uint64_t n) { + lower += n; + if (lower < n) ++upper; + } + void operator>>=(int shift) { + assert(shift == 32); + (void)shift; + lower = (upper << 32) | (lower >> 32); + upper >>= 32; + } +}; + +class bigint { + private: + // A bigint is stored as an array of bigits (big digits), with bigit at index + // 0 being the least significant one. + using bigit = uint32_t; + using double_bigit = uint64_t; + enum { bigits_capacity = 32 }; + basic_memory_buffer bigits_; + int exp_; + + static FMT_CONSTEXPR_DECL const int bigit_bits = bits::value; + + friend struct formatter; + + void subtract_bigits(int index, bigit other, bigit& borrow) { + auto result = static_cast(bigits_[index]) - other - borrow; + bigits_[index] = static_cast(result); + borrow = static_cast(result >> (bigit_bits * 2 - 1)); + } + + void remove_leading_zeros() { + int num_bigits = static_cast(bigits_.size()) - 1; + while (num_bigits > 0 && bigits_[num_bigits] == 0) --num_bigits; + bigits_.resize(num_bigits + 1); + } + + // Computes *this -= other assuming aligned bigints and *this >= other. + void subtract_aligned(const bigint& other) { + FMT_ASSERT(other.exp_ >= exp_, "unaligned bigints"); + FMT_ASSERT(compare(*this, other) >= 0, ""); + bigit borrow = 0; + int i = other.exp_ - exp_; + for (int j = 0, n = static_cast(other.bigits_.size()); j != n; + ++i, ++j) { + subtract_bigits(i, other.bigits_[j], borrow); + } + while (borrow > 0) subtract_bigits(i, 0, borrow); + remove_leading_zeros(); + } + + void multiply(uint32_t value) { + const double_bigit wide_value = value; + bigit carry = 0; + for (size_t i = 0, n = bigits_.size(); i < n; ++i) { + double_bigit result = bigits_[i] * wide_value + carry; + bigits_[i] = static_cast(result); + carry = static_cast(result >> bigit_bits); + } + if (carry != 0) bigits_.push_back(carry); + } + + void multiply(uint64_t value) { + const bigit mask = ~bigit(0); + const double_bigit lower = value & mask; + const double_bigit upper = value >> bigit_bits; + double_bigit carry = 0; + for (size_t i = 0, n = bigits_.size(); i < n; ++i) { + double_bigit result = bigits_[i] * lower + (carry & mask); + carry = + bigits_[i] * upper + (result >> bigit_bits) + (carry >> bigit_bits); + bigits_[i] = static_cast(result); + } + while (carry != 0) { + bigits_.push_back(carry & mask); + carry >>= bigit_bits; + } + } + + public: + bigint() : exp_(0) {} + explicit bigint(uint64_t n) { assign(n); } + ~bigint() { assert(bigits_.capacity() <= bigits_capacity); } + + bigint(const bigint&) = delete; + void operator=(const bigint&) = delete; + + void assign(const bigint& other) { + bigits_.resize(other.bigits_.size()); + auto data = other.bigits_.data(); + std::copy(data, data + other.bigits_.size(), bigits_.data()); + exp_ = other.exp_; + } + + void assign(uint64_t n) { + int num_bigits = 0; + do { + bigits_[num_bigits++] = n & ~bigit(0); + n >>= bigit_bits; + } while (n != 0); + bigits_.resize(num_bigits); + exp_ = 0; + } + + int num_bigits() const { return static_cast(bigits_.size()) + exp_; } + + bigint& operator<<=(int shift) { + assert(shift >= 0); + exp_ += shift / bigit_bits; + shift %= bigit_bits; + if (shift == 0) return *this; + bigit carry = 0; + for (size_t i = 0, n = bigits_.size(); i < n; ++i) { + bigit c = bigits_[i] >> (bigit_bits - shift); + bigits_[i] = (bigits_[i] << shift) + carry; + carry = c; + } + if (carry != 0) bigits_.push_back(carry); + return *this; + } + + template bigint& operator*=(Int value) { + FMT_ASSERT(value > 0, ""); + multiply(uint32_or_64_or_128_t(value)); + return *this; + } + + friend int compare(const bigint& lhs, const bigint& rhs) { + int num_lhs_bigits = lhs.num_bigits(), num_rhs_bigits = rhs.num_bigits(); + if (num_lhs_bigits != num_rhs_bigits) + return num_lhs_bigits > num_rhs_bigits ? 1 : -1; + int i = static_cast(lhs.bigits_.size()) - 1; + int j = static_cast(rhs.bigits_.size()) - 1; + int end = i - j; + if (end < 0) end = 0; + for (; i >= end; --i, --j) { + bigit lhs_bigit = lhs.bigits_[i], rhs_bigit = rhs.bigits_[j]; + if (lhs_bigit != rhs_bigit) return lhs_bigit > rhs_bigit ? 1 : -1; + } + if (i != j) return i > j ? 1 : -1; + return 0; + } + + // Returns compare(lhs1 + lhs2, rhs). + friend int add_compare(const bigint& lhs1, const bigint& lhs2, + const bigint& rhs) { + int max_lhs_bigits = (std::max)(lhs1.num_bigits(), lhs2.num_bigits()); + int num_rhs_bigits = rhs.num_bigits(); + if (max_lhs_bigits + 1 < num_rhs_bigits) return -1; + if (max_lhs_bigits > num_rhs_bigits) return 1; + auto get_bigit = [](const bigint& n, int i) -> bigit { + return i >= n.exp_ && i < n.num_bigits() ? n.bigits_[i - n.exp_] : 0; + }; + double_bigit borrow = 0; + int min_exp = (std::min)((std::min)(lhs1.exp_, lhs2.exp_), rhs.exp_); + for (int i = num_rhs_bigits - 1; i >= min_exp; --i) { + double_bigit sum = + static_cast(get_bigit(lhs1, i)) + get_bigit(lhs2, i); + bigit rhs_bigit = get_bigit(rhs, i); + if (sum > rhs_bigit + borrow) return 1; + borrow = rhs_bigit + borrow - sum; + if (borrow > 1) return -1; + borrow <<= bigit_bits; + } + return borrow != 0 ? -1 : 0; + } + + // Assigns pow(10, exp) to this bigint. + void assign_pow10(int exp) { + assert(exp >= 0); + if (exp == 0) return assign(1); + // Find the top bit. + int bitmask = 1; + while (exp >= bitmask) bitmask <<= 1; + bitmask >>= 1; + // pow(10, exp) = pow(5, exp) * pow(2, exp). First compute pow(5, exp) by + // repeated squaring and multiplication. + assign(5); + bitmask >>= 1; + while (bitmask != 0) { + square(); + if ((exp & bitmask) != 0) *this *= 5; + bitmask >>= 1; + } + *this <<= exp; // Multiply by pow(2, exp) by shifting. + } + + void square() { + basic_memory_buffer n(std::move(bigits_)); + int num_bigits = static_cast(bigits_.size()); + int num_result_bigits = 2 * num_bigits; + bigits_.resize(num_result_bigits); + using accumulator_t = conditional_t; + auto sum = accumulator_t(); + for (int bigit_index = 0; bigit_index < num_bigits; ++bigit_index) { + // Compute bigit at position bigit_index of the result by adding + // cross-product terms n[i] * n[j] such that i + j == bigit_index. + for (int i = 0, j = bigit_index; j >= 0; ++i, --j) { + // Most terms are multiplied twice which can be optimized in the future. + sum += static_cast(n[i]) * n[j]; + } + bigits_[bigit_index] = static_cast(sum); + sum >>= bits::value; // Compute the carry. + } + // Do the same for the top half. + for (int bigit_index = num_bigits; bigit_index < num_result_bigits; + ++bigit_index) { + for (int j = num_bigits - 1, i = bigit_index - j; i < num_bigits;) + sum += static_cast(n[i++]) * n[j--]; + bigits_[bigit_index] = static_cast(sum); + sum >>= bits::value; + } + --num_result_bigits; + remove_leading_zeros(); + exp_ *= 2; + } + + // Divides this bignum by divisor, assigning the remainder to this and + // returning the quotient. + int divmod_assign(const bigint& divisor) { + FMT_ASSERT(this != &divisor, ""); + if (compare(*this, divisor) < 0) return 0; + int num_bigits = static_cast(bigits_.size()); + FMT_ASSERT(divisor.bigits_[divisor.bigits_.size() - 1] != 0, ""); + int exp_difference = exp_ - divisor.exp_; + if (exp_difference > 0) { + // Align bigints by adding trailing zeros to simplify subtraction. + bigits_.resize(num_bigits + exp_difference); + for (int i = num_bigits - 1, j = i + exp_difference; i >= 0; --i, --j) + bigits_[j] = bigits_[i]; + std::uninitialized_fill_n(bigits_.data(), exp_difference, 0); + exp_ -= exp_difference; + } + int quotient = 0; + do { + subtract_aligned(divisor); + ++quotient; + } while (compare(*this, divisor) >= 0); + return quotient; + } +}; + enum round_direction { unknown, up, down }; // Given the divisor (normally a power of 10), the remainder = v % divisor for @@ -500,13 +781,13 @@ enum result { // error: the size of the region (lower, upper) outside of which numbers // definitely do not round to value (Delta in Grisu3). template -digits::result grisu_gen_digits(fp value, uint64_t error, int& exp, - Handler& handler) { - fp one(1ull << -value.e, value.e); +FMT_ALWAYS_INLINE digits::result grisu_gen_digits(fp value, uint64_t error, + int& exp, Handler& handler) { + const fp one(1ULL << -value.e, value.e); // The integral part of scaled value (p1 in Grisu) = value / one. It cannot be // zero because it contains a product of two 64-bit numbers with MSB set (due // to normalization) - 1, shifted right by at most 60 bits. - uint32_t integral = static_cast(value.f >> -one.e); + auto integral = static_cast(value.f >> -one.e); FMT_ASSERT(integral != 0, ""); FMT_ASSERT(integral == value.f >> -one.e, ""); // The fractional part of scaled value (p2 in Grisu) c = value % one. @@ -519,44 +800,39 @@ digits::result grisu_gen_digits(fp value, uint64_t error, int& exp, // Generate digits for the integral part. This can produce up to 10 digits. do { uint32_t digit = 0; - // This optimization by miloyip reduces the number of integer divisions by + auto divmod_integral = [&](uint32_t divisor) { + digit = integral / divisor; + integral %= divisor; + }; + // This optimization by Milo Yip reduces the number of integer divisions by // one per iteration. switch (exp) { case 10: - digit = integral / 1000000000; - integral %= 1000000000; + divmod_integral(1000000000); break; case 9: - digit = integral / 100000000; - integral %= 100000000; + divmod_integral(100000000); break; case 8: - digit = integral / 10000000; - integral %= 10000000; + divmod_integral(10000000); break; case 7: - digit = integral / 1000000; - integral %= 1000000; + divmod_integral(1000000); break; case 6: - digit = integral / 100000; - integral %= 100000; + divmod_integral(100000); break; case 5: - digit = integral / 10000; - integral %= 10000; + divmod_integral(10000); break; case 4: - digit = integral / 1000; - integral %= 1000; + divmod_integral(1000); break; case 3: - digit = integral / 100; - integral %= 100; + divmod_integral(100); break; case 2: - digit = integral / 10; - integral %= 10; + divmod_integral(10); break; case 1: digit = integral; @@ -640,7 +916,7 @@ struct fixed_handler { }; // The shortest representation digit handler. -template struct grisu_shortest_handler { +struct grisu_shortest_handler { char* buf; int size; // Distance between scaled value and upper bound (wp_W in Grisu3). @@ -666,11 +942,6 @@ template struct grisu_shortest_handler { uint64_t error, int exp, bool integral) { buf[size++] = digit; if (remainder >= error) return digits::more; - if (GRISU_VERSION != 3) { - uint64_t d = integral ? diff : diff * data::powers_of_10_64[-exp]; - round(d, divisor, remainder, error); - return digits::done; - } uint64_t unit = integral ? 1 : data::powers_of_10_64[-exp]; uint64_t up = (diff - 1) * unit; // wp_Wup round(up, divisor, remainder, error); @@ -686,151 +957,289 @@ template struct grisu_shortest_handler { } }; -template > -FMT_API bool grisu_format(Double value, buffer& buf, int precision, - unsigned options, int& exp) { +// Formats value using a variation of the Fixed-Precision Positive +// Floating-Point Printout ((FPP)^2) algorithm by Steele & White: +// https://fmt.dev/p372-steele.pdf. +template +void fallback_format(Double d, buffer& buf, int& exp10) { + bigint numerator; // 2 * R in (FPP)^2. + bigint denominator; // 2 * S in (FPP)^2. + // lower and upper are differences between value and corresponding boundaries. + bigint lower; // (M^- in (FPP)^2). + bigint upper_store; // upper's value if different from lower. + bigint* upper = nullptr; // (M^+ in (FPP)^2). + fp value; + // Shift numerator and denominator by an extra bit or two (if lower boundary + // is closer) to make lower and upper integers. This eliminates multiplication + // by 2 during later computations. + // TODO: handle float + int shift = value.assign(d) ? 2 : 1; + uint64_t significand = value.f << shift; + if (value.e >= 0) { + numerator.assign(significand); + numerator <<= value.e; + lower.assign(1); + lower <<= value.e; + if (shift != 1) { + upper_store.assign(1); + upper_store <<= value.e + 1; + upper = &upper_store; + } + denominator.assign_pow10(exp10); + denominator <<= 1; + } else if (exp10 < 0) { + numerator.assign_pow10(-exp10); + lower.assign(numerator); + if (shift != 1) { + upper_store.assign(numerator); + upper_store <<= 1; + upper = &upper_store; + } + numerator *= significand; + denominator.assign(1); + denominator <<= shift - value.e; + } else { + numerator.assign(significand); + denominator.assign_pow10(exp10); + denominator <<= shift - value.e; + lower.assign(1); + if (shift != 1) { + upper_store.assign(1ULL << 1); + upper = &upper_store; + } + } + if (!upper) upper = &lower; + // Invariant: value == (numerator / denominator) * pow(10, exp10). + bool even = (value.f & 1) == 0; + int num_digits = 0; + char* data = buf.data(); + for (;;) { + int digit = numerator.divmod_assign(denominator); + bool low = compare(numerator, lower) - even < 0; // numerator <[=] lower. + // numerator + upper >[=] pow10: + bool high = add_compare(numerator, *upper, denominator) + even > 0; + data[num_digits++] = static_cast('0' + digit); + if (low || high) { + if (!low) { + ++data[num_digits - 1]; + } else if (high) { + int result = add_compare(numerator, numerator, denominator); + // Round half to even. + if (result > 0 || (result == 0 && (digit % 2) != 0)) + ++data[num_digits - 1]; + } + buf.resize(num_digits); + exp10 -= num_digits - 1; + return; + } + numerator *= 10; + lower *= 10; + if (upper != &lower) *upper *= 10; + } +} + +// Formats value using the Grisu algorithm +// (https://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf) +// if T is a IEEE754 binary32 or binary64 and snprintf otherwise. +template +int format_float(T value, int precision, float_specs specs, buffer& buf) { + static_assert(!std::is_same(), ""); FMT_ASSERT(value >= 0, "value is negative"); - bool fixed = (options & grisu_options::fixed) != 0; + + const bool fixed = specs.format == float_format::fixed; if (value <= 0) { // <= instead of == to silence a warning. if (precision <= 0 || !fixed) { - exp = 0; buf.push_back('0'); - } else { - exp = -precision; - buf.resize(to_unsigned(precision)); - std::uninitialized_fill_n(buf.data(), precision, '0'); + return 0; } - return true; + buf.resize(to_unsigned(precision)); + std::uninitialized_fill_n(buf.data(), precision, '0'); + return -precision; } - fp fp_value(value); + if (!specs.use_grisu) return snprintf_float(value, precision, specs, buf); + + int exp = 0; const int min_exp = -60; // alpha in Grisu. int cached_exp10 = 0; // K in Grisu. if (precision != -1) { - if (precision > 17) return false; - fp_value.normalize(); - auto cached_pow = get_cached_power( - min_exp - (fp_value.e + fp::significand_size), cached_exp10); - fp_value = fp_value * cached_pow; + if (precision > 17) return snprintf_float(value, precision, specs, buf); + fp normalized = normalize(fp(value)); + const auto cached_pow = get_cached_power( + min_exp - (normalized.e + fp::significand_size), cached_exp10); + normalized = normalized * cached_pow; fixed_handler handler{buf.data(), 0, precision, -cached_exp10, fixed}; - if (grisu_gen_digits(fp_value, 1, exp, handler) == digits::error) - return false; - buf.resize(to_unsigned(handler.size)); - } else { - fp lower, upper; // w^- and w^+ in the Grisu paper. - fp_value.compute_boundaries(lower, upper); - // Find a cached power of 10 such that multiplying upper by it will bring - // the exponent in the range [min_exp, -32]. - auto cached_pow = get_cached_power( // \tilde{c}_{-k} in Grisu. - min_exp - (upper.e + fp::significand_size), cached_exp10); - fp_value.normalize(); - fp_value = fp_value * cached_pow; - lower = lower * cached_pow; // \tilde{M}^- in Grisu. - upper = upper * cached_pow; // \tilde{M}^+ in Grisu. - assert(min_exp <= upper.e && upper.e <= -32); - auto result = digits::result(); - int size = 0; - if ((options & grisu_options::grisu3) != 0) { - --lower.f; // \tilde{M}^- - 1 ulp -> M^-_{\downarrow}. - ++upper.f; // \tilde{M}^+ + 1 ulp -> M^+_{\uparrow}. - // Numbers outside of (lower, upper) definitely do not round to value. - grisu_shortest_handler<3> handler{buf.data(), 0, (upper - fp_value).f}; - result = grisu_gen_digits(upper, upper.f - lower.f, exp, handler); - size = handler.size; - } else { - ++lower.f; // \tilde{M}^- + 1 ulp -> M^-_{\uparrow}. - --upper.f; // \tilde{M}^+ - 1 ulp -> M^+_{\downarrow}. - grisu_shortest_handler<2> handler{buf.data(), 0, (upper - fp_value).f}; - result = grisu_gen_digits(upper, upper.f - lower.f, exp, handler); - size = handler.size; + if (grisu_gen_digits(normalized, 1, exp, handler) == digits::error) + return snprintf_float(value, precision, specs, buf); + int num_digits = handler.size; + if (!fixed) { + // Remove trailing zeros. + while (num_digits > 0 && buf[num_digits - 1] == '0') { + --num_digits; + ++exp; + } } - if (result == digits::error) return false; - buf.resize(to_unsigned(size)); + buf.resize(to_unsigned(num_digits)); + } else { + fp fp_value; + auto boundaries = specs.binary32 + ? fp_value.assign_float_with_boundaries(value) + : fp_value.assign_with_boundaries(value); + fp_value = normalize(fp_value); + // Find a cached power of 10 such that multiplying value by it will bring + // the exponent in the range [min_exp, -32]. + const fp cached_pow = get_cached_power( + min_exp - (fp_value.e + fp::significand_size), cached_exp10); + // Multiply value and boundaries by the cached power of 10. + fp_value = fp_value * cached_pow; + boundaries.lower = multiply(boundaries.lower, cached_pow.f); + boundaries.upper = multiply(boundaries.upper, cached_pow.f); + assert(min_exp <= fp_value.e && fp_value.e <= -32); + --boundaries.lower; // \tilde{M}^- - 1 ulp -> M^-_{\downarrow}. + ++boundaries.upper; // \tilde{M}^+ + 1 ulp -> M^+_{\uparrow}. + // Numbers outside of (lower, upper) definitely do not round to value. + grisu_shortest_handler handler{buf.data(), 0, + boundaries.upper - fp_value.f}; + auto result = + grisu_gen_digits(fp(boundaries.upper, fp_value.e), + boundaries.upper - boundaries.lower, exp, handler); + if (result == digits::error) { + exp += handler.size - cached_exp10 - 1; + fallback_format(value, buf, exp); + return exp; + } + buf.resize(to_unsigned(handler.size)); } - exp -= cached_exp10; - return true; + return exp - cached_exp10; } -template -char* sprintf_format(Double value, internal::buffer& buf, - sprintf_specs specs) { +template +int snprintf_float(T value, int precision, float_specs specs, + buffer& buf) { // Buffer capacity must be non-zero, otherwise MSVC's vsnprintf_s will fail. - FMT_ASSERT(buf.capacity() != 0, "empty buffer"); + FMT_ASSERT(buf.capacity() > buf.size(), "empty buffer"); + static_assert(!std::is_same(), ""); - // Build format string. - enum { max_format_size = 10 }; // longest format: %#-*.*Lg + // Subtract 1 to account for the difference in precision since we use %e for + // both general and exponent format. + if (specs.format == float_format::general || + specs.format == float_format::exp) + precision = (precision >= 0 ? precision : 6) - 1; + + // Build the format string. + enum { max_format_size = 7 }; // Ths longest format is "%#.*Le". char format[max_format_size]; char* format_ptr = format; *format_ptr++ = '%'; - if (specs.alt || !specs.type) *format_ptr++ = '#'; - if (specs.precision >= 0) { + if (specs.trailing_zeros) *format_ptr++ = '#'; + if (precision >= 0) { *format_ptr++ = '.'; *format_ptr++ = '*'; } - if (std::is_same::value) *format_ptr++ = 'L'; - - char type = specs.type; - - if (type == '%') - type = 'f'; - else if (type == 0 || type == 'n') - type = 'g'; -#if FMT_MSC_VER - if (type == 'F') { - // MSVC's printf doesn't support 'F'. - type = 'f'; - } -#endif - *format_ptr++ = type; + if (std::is_same()) *format_ptr++ = 'L'; + *format_ptr++ = specs.format != float_format::hex + ? (specs.format == float_format::fixed ? 'f' : 'e') + : (specs.upper ? 'A' : 'a'); *format_ptr = '\0'; // Format using snprintf. - char* start = nullptr; - char* decimal_point_pos = nullptr; + auto offset = buf.size(); for (;;) { - std::size_t buffer_size = buf.capacity(); - start = &buf[0]; - int result = - format_float(start, buffer_size, format, specs.precision, value); - if (result >= 0) { - unsigned n = internal::to_unsigned(result); - if (n < buf.capacity()) { - // Find the decimal point. - auto p = buf.data(), end = p + n; - if (*p == '+' || *p == '-') ++p; - if (specs.type != 'a' && specs.type != 'A') { - while (p < end && *p >= '0' && *p <= '9') ++p; - if (p < end && *p != 'e' && *p != 'E') { - decimal_point_pos = p; - if (!specs.type) { - // Keep only one trailing zero after the decimal point. - ++p; - if (*p == '0') ++p; - while (p != end && *p >= '1' && *p <= '9') ++p; - char* where = p; - while (p != end && *p == '0') ++p; - if (p == end || *p < '0' || *p > '9') { - if (p != end) std::memmove(where, p, to_unsigned(end - p)); - n -= static_cast(p - where); - } - } - } - } - 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); + auto begin = buf.data() + offset; + auto capacity = buf.capacity() - offset; +#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION + if (precision > 100000) + throw std::runtime_error( + "fuzz mode - avoid large allocation inside snprintf"); +#endif + // Suppress the warning about a nonliteral format string. + auto snprintf_ptr = FMT_SNPRINTF; + int result = precision >= 0 + ? snprintf_ptr(begin, capacity, format, precision, value) + : snprintf_ptr(begin, capacity, format, value); + if (result < 0) { + buf.reserve(buf.capacity() + 1); // The buffer will grow exponentially. + continue; } + unsigned size = to_unsigned(result); + // Size equal to capacity means that the last character was truncated. + if (size >= capacity) { + buf.reserve(size + offset + 1); // Add 1 for the terminating '\0'. + continue; + } + auto is_digit = [](char c) { return c >= '0' && c <= '9'; }; + if (specs.format == float_format::fixed) { + if (precision == 0) { + buf.resize(size); + return 0; + } + // Find and remove the decimal point. + auto end = begin + size, p = end; + do { + --p; + } while (is_digit(*p)); + int fraction_size = static_cast(end - p - 1); + std::memmove(p, p + 1, fraction_size); + buf.resize(size - 1); + return -fraction_size; + } + if (specs.format == float_format::hex) { + buf.resize(size + offset); + return 0; + } + // Find and parse the exponent. + auto end = begin + size, exp_pos = end; + do { + --exp_pos; + } while (*exp_pos != 'e'); + char sign = exp_pos[1]; + assert(sign == '+' || sign == '-'); + int exp = 0; + auto p = exp_pos + 2; // Skip 'e' and sign. + do { + assert(is_digit(*p)); + exp = exp * 10 + (*p++ - '0'); + } while (p != end); + if (sign == '-') exp = -exp; + int fraction_size = 0; + if (exp_pos != begin + 1) { + // Remove trailing zeros. + auto fraction_end = exp_pos - 1; + while (*fraction_end == '0') --fraction_end; + // Move the fractional part left to get rid of the decimal point. + fraction_size = static_cast(fraction_end - begin - 1); + std::memmove(begin + 1, begin + 2, fraction_size); + } + buf.resize(fraction_size + offset + 1); + return exp - fraction_size; } - return decimal_point_pos; } } // namespace internal +template <> struct formatter { + format_parse_context::iterator parse(format_parse_context& ctx) { + return ctx.begin(); + } + + format_context::iterator format(const internal::bigint& n, + format_context& ctx) { + auto out = ctx.out(); + bool first = true; + for (auto i = n.bigits_.size(); i > 0; --i) { + auto value = n.bigits_[i - 1]; + if (first) { + out = format_to(out, "{:x}", value); + first = false; + continue; + } + out = format_to(out, "{:08x}", value); + } + if (n.exp_ > 0) + out = format_to(out, "p{}", n.exp_ * internal::bigint::bigit_bits); + return out; + } +}; + #if FMT_USE_WINDOWS_H FMT_FUNC internal::utf8_to_utf16::utf8_to_utf16(string_view s) { @@ -974,23 +1383,10 @@ FMT_FUNC void vprint(std::FILE* f, string_view format_str, format_args args) { internal::fwrite_fully(buffer.data(), 1, buffer.size(), f); } -FMT_FUNC void vprint(std::FILE* f, wstring_view format_str, wformat_args args) { - wmemory_buffer buffer; - internal::vformat_to(buffer, format_str, args); - buffer.push_back(L'\0'); - if (std::fputws(buffer.data(), f) == -1) { - FMT_THROW(system_error(errno, "cannot write to file")); - } -} - FMT_FUNC void vprint(string_view format_str, format_args args) { vprint(stdout, format_str, args); } -FMT_FUNC void vprint(wstring_view format_str, wformat_args args) { - vprint(stdout, format_str, args); -} - FMT_END_NAMESPACE #ifdef _MSC_VER diff --git a/include/spdlog/fmt/bundled/format.h b/include/spdlog/fmt/bundled/format.h index f27996d3..398c2a77 100644 --- a/include/spdlog/fmt/bundled/format.h +++ b/include/spdlog/fmt/bundled/format.h @@ -33,18 +33,16 @@ #ifndef FMT_FORMAT_H_ #define FMT_FORMAT_H_ +#include "core.h" + #include -#include +#include #include #include -#include -#include #include #include #include -#include "core.h" - #ifdef __clang__ # define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__) #else @@ -71,6 +69,12 @@ # define FMT_HAS_BUILTIN(x) 0 #endif +#if FMT_HAS_CPP_ATTRIBUTE(fallthrough) >= 201603 && __cplusplus >= 201703 +# define FMT_FALLTHROUGH [[fallthrough]] +#else +# define FMT_FALLTHROUGH +#endif + #ifndef FMT_THROW # if FMT_EXCEPTIONS # if FMT_MSC_VER @@ -84,7 +88,7 @@ template inline void do_throw(const Exception& x) { } } // namespace internal FMT_END_NAMESPACE -# define FMT_THROW(x) fmt::internal::do_throw(x) +# define FMT_THROW(x) internal::do_throw(x) # else # define FMT_THROW(x) throw x # endif @@ -92,7 +96,7 @@ FMT_END_NAMESPACE # define FMT_THROW(x) \ do { \ static_cast(sizeof(x)); \ - assert(false); \ + FMT_ASSERT(false, ""); \ } while (false) # endif #endif @@ -123,14 +127,6 @@ FMT_END_NAMESPACE # endif #endif -#ifdef FMT_USE_INT128 -// Do nothing. -#elif defined(__SIZEOF_INT128__) -# define FMT_USE_INT128 1 -#else -# define FMT_USE_INT128 0 -#endif - // __builtin_clz is broken in clang with Microsoft CodeGen: // https://github.com/fmtlib/fmt/issues/519 #if (FMT_GCC_VERSION || FMT_HAS_BUILTIN(__builtin_clz)) && !FMT_MSC_VER @@ -156,14 +152,14 @@ inline uint32_t clz(uint32_t x) { unsigned long r = 0; _BitScanReverse(&r, x); - assert(x != 0); + FMT_ASSERT(x != 0, ""); // Static analysis complains about using uninitialized data // "r", but the only way that can happen is if "x" is 0, // which the callers guarantee to not happen. # pragma warning(suppress : 6102) return 31 - r; } -# define FMT_BUILTIN_CLZ(n) fmt::internal::clz(n) +# define FMT_BUILTIN_CLZ(n) internal::clz(n) # if defined(_WIN64) && !defined(__clang__) # pragma intrinsic(_BitScanReverse64) @@ -181,32 +177,36 @@ inline uint32_t clzll(uint64_t x) { _BitScanReverse(&r, static_cast(x)); # endif - assert(x != 0); + FMT_ASSERT(x != 0, ""); // Static analysis complains about using uninitialized data // "r", but the only way that can happen is if "x" is 0, // which the callers guarantee to not happen. # pragma warning(suppress : 6102) return 63 - r; } -# define FMT_BUILTIN_CLZLL(n) fmt::internal::clzll(n) +# define FMT_BUILTIN_CLZLL(n) internal::clzll(n) } // namespace internal FMT_END_NAMESPACE #endif +// Enable the deprecated numeric alignment. +#ifndef FMT_NUMERIC_ALIGN +# define FMT_NUMERIC_ALIGN 1 +#endif + +// Enable the deprecated percent specifier. +#ifndef FMT_DEPRECATED_PERCENT +# define FMT_DEPRECATED_PERCENT 0 +#endif + FMT_BEGIN_NAMESPACE namespace internal { -// A fallback implementation of uintptr_t for systems that lack it. -struct fallback_uintptr { - unsigned char value[sizeof(void*)]; -}; -#ifdef UINTPTR_MAX -using uintptr_t = ::uintptr_t; -#else -using uintptr_t = fallback_uintptr; -#endif +// A helper function to suppress bogus "conditional expression is constant" +// warnings. +template inline T const_check(T value) { return value; } -// An equivalent of `*reinterpret_cast(&source)` that doesn't produce +// An equivalent of `*reinterpret_cast(&source)` that doesn't have // undefined behavior (e.g. due to type aliasing). // Example: uint64_t d = bit_cast(2.718); template @@ -217,6 +217,50 @@ inline Dest bit_cast(const Source& source) { return dest; } +inline bool is_big_endian() { + auto u = 1u; + struct bytes { + char data[sizeof(u)]; + }; + return bit_cast(u).data[0] == 0; +} + +// A fallback implementation of uintptr_t for systems that lack it. +struct fallback_uintptr { + unsigned char value[sizeof(void*)]; + + fallback_uintptr() = default; + explicit fallback_uintptr(const void* p) { + *this = bit_cast(p); + if (is_big_endian()) { + for (size_t i = 0, j = sizeof(void*) - 1; i < j; ++i, --j) + std::swap(value[i], value[j]); + } + } +}; +#ifdef UINTPTR_MAX +using uintptr_t = ::uintptr_t; +inline uintptr_t to_uintptr(const void* p) { return bit_cast(p); } +#else +using uintptr_t = fallback_uintptr; +inline fallback_uintptr to_uintptr(const void* p) { + return fallback_uintptr(p); +} +#endif + +// Returns the largest possible value for type T. Same as +// std::numeric_limits::max() but shorter and not affected by the max macro. +template constexpr T max_value() { + return (std::numeric_limits::max)(); +} +template constexpr int num_bits() { + return std::numeric_limits::digits; +} +template <> constexpr int num_bits() { + return static_cast(sizeof(void*) * + std::numeric_limits::digits); +} + // An approximation of iterator_t for pre-C++20 systems. template using iterator_t = decltype(std::begin(std::declval())); @@ -290,19 +334,21 @@ inline Iterator& reserve(Iterator& it, std::size_t) { // An output iterator that counts the number of objects written to it and // discards them. -template class counting_iterator { +class counting_iterator { private: std::size_t count_; - mutable T blackhole_; public: using iterator_category = std::output_iterator_tag; - using value_type = T; using difference_type = std::ptrdiff_t; - using pointer = T*; - using reference = T&; + using pointer = void; + using reference = void; using _Unchecked_type = counting_iterator; // Mark iterator as checked. + struct value_type { + template void operator=(const T&) {} + }; + counting_iterator() : count_(0) {} std::size_t count() const { return count_; } @@ -318,7 +364,7 @@ template class counting_iterator { return it; } - T& operator*() const { return blackhole_; } + value_type operator*() const { return {}; } }; template class truncating_iterator_base { @@ -413,17 +459,6 @@ class output_range { sentinel end() const { return {}; } // Sentinel is not used yet. }; -// A range with an iterator appending to a buffer. -template -class buffer_range - : public output_range>, T> { - public: - using iterator = std::back_insert_iterator>; - using output_range::output_range; - buffer_range(buffer& buf) - : output_range(std::back_inserter(buf)) {} -}; - template inline size_t count_code_points(basic_string_view s) { return s.size(); @@ -439,6 +474,24 @@ inline size_t count_code_points(basic_string_view s) { return num_code_points; } +template +inline size_t code_point_index(basic_string_view s, size_t n) { + size_t size = s.size(); + return n < size ? n : size; +} + +// Calculates the index of the nth code point in a UTF-8 string. +inline size_t code_point_index(basic_string_view s, size_t n) { + const char8_t* data = s.data(); + size_t num_code_points = 0; + for (size_t i = 0, size = s.size(); i != size; ++i) { + if ((data[i] & 0xc0) != 0x80 && ++num_code_points > n) { + return i; + } + } + return s.size(); +} + inline char8_t to_char8_t(char c) { return static_cast(c); } template @@ -460,7 +513,7 @@ OutputIt copy_str(InputIt begin, InputIt end, OutputIt it) { } #ifndef FMT_USE_GRISU -# define FMT_USE_GRISU 0 +# define FMT_USE_GRISU 1 #endif template constexpr bool use_grisu() { @@ -478,6 +531,17 @@ void buffer::append(const U* begin, const U* end) { } } // namespace internal +// A range with an iterator appending to a buffer. +template +class buffer_range : public internal::output_range< + std::back_insert_iterator>, T> { + public: + using iterator = std::back_insert_iterator>; + using internal::output_range::output_range; + buffer_range(internal::buffer& buf) + : internal::output_range(std::back_inserter(buf)) {} +}; + // A UTF-8 string view. class u8string_view : public basic_string_view { public: @@ -552,7 +616,7 @@ class basic_memory_buffer : private Allocator, public internal::buffer { : Allocator(alloc) { this->set(store_, SIZE); } - ~basic_memory_buffer() { deallocate(); } + ~basic_memory_buffer() FMT_OVERRIDE { deallocate(); } private: // Move data from other to this buffer. @@ -581,15 +645,15 @@ class basic_memory_buffer : private Allocator, public internal::buffer { of the other object to it. \endrst */ - basic_memory_buffer(basic_memory_buffer&& other) { move(other); } + basic_memory_buffer(basic_memory_buffer&& other) FMT_NOEXCEPT { move(other); } /** \rst Moves the content of the other ``basic_memory_buffer`` object to this one. \endrst */ - basic_memory_buffer& operator=(basic_memory_buffer&& other) { - assert(this != &other); + basic_memory_buffer& operator=(basic_memory_buffer&& other) FMT_NOEXCEPT { + FMT_ASSERT(this != &other, ""); deallocate(); move(other); return *this; @@ -628,7 +692,11 @@ class FMT_API format_error : public std::runtime_error { explicit format_error(const char* message) : std::runtime_error(message) {} explicit format_error(const std::string& message) : std::runtime_error(message) {} - ~format_error() FMT_NOEXCEPT; + format_error(const format_error&) = default; + format_error& operator=(const format_error&) = default; + format_error(format_error&&) = default; + format_error& operator=(format_error&&) = default; + ~format_error() FMT_NOEXCEPT FMT_OVERRIDE; }; namespace internal { @@ -644,11 +712,12 @@ FMT_CONSTEXPR bool is_negative(T) { return false; } -// Smallest of uint32_t and uint64_t that is large enough to represent all -// values of T. +// Smallest of uint32_t, uint64_t, uint128_t that is large enough to +// represent all values of T. template -using uint32_or_64_t = - conditional_t::digits <= 32, uint32_t, uint64_t>; +using uint32_or_64_or_128_t = conditional_t< + std::numeric_limits::digits <= 32, uint32_t, + conditional_t::digits <= 64, uint64_t, uint128_t>>; // Static data is placed in this class template for the header-only config. template struct FMT_EXTERN_TEMPLATE_API basic_data { @@ -663,6 +732,7 @@ template struct FMT_EXTERN_TEMPLATE_API basic_data { static const char background_color[]; static const char reset_color[5]; static const wchar_t wreset_color[5]; + static const char signs[]; }; FMT_EXTERN template struct basic_data; @@ -697,6 +767,23 @@ inline int count_digits(uint64_t n) { } #endif +#if FMT_USE_INT128 +inline int count_digits(uint128_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 + // "Three Optimization Tips for C++". See speed-test for a comparison. + if (n < 10) return count; + if (n < 100) return count + 1; + if (n < 1000) return count + 2; + if (n < 10000) return count + 3; + n /= 10000U; + count += 4; + } +} +#endif + // Counts the number of digits in n. BITS = log2(radix). template inline int count_digits(UInt n) { int num_digits = 0; @@ -708,17 +795,14 @@ template inline int count_digits(UInt n) { template <> int count_digits<4>(internal::fallback_uintptr n); -#if FMT_HAS_CPP_ATTRIBUTE(always_inline) -# define FMT_ALWAYS_INLINE __attribute__((always_inline)) +#if FMT_GCC_VERSION || FMT_CLANG_VERSION +# define FMT_ALWAYS_INLINE inline __attribute__((always_inline)) #else # define FMT_ALWAYS_INLINE #endif -template -inline char* lg(uint32_t n, Handler h) FMT_ALWAYS_INLINE; - // Computes g = floor(log10(n)) and calls h.on(n); -template inline char* lg(uint32_t n, Handler h) { +template FMT_ALWAYS_INLINE char* lg(uint32_t n, Handler h) { return n < 100 ? n < 10 ? h.template on<0>(n) : h.template on<1>(n) : n < 1000000 ? n < 10000 ? n < 1000 ? h.template on<2>(n) @@ -779,6 +863,14 @@ inline int count_digits(uint32_t n) { } #endif +template FMT_API std::string grouping_impl(locale_ref loc); +template inline std::string grouping(locale_ref loc) { + return grouping_impl(loc); +} +template <> inline std::string grouping(locale_ref loc) { + return grouping_impl(loc); +} + template FMT_API Char thousands_sep_impl(locale_ref loc); template inline Char thousands_sep(locale_ref loc) { return Char(thousands_sep_impl(loc)); @@ -808,7 +900,7 @@ inline Char* format_decimal(Char* buffer, UInt value, int num_digits, // Integer division is slow so do it for a group of two digits instead // of for every digit. The idea comes from the talk by Alexandrescu // "Three Optimization Tips for C++". See speed-test for a comparison. - unsigned index = static_cast((value % 100) * 2); + auto index = static_cast((value % 100) * 2); value /= 100; *--buffer = static_cast(data::digits[index + 1]); add_thousands_sep(buffer); @@ -819,20 +911,26 @@ inline Char* format_decimal(Char* buffer, UInt value, int num_digits, *--buffer = static_cast('0' + value); return end; } - unsigned index = static_cast(value * 2); + auto index = static_cast(value * 2); *--buffer = static_cast(data::digits[index + 1]); add_thousands_sep(buffer); *--buffer = static_cast(data::digits[index]); return end; } +template constexpr int digits10() noexcept { + return std::numeric_limits::digits10; +} +template <> constexpr int digits10() noexcept { return 38; } +template <> constexpr int digits10() noexcept { return 38; } + template inline Iterator format_decimal(Iterator out, UInt value, int num_digits, F add_thousands_sep) { FMT_ASSERT(num_digits >= 0, "invalid digit count"); // Buffer should be large enough to hold all digits (<= digits10 + 1). - enum { max_size = std::numeric_limits::digits10 + 1 }; - Char buffer[max_size + max_size / 3]; + enum { max_size = digits10() + 1 }; + Char buffer[2 * max_size]; auto end = format_decimal(buffer, value, num_digits, add_thousands_sep); return internal::copy_str(buffer, end, out); } @@ -881,7 +979,7 @@ Char* format_uint(Char* buffer, internal::fallback_uintptr n, int 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). - char buffer[std::numeric_limits::digits / BASE_BITS + 1]; + char buffer[num_bits() / BASE_BITS + 1]; format_uint(buffer, value, num_digits, upper); return internal::copy_str(buffer, buffer + num_digits, out); } @@ -929,9 +1027,8 @@ class utf16_to_utf8 { FMT_API int convert(wstring_view s); }; -FMT_API void format_windows_error(fmt::internal::buffer& out, - int error_code, - fmt::string_view message) FMT_NOEXCEPT; +FMT_API void format_windows_error(internal::buffer& out, int error_code, + string_view message) FMT_NOEXCEPT; #endif template struct null {}; @@ -991,9 +1088,29 @@ using format_specs = basic_format_specs; namespace internal { +// A floating-point presentation format. +enum class float_format : unsigned char { + general, // General: exponent notation or fixed point based on magnitude. + exp, // Exponent notation with the default precision of 6, e.g. 1.2e-3. + fixed, // Fixed point with the default precision of 6, e.g. 0.0012. + hex +}; + +struct float_specs { + int precision; + float_format format : 8; + sign_t sign : 8; + bool upper : 1; + bool locale : 1; + bool percent : 1; + bool binary32 : 1; + bool use_grisu : 1; + bool trailing_zeros : 1; +}; + // Writes the exponent exp in the form "[+-]d{2,3}" to buffer. template It write_exponent(int exp, It it) { - FMT_ASSERT(-1000 < exp && exp < 1000, "exponent out of range"); + FMT_ASSERT(-10000 < exp && exp < 10000, "exponent out of range"); if (exp < 0) { *it++ = static_cast('-'); exp = -exp; @@ -1001,7 +1118,9 @@ template It write_exponent(int exp, It it) { *it++ = static_cast('+'); } if (exp >= 100) { - *it++ = static_cast(static_cast('0' + exp / 100)); + const char* top = data::digits + (exp / 100) * 2; + if (exp >= 1000) *it++ = static_cast(top[0]); + *it++ = static_cast(top[1]); exp %= 100; } const char* d = data::digits + exp * 2; @@ -1010,103 +1129,121 @@ template It write_exponent(int exp, It it) { return it; } -struct gen_digits_params { - int num_digits; - bool fixed; - bool upper; - bool trailing_zeros; -}; +template class float_writer { + private: + // The number is given as v = digits_ * pow(10, exp_). + const char* digits_; + int num_digits_; + int exp_; + size_t size_; + float_specs specs_; + Char decimal_point_; -// The number is given as v = digits * pow(10, exp). -template -It grisu_prettify(const char* digits, int size, int exp, It it, - gen_digits_params params, Char decimal_point) { - // pow(10, full_exp - 1) <= v <= pow(10, full_exp). - int full_exp = size + exp; - if (!params.fixed) { - // Insert a decimal point after the first digit and add an exponent. - *it++ = static_cast(*digits); - if (size > 1) *it++ = decimal_point; - exp += size - 1; - it = copy_str(digits + 1, digits + size, it); - if (size < params.num_digits) - it = std::fill_n(it, params.num_digits - size, static_cast('0')); - *it++ = static_cast(params.upper ? 'E' : 'e'); - return write_exponent(exp, it); - } - if (size <= full_exp) { - // 1234e7 -> 12340000000[.0+] - it = copy_str(digits, digits + size, it); - it = std::fill_n(it, full_exp - size, static_cast('0')); - int num_zeros = (std::max)(params.num_digits - full_exp, 1); - if (params.trailing_zeros) { - *it++ = decimal_point; + template It prettify(It it) const { + // pow(10, full_exp - 1) <= v <= pow(10, full_exp). + int full_exp = num_digits_ + exp_; + if (specs_.format == float_format::exp) { + // Insert a decimal point after the first digit and add an exponent. + *it++ = static_cast(*digits_); + if (num_digits_ > 1) *it++ = decimal_point_; + it = copy_str(digits_ + 1, digits_ + num_digits_, it); + int num_zeros = specs_.precision - num_digits_; + if (num_zeros > 0 && specs_.trailing_zeros) + it = std::fill_n(it, num_zeros, static_cast('0')); + *it++ = static_cast(specs_.upper ? 'E' : 'e'); + return write_exponent(full_exp - 1, it); + } + if (num_digits_ <= full_exp) { + // 1234e7 -> 12340000000[.0+] + it = copy_str(digits_, digits_ + num_digits_, it); + it = std::fill_n(it, full_exp - num_digits_, static_cast('0')); + if (specs_.trailing_zeros) { + *it++ = decimal_point_; + int num_zeros = specs_.precision - full_exp; + if (num_zeros <= 0) { + if (specs_.format != float_format::fixed) + *it++ = static_cast('0'); + return it; + } #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION - if (num_zeros > 1000) - throw std::runtime_error("fuzz mode - avoiding excessive cpu use"); + if (num_zeros > 1000) + throw std::runtime_error("fuzz mode - avoiding excessive cpu use"); #endif - it = std::fill_n(it, num_zeros, static_cast('0')); - } - } else if (full_exp > 0) { - // 1234e-2 -> 12.34[0+] - it = copy_str(digits, digits + full_exp, it); - if (!params.trailing_zeros) { - // Remove trailing zeros. - while (size > full_exp && digits[size - 1] == '0') --size; - if (size != full_exp) *it++ = decimal_point; - return copy_str(digits + full_exp, digits + size, it); - } - *it++ = decimal_point; - it = copy_str(digits + full_exp, digits + size, it); - if (params.num_digits > size) { - // Add trailing zeros. - int num_zeros = params.num_digits - size; - it = std::fill_n(it, num_zeros, static_cast('0')); - } - } else { - // 1234e-6 -> 0.001234 - *it++ = static_cast('0'); - int num_zeros = -full_exp; - if (params.num_digits >= 0 && params.num_digits < num_zeros) - num_zeros = params.num_digits; - if (!params.trailing_zeros) - while (size > 0 && digits[size - 1] == '0') --size; - if (num_zeros != 0 || size != 0) { - *it++ = decimal_point; - it = std::fill_n(it, num_zeros, static_cast('0')); - it = copy_str(digits, digits + size, it); + it = std::fill_n(it, num_zeros, static_cast('0')); + } + } else if (full_exp > 0) { + // 1234e-2 -> 12.34[0+] + it = copy_str(digits_, digits_ + full_exp, it); + if (!specs_.trailing_zeros) { + // Remove trailing zeros. + int num_digits = num_digits_; + while (num_digits > full_exp && digits_[num_digits - 1] == '0') + --num_digits; + if (num_digits != full_exp) *it++ = decimal_point_; + return copy_str(digits_ + full_exp, digits_ + num_digits, it); + } + *it++ = decimal_point_; + it = copy_str(digits_ + full_exp, digits_ + num_digits_, it); + if (specs_.precision > num_digits_) { + // Add trailing zeros. + int num_zeros = specs_.precision - num_digits_; + it = std::fill_n(it, num_zeros, static_cast('0')); + } + } else { + // 1234e-6 -> 0.001234 + *it++ = static_cast('0'); + int num_zeros = -full_exp; + if (specs_.precision >= 0 && specs_.precision < num_zeros) + num_zeros = specs_.precision; + int num_digits = num_digits_; + if (!specs_.trailing_zeros) + while (num_digits > 0 && digits_[num_digits - 1] == '0') --num_digits; + if (num_zeros != 0 || num_digits != 0) { + *it++ = decimal_point_; + it = std::fill_n(it, num_zeros, static_cast('0')); + it = copy_str(digits_, digits_ + num_digits, it); + } } + return it; } - return it; -} -namespace grisu_options { -enum { fixed = 1, grisu3 = 2 }; -} + public: + float_writer(const char* digits, int num_digits, int exp, float_specs specs, + Char decimal_point) + : digits_(digits), + num_digits_(num_digits), + exp_(exp), + specs_(specs), + decimal_point_(decimal_point) { + int full_exp = num_digits + exp - 1; + int precision = specs.precision > 0 ? specs.precision : 16; + if (specs_.format == float_format::general && + !(full_exp >= -4 && full_exp < precision)) { + specs_.format = float_format::exp; + } + size_ = prettify(counting_iterator()).count(); + size_ += specs.sign ? 1 : 0; + } -// Formats value using the Grisu algorithm: -// https://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf -template -FMT_API bool grisu_format(Double, buffer&, int, unsigned, int&); -template -inline bool grisu_format(Double, buffer&, int, unsigned, int&) { - return false; -} + size_t size() const { return size_; } + size_t width() const { return size(); } -struct sprintf_specs { - int precision; - char type; - bool alt : 1; - - template - constexpr sprintf_specs(basic_format_specs specs) - : precision(specs.precision), type(specs.type), alt(specs.alt) {} - - constexpr bool has_precision() const { return precision >= 0; } + template void operator()(It&& it) { + if (specs_.sign) *it++ = static_cast(data::signs[specs_.sign]); + it = prettify(it); + } }; -template -char* sprintf_format(Double, internal::buffer&, sprintf_specs); +template +int format_float(T value, int precision, float_specs specs, buffer& buf); + +// Formats a floating-point number with snprintf. +template +int snprintf_float(T value, int precision, float_specs specs, + buffer& buf); + +template T promote_float(T value) { return value; } +inline double promote_float(float value) { return value; } template FMT_CONSTEXPR void handle_int_type_spec(char spec, Handler&& handler) { @@ -1134,36 +1271,56 @@ FMT_CONSTEXPR void handle_int_type_spec(char spec, Handler&& handler) { } } -template -FMT_CONSTEXPR void handle_float_type_spec(char spec, Handler&& handler) { - switch (spec) { +template +FMT_CONSTEXPR float_specs parse_float_type_spec( + const basic_format_specs& specs, ErrorHandler&& eh = {}) { + auto result = float_specs(); + result.trailing_zeros = specs.alt; + switch (specs.type) { case 0: - case 'g': + result.format = float_format::general; + result.trailing_zeros |= specs.precision != 0; + break; case 'G': - handler.on_general(); + result.upper = true; + FMT_FALLTHROUGH; + case 'g': + result.format = float_format::general; break; - case 'e': case 'E': - handler.on_exp(); + result.upper = true; + FMT_FALLTHROUGH; + case 'e': + result.format = float_format::exp; + result.trailing_zeros |= specs.precision != 0; break; - case 'f': case 'F': - handler.on_fixed(); + result.upper = true; + FMT_FALLTHROUGH; + case 'f': + result.format = float_format::fixed; + result.trailing_zeros |= specs.precision != 0; break; +#if FMT_DEPRECATED_PERCENT case '%': - handler.on_percent(); + result.format = float_format::fixed; + result.percent = true; break; - case 'a': +#endif case 'A': - handler.on_hex(); + result.upper = true; + FMT_FALLTHROUGH; + case 'a': + result.format = float_format::hex; break; case 'n': - handler.on_num(); + result.locale = true; break; default: - handler.on_error(); + eh.on_error("invalid type specifier"); break; } + return result; } template @@ -1211,24 +1368,6 @@ template class int_type_checker : private ErrorHandler { } }; -template -class float_type_checker : private ErrorHandler { - public: - FMT_CONSTEXPR explicit float_type_checker(ErrorHandler eh) - : ErrorHandler(eh) {} - - FMT_CONSTEXPR void on_general() {} - FMT_CONSTEXPR void on_exp() {} - FMT_CONSTEXPR void on_fixed() {} - FMT_CONSTEXPR void on_percent() {} - FMT_CONSTEXPR void on_hex() {} - FMT_CONSTEXPR void on_num() {} - - FMT_CONSTEXPR void on_error() { - ErrorHandler::on_error("invalid type specifier"); - } -}; - template class char_specs_checker : public ErrorHandler { private: @@ -1271,6 +1410,20 @@ void arg_map::init(const basic_format_args& args) { } } +template struct nonfinite_writer { + sign_t sign; + const char* str; + static constexpr size_t str_size = 3; + + size_t size() const { return str_size + (sign ? 1 : 0); } + size_t width() const { return size(); } + + template void operator()(It&& it) const { + if (sign) *it++ = static_cast(data::signs[sign]); + it = copy_str(str, str + str_size, it); + } +}; + // This template provides operations for formatting and writing data into a // character range. template class basic_writer { @@ -1281,7 +1434,7 @@ template class basic_writer { private: iterator out_; // Output iterator. - internal::locale_ref locale_; + locale_ref locale_; // Attempts to reserve space for n extra characters in the output range. // Returns a pointer to the reserved range or a reference to out_. @@ -1301,7 +1454,7 @@ template class basic_writer { template void operator()(It&& it) const { if (prefix.size() != 0) - it = internal::copy_str(prefix.begin(), prefix.end(), it); + it = copy_str(prefix.begin(), prefix.end(), it); it = std::fill_n(it, padding, fill); f(it); } @@ -1312,18 +1465,18 @@ template class basic_writer { // where are written by f(it). template void write_int(int num_digits, string_view prefix, format_specs specs, F f) { - std::size_t size = prefix.size() + internal::to_unsigned(num_digits); + std::size_t size = prefix.size() + to_unsigned(num_digits); char_type fill = specs.fill[0]; std::size_t padding = 0; if (specs.align == align::numeric) { - auto unsiged_width = internal::to_unsigned(specs.width); + auto unsiged_width = to_unsigned(specs.width); if (unsiged_width > size) { padding = unsiged_width - size; size = unsiged_width; } } else if (specs.precision > num_digits) { - size = prefix.size() + internal::to_unsigned(specs.precision); - padding = internal::to_unsigned(specs.precision - num_digits); + size = prefix.size() + to_unsigned(specs.precision); + padding = to_unsigned(specs.precision - num_digits); fill = static_cast('0'); } if (specs.align == align::none) specs.align = align::right; @@ -1332,19 +1485,19 @@ template class basic_writer { // Writes a decimal integer. template void write_decimal(Int value) { - auto abs_value = static_cast>(value); - bool is_negative = internal::is_negative(value); - if (is_negative) abs_value = 0 - abs_value; - int num_digits = internal::count_digits(abs_value); - auto&& it = - reserve((is_negative ? 1 : 0) + static_cast(num_digits)); - if (is_negative) *it++ = static_cast('-'); - it = internal::format_decimal(it, abs_value, num_digits); + auto abs_value = static_cast>(value); + bool negative = is_negative(value); + // Don't do -abs_value since it trips unsigned-integer-overflow sanitizer. + if (negative) abs_value = ~abs_value + 1; + int num_digits = count_digits(abs_value); + auto&& it = reserve((negative ? 1 : 0) + static_cast(num_digits)); + if (negative) *it++ = static_cast('-'); + it = format_decimal(it, abs_value, num_digits); } // The handle_int_type_spec handler that writes an integer. template struct int_writer { - using unsigned_type = uint32_or_64_t; + using unsigned_type = uint32_or_64_or_128_t; basic_writer& writer; const Specs& specs; @@ -1359,7 +1512,7 @@ template class basic_writer { specs(s), abs_value(static_cast(value)), prefix_size(0) { - if (internal::is_negative(value)) { + if (is_negative(value)) { prefix[0] = '-'; ++prefix_size; abs_value = 0 - abs_value; @@ -1379,7 +1532,7 @@ template class basic_writer { }; void on_dec() { - int num_digits = internal::count_digits(abs_value); + int num_digits = count_digits(abs_value); writer.write_int(num_digits, get_prefix(), specs, dec_writer{abs_value, num_digits}); } @@ -1389,8 +1542,8 @@ template class basic_writer { int num_digits; template void operator()(It&& it) const { - it = internal::format_uint<4, char_type>(it, self.abs_value, num_digits, - self.specs.type != 'x'); + it = format_uint<4, char_type>(it, self.abs_value, num_digits, + self.specs.type != 'x'); } }; @@ -1399,7 +1552,7 @@ template class basic_writer { prefix[prefix_size++] = '0'; prefix[prefix_size++] = specs.type; } - int num_digits = internal::count_digits<4>(abs_value); + int num_digits = count_digits<4>(abs_value); writer.write_int(num_digits, get_prefix(), specs, hex_writer{*this, num_digits}); } @@ -1409,7 +1562,7 @@ template class basic_writer { int num_digits; template void operator()(It&& it) const { - it = internal::format_uint(it, abs_value, num_digits); + it = format_uint(it, abs_value, num_digits); } }; @@ -1418,14 +1571,14 @@ template class basic_writer { prefix[prefix_size++] = '0'; prefix[prefix_size++] = static_cast(specs.type); } - int num_digits = internal::count_digits<1>(abs_value); + int num_digits = count_digits<1>(abs_value); writer.write_int(num_digits, get_prefix(), specs, bin_writer<1>{abs_value, num_digits}); } void on_oct() { - int num_digits = internal::count_digits<3>(abs_value); - if (specs.alt && specs.precision <= num_digits) { + int num_digits = count_digits<3>(abs_value); + if (specs.alt && specs.precision <= num_digits && abs_value != 0) { // Octal prefix '0' is counted as a digit, so only add it if precision // is not greater than the number of digits. prefix[prefix_size++] = '0'; @@ -1439,30 +1592,50 @@ template class basic_writer { struct num_writer { unsigned_type abs_value; int size; + const std::string& groups; char_type sep; template void operator()(It&& it) const { basic_string_view s(&sep, sep_size); // Index of a decimal digit with the least significant digit having // index 0. - unsigned digit_index = 0; - it = internal::format_decimal( - it, abs_value, size, [s, &digit_index](char_type*& buffer) { - if (++digit_index % 3 != 0) return; + int digit_index = 0; + std::string::const_iterator group = groups.cbegin(); + it = format_decimal( + it, abs_value, size, + [this, s, &group, &digit_index](char_type*& buffer) { + if (*group <= 0 || ++digit_index % *group != 0 || + *group == max_value()) + return; + if (group + 1 != groups.cend()) { + digit_index = 0; + ++group; + } buffer -= s.size(); std::uninitialized_copy(s.data(), s.data() + s.size(), - internal::make_checked(buffer, s.size())); + make_checked(buffer, s.size())); }); } }; void on_num() { - char_type sep = internal::thousands_sep(writer.locale_); + std::string groups = grouping(writer.locale_); + if (groups.empty()) return on_dec(); + auto sep = thousands_sep(writer.locale_); if (!sep) return on_dec(); - int num_digits = internal::count_digits(abs_value); - int size = num_digits + sep_size * ((num_digits - 1) / 3); + int num_digits = count_digits(abs_value); + int size = num_digits; + std::string::const_iterator group = groups.cbegin(); + while (group != groups.cend() && num_digits > *group && *group > 0 && + *group != max_value()) { + size += sep_size; + num_digits -= *group; + ++group; + } + if (group == groups.cend()) + size += sep_size * ((num_digits - 1) / groups.back()); writer.write_int(size, get_prefix(), specs, - num_writer{abs_value, size, sep}); + num_writer{abs_value, size, groups, sep}); } FMT_NORETURN void on_error() { @@ -1470,98 +1643,17 @@ template class basic_writer { } }; - enum { inf_size = 3 }; // This is an enum to workaround a bug in MSVC. - - struct inf_or_nan_writer { - char sign; - bool as_percentage; - const char* str; - - size_t size() const { - return static_cast(inf_size + (sign ? 1 : 0) + - (as_percentage ? 1 : 0)); - } - size_t width() const { return size(); } - - template void operator()(It&& it) const { - if (sign) *it++ = static_cast(sign); - it = internal::copy_str( - str, str + static_cast(inf_size), it); - if (as_percentage) *it++ = static_cast('%'); - } - }; - - struct double_writer { - char sign; - internal::buffer& buffer; - char* decimal_point_pos; - char_type decimal_point; - - size_t size() const { return buffer.size() + (sign ? 1 : 0); } - size_t width() const { return size(); } - - template void operator()(It&& it) { - if (sign) *it++ = static_cast(sign); - auto begin = buffer.begin(); - if (decimal_point_pos) { - it = internal::copy_str(begin, decimal_point_pos, it); - *it++ = decimal_point; - begin = decimal_point_pos + 1; - } - it = internal::copy_str(begin, buffer.end(), it); - } - }; - - class grisu_writer { - private: - internal::buffer& digits_; - size_t size_; - char sign_; - int exp_; - internal::gen_digits_params params_; - char_type decimal_point_; - - public: - grisu_writer(char sign, internal::buffer& digits, int exp, - const internal::gen_digits_params& params, - char_type decimal_point) - : digits_(digits), - sign_(sign), - exp_(exp), - params_(params), - decimal_point_(decimal_point) { - int num_digits = static_cast(digits.size()); - int full_exp = num_digits + exp - 1; - int precision = params.num_digits > 0 ? params.num_digits : 11; - params_.fixed |= full_exp >= -4 && full_exp < precision; - auto it = internal::grisu_prettify( - digits.data(), num_digits, exp, internal::counting_iterator(), - params_, '.'); - size_ = it.count(); - } - - size_t size() const { return size_ + (sign_ ? 1 : 0); } - size_t width() const { return size(); } - - template void operator()(It&& it) { - if (sign_) *it++ = static_cast(sign_); - int num_digits = static_cast(digits_.size()); - it = internal::grisu_prettify(digits_.data(), num_digits, exp_, - it, params_, decimal_point_); - } - }; - template struct str_writer { const Char* s; size_t size_; size_t size() const { return size_; } size_t width() const { - return internal::count_code_points(basic_string_view(s, size_)); + return count_code_points(basic_string_view(s, size_)); } template void operator()(It&& it) const { - it = internal::copy_str(s, s + size_, it); + it = copy_str(s, s + size_, it); } }; @@ -1575,14 +1667,12 @@ template class basic_writer { template void operator()(It&& it) const { *it++ = static_cast('0'); *it++ = static_cast('x'); - it = internal::format_uint<4, char_type>(it, value, num_digits); + it = format_uint<4, char_type>(it, value, num_digits); } }; public: - /** Constructs a ``basic_writer`` object. */ - explicit basic_writer(Range out, - internal::locale_ref loc = internal::locale_ref()) + explicit basic_writer(Range out, locale_ref loc = locale_ref()) : out_(out.begin()), locale_(loc) {} iterator out() const { return out_; } @@ -1621,32 +1711,70 @@ template class basic_writer { void write(unsigned long value) { write_decimal(value); } void write(unsigned long long value) { write_decimal(value); } - // Writes a formatted integer. +#if FMT_USE_INT128 + void write(int128_t value) { write_decimal(value); } + void write(uint128_t value) { write_decimal(value); } +#endif + template void write_int(T value, const Spec& spec) { - internal::handle_int_type_spec(spec.type, - int_writer(*this, value, spec)); + handle_int_type_spec(spec.type, int_writer(*this, value, spec)); } - void write(double value, const format_specs& specs = format_specs()) { - write_double(value, specs); + template ::value)> + void write(T value, format_specs specs = {}) { + float_specs fspecs = parse_float_type_spec(specs); + fspecs.sign = specs.sign; + if (std::signbit(value)) { // value < 0 is false for NaN so use signbit. + fspecs.sign = sign::minus; + value = -value; + } else if (fspecs.sign == sign::minus) { + fspecs.sign = sign::none; + } + + if (!std::isfinite(value)) { + auto str = std::isinf(value) ? (fspecs.upper ? "INF" : "inf") + : (fspecs.upper ? "NAN" : "nan"); + return write_padded(specs, nonfinite_writer{fspecs.sign, str}); + } + + if (specs.align == align::none) { + specs.align = align::right; + } else if (specs.align == align::numeric) { + if (fspecs.sign) { + auto&& it = reserve(1); + *it++ = static_cast(data::signs[fspecs.sign]); + fspecs.sign = sign::none; + if (specs.width != 0) --specs.width; + } + specs.align = align::right; + } + + memory_buffer buffer; + if (fspecs.format == float_format::hex) { + if (fspecs.sign) buffer.push_back(data::signs[fspecs.sign]); + snprintf_float(promote_float(value), specs.precision, fspecs, buffer); + write_padded(specs, str_writer{buffer.data(), buffer.size()}); + return; + } + int precision = specs.precision >= 0 || !specs.type ? specs.precision : 6; + if (fspecs.format == float_format::exp) ++precision; + if (const_check(std::is_same())) fspecs.binary32 = true; + fspecs.use_grisu = use_grisu(); + if (const_check(FMT_DEPRECATED_PERCENT) && fspecs.percent) value *= 100; + int exp = format_float(promote_float(value), precision, fspecs, buffer); + if (const_check(FMT_DEPRECATED_PERCENT) && fspecs.percent) { + buffer.push_back('%'); + --exp; // Adjust decimal place position. + } + fspecs.precision = precision; + char_type point = fspecs.locale ? decimal_point(locale_) + : static_cast('.'); + write_padded(specs, float_writer(buffer.data(), + static_cast(buffer.size()), + exp, fspecs, point)); } - /** - \rst - Formats *value* using the general format for floating-point numbers - (``'g'``) and writes it to the buffer. - \endrst - */ - void write(long double value, const format_specs& specs = format_specs()) { - write_double(value, specs); - } - - // Formats a floating-point number (double or long double). - template ()> - void write_double(T value, const format_specs& specs); - - /** Writes a character to the buffer. */ void write(char value) { auto&& it = reserve(1); *it++ = value; @@ -1658,14 +1786,9 @@ template class basic_writer { *it++ = value; } - /** - \rst - Writes *value* to the buffer. - \endrst - */ void write(string_view value) { auto&& it = reserve(value.size()); - it = internal::copy_str(value.begin(), value.end(), it); + it = copy_str(value.begin(), value.end(), it); } void write(wstring_view value) { static_assert(std::is_same::value, ""); @@ -1673,25 +1796,23 @@ template class basic_writer { it = std::copy(value.begin(), value.end(), it); } - // Writes a formatted string. template void write(const Char* s, std::size_t size, const format_specs& specs) { write_padded(specs, str_writer{s, size}); } template - void write(basic_string_view s, - const format_specs& specs = format_specs()) { + void write(basic_string_view s, const format_specs& specs = {}) { const Char* data = s.data(); std::size_t size = s.size(); - if (specs.precision >= 0 && internal::to_unsigned(specs.precision) < size) - size = internal::to_unsigned(specs.precision); + if (specs.precision >= 0 && to_unsigned(specs.precision) < size) + size = code_point_index(s, to_unsigned(specs.precision)); write(data, size, specs); } template void write_pointer(UIntPtr value, const format_specs* specs) { - int num_digits = internal::count_digits<4>(value); + int num_digits = count_digits<4>(value); auto pw = pointer_writer{value, num_digits}; if (!specs) return pw(reserve(to_unsigned(num_digits) + 2)); format_specs specs_copy = *specs; @@ -1702,6 +1823,10 @@ template class basic_writer { using writer = basic_writer>; +template struct is_integral : std::is_integral {}; +template <> struct is_integral : std::true_type {}; +template <> struct is_integral : std::true_type {}; + template class arg_formatter_base { public: @@ -1731,7 +1856,7 @@ class arg_formatter_base { } void write_pointer(const void* p) { - writer_.write_pointer(internal::bit_cast(p), specs_); + writer_.write_pointer(internal::to_uintptr(p), specs_); } protected: @@ -1764,7 +1889,7 @@ class arg_formatter_base { return out(); } - template ::value)> + template ::value)> iterator operator()(T value) { if (specs_) writer_.write_int(value, *specs_); @@ -1787,7 +1912,7 @@ class arg_formatter_base { template ::value)> iterator operator()(T value) { - writer_.write_double(value, specs_ ? *specs_ : format_specs()); + writer_.write(value, specs_ ? *specs_ : format_specs()); return out(); } @@ -1852,14 +1977,14 @@ template FMT_CONSTEXPR bool is_name_start(Char c) { template FMT_CONSTEXPR int parse_nonnegative_int(const Char*& begin, const Char* end, ErrorHandler&& eh) { - assert(begin != end && '0' <= *begin && *begin <= '9'); + FMT_ASSERT(begin != end && '0' <= *begin && *begin <= '9', ""); if (*begin == '0') { ++begin; return 0; } unsigned value = 0; // Convert to unsigned to prevent a warning. - constexpr unsigned max_int = (std::numeric_limits::max)(); + constexpr unsigned max_int = max_value(); unsigned big = max_int / 10; do { // Check for overflow. @@ -1878,11 +2003,11 @@ template class custom_formatter { private: using char_type = typename Context::char_type; - basic_parse_context& parse_ctx_; + basic_format_parse_context& parse_ctx_; Context& ctx_; public: - explicit custom_formatter(basic_parse_context& parse_ctx, + explicit custom_formatter(basic_format_parse_context& parse_ctx, Context& ctx) : parse_ctx_(parse_ctx), ctx_(ctx) {} @@ -1896,7 +2021,7 @@ template class custom_formatter { template using is_integer = - bool_constant::value && !std::is_same::value && + bool_constant::value && !std::is_same::value && !std::is_same::value && !std::is_same::value>; @@ -1981,20 +2106,20 @@ template class numeric_specs_checker { : error_handler_(eh), arg_type_(arg_type) {} FMT_CONSTEXPR void require_numeric_argument() { - if (!is_arithmetic(arg_type_)) + if (!is_arithmetic_type(arg_type_)) error_handler_.on_error("format specifier requires numeric argument"); } FMT_CONSTEXPR void check_sign() { require_numeric_argument(); - if (is_integral(arg_type_) && arg_type_ != int_type && + if (is_integral_type(arg_type_) && arg_type_ != int_type && arg_type_ != long_long_type && arg_type_ != internal::char_type) { error_handler_.on_error("format specifier requires signed argument"); } } FMT_CONSTEXPR void check_precision() { - if (is_integral(arg_type_) || arg_type_ == internal::pointer_type) + if (is_integral_type(arg_type_) || arg_type_ == internal::pointer_type) error_handler_.on_error("precision not allowed for this argument type"); } @@ -2049,14 +2174,12 @@ template class specs_checker : public Handler { numeric_specs_checker checker_; }; -template