tetl 0.1.0
Embedded Template Library
Loading...
Searching...
No Matches
to_floating_point.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: BSL-1.0
2
3#ifndef TETL_STRINGS_TO_FLOATING_POINT_HPP
4#define TETL_STRINGS_TO_FLOATING_POINT_HPP
5
10
11namespace etl::strings {
12
13enum struct to_floating_point_error : unsigned char {
17};
18
19template <typename Float>
25
26template <typename Float>
27[[nodiscard]] constexpr auto to_floating_point(etl::string_view str) noexcept -> to_floating_point_result<Float>
28{
29 auto res = Float{0};
30 auto div = Float{1};
31 auto afterDecimalPoint = false;
32 auto leadingSpaces = true;
33
34 auto const* ptr = str.data();
35 for (; *ptr != '\0'; ++ptr) {
36 if (etl::isspace(*ptr) && leadingSpaces) {
37 continue;
38 }
39 leadingSpaces = false;
40
41 if (etl::isdigit(*ptr)) {
42 if (!afterDecimalPoint) {
43 res *= 10; // Shift the previous digits to the left
44 res += *ptr - '0'; // Add the new one
45 } else {
46 div *= 10;
47 res += static_cast<Float>(*ptr - '0') / div;
48 }
49 } else if (*ptr == '.') {
50 afterDecimalPoint = true;
51 } else {
52 return {.end = str.data(), .error = to_floating_point_error::invalid_input, .value = {}};
53 }
54 }
55
56 return {.end = ptr, .error = {}, .value = res};
57}
58
59} // namespace etl::strings
60
61#endif // TETL_STRINGS_TO_FLOATING_POINT_HPP
constexpr auto isdigit(int ch) noexcept -> int
Checks if the given character is one of the 10 decimal digits: 0123456789.
Definition isdigit.hpp:15
constexpr auto isspace(int ch) noexcept -> int
Checks if the given character is whitespace character as classified by the default C locale.
Definition isspace.hpp:19
basic_string_view< char, etl::char_traits< char > > string_view
Typedef for common character type char
Definition basic_string_view.hpp:704
Definition find.hpp:8
constexpr auto to_floating_point(etl::string_view str) noexcept -> to_floating_point_result< Float >
Definition to_floating_point.hpp:27
@ overflow
Definition from_floating_point.hpp:20
@ none
Definition from_floating_point.hpp:19
to_floating_point_error
Definition to_floating_point.hpp:13
@ invalid_input
Definition to_floating_point.hpp:15
@ none
Definition to_floating_point.hpp:14
constexpr auto div(int x, int y) noexcept -> div_t
Computes both the quotient and the remainder of the division of the numerator x by the denominator y....
Definition div.hpp:37
Definition to_floating_point.hpp:20
to_floating_point_error error
Definition to_floating_point.hpp:22
char const * end
Definition to_floating_point.hpp:21
Float value
Definition to_floating_point.hpp:23