File: github_issue_280.cpp

package info (click to toggle)
boost1.90 1.90.0-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 593,120 kB
  • sloc: cpp: 4,190,908; xml: 196,648; python: 34,618; ansic: 23,145; asm: 5,468; sh: 3,774; makefile: 1,161; perl: 1,020; sql: 728; ruby: 676; yacc: 478; java: 77; lisp: 24; csh: 6
file content (61 lines) | stat: -rw-r--r-- 2,038 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Copyright 2025 Matt Borland
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
//
// See: https://github.com/boostorg/charconv/issues/280

#include <boost/charconv.hpp>
#include <boost/core/lightweight_test.hpp>
#include <string>

template <std::size_t precision>
void test(const char* result_string)
{
    constexpr double d = DBL_MIN;
    // for scientific, precision + 7 should suffice:
    // <digit> <.> <#precision digits> <e> <sign> <up to 3 digits>
    //  1       2                       3   4      7
    constexpr size_t buf_size = precision + 7;
    char buf[buf_size];

    auto result = boost::charconv::to_chars(buf, buf + buf_size, d, boost::charconv::chars_format::scientific, precision);
    BOOST_TEST(result);

    // We have to use memcmp here since there is no space to null terminate
    BOOST_TEST(std::memcmp(buf, result_string, precision) == 0);
}

template <std::size_t precision>
void test_negative(const char* result_string)
{
    constexpr double d = -DBL_MIN;
    // for scientific, precision + 7 should suffice:
    // <digit> <.> <#precision digits> <e> <sign> <up to 3 digits>
    //  1       2                       3   4      7
    constexpr size_t buf_size = 1 + precision + 7;
    char buf[buf_size];

    auto result = boost::charconv::to_chars(buf, buf + buf_size, d, boost::charconv::chars_format::scientific, precision);
    BOOST_TEST(result);

    // We have to use memcmp here since there is no space to null terminate
    BOOST_TEST(std::memcmp(buf, result_string, precision) == 0);
}

int main()
{
    // DBL_MIN = 2.2250738585072013830902327173324040642192159804623318306e-308
    test<1>("2.2e-308");
    test<2>("2.23e-308");
    test<3>("2.225e-308");
    test<4>("2.2251e-308");
    test<5>("2.22507e-308");

    test_negative<1>("-2.2e-308");
    test_negative<2>("-2.23e-308");
    test_negative<3>("-2.225e-308");
    test_negative<4>("-2.2251e-308");
    test_negative<5>("-2.22507e-308");

    return boost::report_errors();
}