Skip to content

Commit

Permalink
Use correct length calculation for int formatting to ensure format_le…
Browse files Browse the repository at this point in the history
…ngth works

Add tests

Fixes #49
  • Loading branch information
seanmiddleditch committed Jan 15, 2024
1 parent 8046821 commit 75135c3
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
6 changes: 3 additions & 3 deletions source/format.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::size_t>(spec.precision) < available) ? spec.precision : available;
size_t const length = (spec.precision >= 0 && static_cast<std::size_t>(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);
Expand Down
10 changes: 10 additions & 0 deletions tests/test_format.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
//
Expand Down

0 comments on commit 75135c3

Please sign in to comment.