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// SPDX-FileCopyrightText: Copyright (C) 2024 Tobias Hienzsch
3
4#ifndef TETL_STRINGS_TO_FLOATING_POINT_HPP
5#define TETL_STRINGS_TO_FLOATING_POINT_HPP
6
7#include <etl/_cctype/isdigit.hpp>
8#include <etl/_cctype/isspace.hpp>
9#include <etl/_string_view/basic_string_view.hpp>
10#include <etl/_type_traits/is_signed.hpp>
11
12namespace etl::strings {
13
14enum struct to_floating_point_error : unsigned char {
15 none,
18};
19
20template <typename Float>
22 char const* end{nullptr};
24 Float value;
25};
26
27template <typename Float>
28[[nodiscard]] constexpr auto to_floating_point(etl::string_view str) noexcept -> to_floating_point_result<Float>
29{
30 auto res = Float{0};
31 auto div = Float{1};
32 auto afterDecimalPoint = false;
33 auto leadingSpaces = true;
34
35 auto const* ptr = str.data();
36 for (; *ptr != '\0'; ++ptr) {
37 if (etl::isspace(*ptr) && leadingSpaces) {
38 continue;
39 }
40 leadingSpaces = false;
41
42 if (etl::isdigit(*ptr)) {
43 if (!afterDecimalPoint) {
44 res *= 10; // Shift the previous digits to the left
45 res += *ptr - '0'; // Add the new one
46 } else {
47 div *= 10;
48 res += static_cast<Float>(*ptr - '0') / div;
49 }
50 } else if (*ptr == '.') {
51 afterDecimalPoint = true;
52 } else {
53 return {.end = str.data(), .error = to_floating_point_error::invalid_input, .value = {}};
54 }
55 }
56
57 return {.end = ptr, .error = {}, .value = res};
58}
59
60} // namespace etl::strings
61
62#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:16
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:20
Definition find.hpp:9
constexpr auto to_floating_point(etl::string_view str) noexcept -> to_floating_point_result< Float >
Definition to_floating_point.hpp:28
to_floating_point_error
Definition to_floating_point.hpp:14
Definition adjacent_find.hpp:9
constexpr auto data() const noexcept -> const_pointer
Returns a pointer to the underlying character array. The pointer is such that the range [data(); data...
Definition basic_string_view.hpp:190
Definition to_floating_point.hpp:21
to_floating_point_error error
Definition to_floating_point.hpp:23
char const * end
Definition to_floating_point.hpp:22
Float value
Definition to_floating_point.hpp:24