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// SPDX-FileCopyrightText: Copyright (C) 2021 Tobias Hienzsch
3
4#ifndef TETL_STRINGS_CONVERSION_HPP
5#define TETL_STRINGS_CONVERSION_HPP
6
7#include <etl/_algorithm/reverse.hpp>
8#include <etl/_concepts/integral.hpp>
9#include <etl/_cstddef/size_t.hpp>
10#include <etl/_math/abs.hpp>
11#include <etl/_math/idiv.hpp>
12#include <etl/_type_traits/is_signed.hpp>
13
14namespace etl::strings {
15
18};
19
20enum struct from_integer_error : unsigned char {
21 none,
23};
24
26 char* end{nullptr};
28};
29
30template <integral Int, from_integer_options Options = from_integer_options{}>
31[[nodiscard]] constexpr auto from_integer(Int num, char* str, size_t length, int base) -> from_integer_result
32{
33 // Handle 0 explicitely, otherwise empty string is printed for 0
34 etl::size_t i = 0;
35 if (num == 0) {
36 if (length < (1 + static_cast<size_t>(Options.terminate_with_null))) {
37 return {.end = str + length, .error = from_integer_error::overflow};
38 }
39 str[i++] = '0';
40 if constexpr (Options.terminate_with_null) {
41 str[i] = '\0';
42 }
43 return {.end = str + i, .error = from_integer_error::none};
44 }
45
46 bool isNegative = false;
47 if constexpr (is_signed_v<Int>) {
48 if (num < 0) {
49 isNegative = true;
50 str[i++] = '-';
51 }
52 }
53
54 while (num != 0) {
55 auto const [quot, rem] = etl::idiv(num, static_cast<Int>(base));
56 auto const digit = static_cast<char>(etl::abs(rem));
57
58 str[i++] = (digit > 9) ? (digit - 10) + 'a' : digit + '0';
59 num = quot;
60
61 if (i == length) {
62 if constexpr (Options.terminate_with_null) {
63 return {.end = nullptr, .error = from_integer_error::overflow};
64 } else {
65 if (num != 0) {
66 return {.end = nullptr, .error = from_integer_error::overflow};
67 }
68 break;
69 }
70 }
71 }
72
73 etl::reverse(str + static_cast<size_t>(isNegative), str + i);
74 if constexpr (Options.terminate_with_null) {
75 str[i] = '\0';
76 }
77
78 return {.end = str + i, .error = from_integer_error::none};
79}
80
81} // namespace etl::strings
82
83#endif // TETL_STRINGS_CONVERSION_HPP
constexpr auto reverse(BidirIt first, BidirIt last) -> void
Reverses the order of the elements in the range [first, last).
Definition reverse.hpp:17
Definition find.hpp:9
from_integer_error
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:31
Definition adjacent_find.hpp:9
Definition from_integer.hpp:16
bool terminate_with_null
Definition from_integer.hpp:17
Definition from_integer.hpp:25
char * end
Definition from_integer.hpp:26
from_integer_error error
Definition from_integer.hpp:27