BRICKS
Small, useful blocks of code, to build bigger things.
Loading...
Searching...
No Matches
charconv.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <charconv>
4#include <limits>
5#include <stdexcept>
6#include <string>
7#include <string_view>
8
9#include "result.hpp"
10
11namespace bricks {
12
29template <typename T>
30auto to_string(const T& value,
31 std::size_t buffer_size = (std::numeric_limits<T>::digits10 + 2)) noexcept
32 -> result<std::string, std::errc>
33{
34 std::string str(buffer_size, '\0');
35 auto [ptr, ec] = std::to_chars(str.data(), str.data() + str.size(), value);
36
37 if (ec != std::errc()) {
38 return ec;
39 }
40
41 str.resize(std::distance(str.data(), ptr));
42 return str;
43}
44
60template <typename T>
61auto from_string(const std::string_view& str) noexcept -> result<T, std::errc>
62{
63 T value;
64 auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), value);
65
66 if (ec != std::errc()) {
67 return ec;
68 }
69
70 if (ptr != str.data() + str.size()) {
71 return std::errc::invalid_argument;
72 }
73
74 return value;
75}
76
77} // namespace bricks
A class to represent the result of an operation.
Definition result.hpp:92
Definition algorithm.hpp:12
auto from_string(const std::string_view &str) noexcept -> result< T, std::errc >
Exceptionlessly convert a string to a number.
Definition charconv.hpp:61
auto to_string(const T &value, std::size_t buffer_size=(std::numeric_limits< T >::digits10+2)) noexcept -> result< std::string, std::errc >
Exceptionlessly convert a number to a string.
Definition charconv.hpp:30