From 75135c3aa804b9d66e4071530cf3c5f7d7eca7cc Mon Sep 17 00:00:00 2001 From: Sean Middleditch Date: Sun, 14 Jan 2024 17:11:14 -0800 Subject: [PATCH] Use correct length calculation for int formatting to ensure format_length works Add tests Fixes #49 --- source/format.cpp | 6 +++--- tests/test_format.cpp | 10 ++++++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/source/format.cpp b/source/format.cpp index 8ac5774..4c392be 100644 --- a/source/format.cpp +++ b/source/format.cpp @@ -535,9 +535,9 @@ namespace NANOFMT_NS { 0, }; - size_t const available = out.end - out.pos; - size_t const length = - (spec.precision >= 0 && static_cast(spec.precision) < available) ? spec.precision : available; + size_t const length = (spec.precision >= 0 && static_cast(spec.precision) < sizeof(chars)) + ? spec.precision + : sizeof(chars); const char* const end = to_chars(chars, chars + length, value, select_int_format(spec.type)); format_int_chars(out, chars, end - chars, value < 0, spec); diff --git a/tests/test_format.cpp b/tests/test_format.cpp index b1f936b..86f2930 100644 --- a/tests/test_format.cpp +++ b/tests/test_format.cpp @@ -237,6 +237,16 @@ TEST_CASE("nanofmt.format.custom", "[nanofmt][format][custom]") { CHECK(sformat("{}", fwd_only_type{}) == "fwd_only_type"); } +TEST_CASE("nanofmt.format.length", "[nanofmt][format][length]") { + using namespace NANOFMT_NS; + + CHECK(format_length("{}") == 0); + CHECK(format_length("{}", 777) == 3); + + // https://github.com/seanmiddleditch/nanofmt/issues/49 + CHECK(format_length("{0} = 0x{0:X} = 0b{0:b}", 28) == 19); +} + // TEST_CASE("nanofmt.format.compile_error", "[nanofmt][format][error]") { // using namespace NANOFMT_NS::test; //