tetl 0.1.0
Embedded Template Library
Loading...
Searching...
No Matches
from_integer.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: BSL-1.0
2
3#ifndef TETL_STRINGS_CONVERSION_HPP
4#define TETL_STRINGS_CONVERSION_HPP
5
9#include <etl/_math/abs.hpp>
10#include <etl/_math/idiv.hpp>
12
13namespace etl::strings {
14
18
19enum struct from_integer_error : unsigned char {
22};
23
28
29template <integral Int, from_integer_options Options = from_integer_options{}>
30[[nodiscard]] constexpr auto from_integer(Int num, char* str, size_t length, int base) -> from_integer_result
31{
32 // Handle 0 explicitely, otherwise empty string is printed for 0
33 etl::size_t i = 0;
34 if (num == 0) {
35 if (length < (1 + static_cast<size_t>(Options.terminate_with_null))) {
36 return {.end = str + length, .error = from_integer_error::overflow};
37 }
38 str[i++] = '0';
39 if constexpr (Options.terminate_with_null) {
40 str[i] = '\0';
41 }
42 return {.end = str + i, .error = from_integer_error::none};
43 }
44
45 bool isNegative = false;
46 if constexpr (is_signed_v<Int>) {
47 if (num < 0 and base == 10) {
48 isNegative = true;
49 str[i++] = '-';
50 }
51 }
52
53 while (num != 0) {
54 auto const [quot, rem] = etl::idiv(num, static_cast<Int>(base));
55 auto const digit = static_cast<char>(etl::abs(rem));
56
57 str[i++] = (digit > 9) ? (digit - 10) + 'a' : digit + '0';
58 num = quot;
59
60 if (length <= i) {
61 return {.end = nullptr, .error = from_integer_error::overflow};
62 }
63 }
64
65 etl::reverse(str + static_cast<size_t>(isNegative), str + i);
66 if constexpr (Options.terminate_with_null) {
67 str[i] = '\0';
68 }
69
70 return {.end = str + i, .error = from_integer_error::none};
71}
72
73} // namespace etl::strings
74
75#endif // TETL_STRINGS_CONVERSION_HPP
The concept integral<T> is satisfied if and only if T is an integral type.
Definition integral.hpp:13
constexpr auto reverse(BidirIt first, BidirIt last) -> void
Reverses the order of the elements in the range [first, last).
Definition reverse.hpp:16
constexpr auto abs(complex< T > const &z) -> T
Definition abs.hpp:13
Definition find.hpp:8
from_integer_error
Definition from_integer.hpp:19
@ overflow
Definition from_integer.hpp:21
@ none
Definition from_integer.hpp:20
constexpr auto from_integer(Int num, char *str, size_t length, int base) -> from_integer_result
Definition from_integer.hpp:30
@ overflow
Definition from_floating_point.hpp:20
@ none
Definition from_floating_point.hpp:19
constexpr bool is_signed_v
Definition is_signed.hpp:30
constexpr auto idiv(Int x, Int y) noexcept -> idiv_result< Int >
Definition idiv.hpp:17
TETL_BUILTIN_SIZET size_t
etl::size_t is the unsigned integer type of the result of the sizeof operator.
Definition size_t.hpp:14
Definition from_integer.hpp:15
bool terminate_with_null
Definition from_integer.hpp:16
Definition from_integer.hpp:24
char * end
Definition from_integer.hpp:25
from_integer_error error
Definition from_integer.hpp:26