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 "debugger.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 hilet first = buffer.data();
32 hilet last = first + buffer.size();
33
34 hilet[new_last, ec] = std::to_chars(first, last, value);
35 hi_assert(ec == std::errc{});
36
37 auto r = std::string{};
39 return r;
40}
41
48template<std::floating_point T>
49[[nodiscard]] std::string to_string(T const &value) noexcept
50{
52
53 hilet first = buffer.data();
54 hilet last = first + buffer.size();
55
56 hilet[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{};
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 hilet first = str.data();
78 hilet last = first + ssize(str);
79
80 hilet[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 hilet first = str.data();
101 hilet last = first + ssize(str);
102
103 hilet[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
DOXYGEN BUG.
Definition algorithm.hpp:16
geometry/margins.hpp
Definition lookahead_iterator.hpp:5
T from_string(std::string_view str, int base=10)
Convert a string to an integer.
Definition charconv.hpp:73
constexpr Out narrow_cast(In const &rhs) noexcept
Cast numeric values without loss of precision.
Definition cast.hpp:377
Exception thrown during parsing on an error.
Definition exception_intf.hpp:47
T back_inserter(T... args)
T copy(T... args)