HikoGUI
A low latency retained GUI
Loading...
Searching...
No Matches
charconv.hpp
1// Copyright Take Vos 2020-2022.
2// Distributed under the Boost Software License, Version 1.0.
3// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
4
5#pragma once
6
7#include "../macros.hpp"
8#include "terminate.hpp"
9#include "exception.hpp"
10#include <concepts>
11#include <charconv>
12#include <string>
13#include <string_view>
14#include <iterator>
15
16hi_export_module(hikogui.utility.charconv);
17
18hi_export namespace hi { inline namespace v1 {
19
26template<std::integral T>
27[[nodiscard]] std::string to_string(T const &value) noexcept
28{
30
31 auto const first = buffer.data();
32 auto const last = first + buffer.size();
33
34 auto const[new_last, ec] = std::to_chars(first, last, value);
35 hi_assert(ec == std::errc{});
36
37 auto r = std::string{};
38 std::copy(first, new_last, std::back_inserter(r));
39 return r;
40}
41
48template<std::floating_point T>
49[[nodiscard]] std::string to_string(T const &value) noexcept
50{
52
53 auto const first = buffer.data();
54 auto const last = first + buffer.size();
55
56 auto const[new_last, ec] = std::to_chars(first, last, value, std::chars_format::general);
57 hi_assert(ec == std::errc{});
58
59 auto r = std::string{};
60 std::copy(first, new_last, std::back_inserter(r));
61 return r;
62}
63
72template<std::integral T>
73[[nodiscard]] T from_string(std::string_view str, int base = 10)
74{
75 auto value = T{};
76
77 auto const first = str.data();
78 auto const last = first + ssize(str);
79
80 auto const[new_last, ec] = std::from_chars(first, last, value, base);
81 if (ec != std::errc{} or new_last != last) {
82 throw parse_error("Can not convert string to integer");
83 }
84
85 return value;
86}
87
95template<std::floating_point T>
96[[nodiscard]] T from_string(std::string_view str)
97{
98 T value;
99
100 auto const first = str.data();
101 auto const last = first + ssize(str);
102
103 auto const[new_last, ec] = std::from_chars(first, last, value);
104 if (ec != std::errc{} or new_last != last) {
105 throw parse_error("Can not convert string to floating point");
106 }
107
108 return value;
109}
110
111}} // namespace hi::inline v1
Utilities for throwing exceptions and terminating the application.
The HikoGUI namespace.
Definition array_generic.hpp:20
T from_string(std::string_view str, int base=10)
Convert a string to an integer.
Definition charconv.hpp:73
DOXYGEN BUG.
Definition algorithm_misc.hpp:20
Exception thrown during parsing on an error.
Definition exception_intf.hpp:48
T back_inserter(T... args)
T copy(T... args)
T data(T... args)
T size(T... args)