// https://www.boost.org/doc/libs/1_92_0/libs/charconv/doc/html/charconv.html

#include <boost/charconv.hpp>

#include <cassert>
#include <cstring>
#include <iostream>
#include <system_error>

int main()
{
    // Floating point round trip, shortest representation
    const double value = 3.14159265358979;
    char buffer[64] = {};

    auto to = boost::charconv::to_chars(buffer, buffer + sizeof(buffer), value);
    assert(to.ec == std::errc());
    *to.ptr = '\0';

    std::cout << "to_chars(" << value << ") = " << buffer << std::endl;

    double parsed = 0;
    auto from = boost::charconv::from_chars(buffer, to.ptr, parsed);
    assert(from.ec == std::errc());
    assert(parsed == value);

    // Explicit format and precision
    char fixed[64] = {};
    auto to_fixed = boost::charconv::to_chars(fixed, fixed + sizeof(fixed), value,
                                              boost::charconv::chars_format::fixed, 4);
    assert(to_fixed.ec == std::errc());
    *to_fixed.ptr = '\0';

    std::cout << "to_chars(" << value << ", fixed, 4) = " << fixed << std::endl;
    assert(std::strcmp(fixed, "3.1416") == 0);

    // Parsing garbage must be reported, not accepted
    const char *bad = "not-a-number";
    double dummy = 0;
    auto bad_res = boost::charconv::from_chars(bad, bad + std::strlen(bad), dummy);
    assert(bad_res.ec == std::errc::invalid_argument);

    return 0;
}
