[ox/std] Fix writeItoa to work with negatives
All checks were successful
Build / build (push) Successful in 1m9s

This commit is contained in:
2026-01-19 23:00:16 -06:00
parent 815c3d19bf
commit a566ed2a8b
3 changed files with 40 additions and 25 deletions

View File

@@ -18,34 +18,34 @@ namespace ox {
template<Integer_c Integer> template<Integer_c Integer>
constexpr ox::Error writeItoa(Integer v, ox::Writer_c auto &writer) noexcept { constexpr ox::Error writeItoa(Integer v, ox::Writer_c auto &writer) noexcept {
if (v) { if (v) {
ox::ResizedInt_t<Integer, 64> mod = 1000000000000000000; ox::ResizedInt_t<Integer, 64> mod = 1000000000000000000;
ox::ResizedInt_t<Integer, 64> val = v; ox::ResizedInt_t<Integer, 64> val = v;
constexpr auto base = 10; constexpr auto base = 10;
auto it = 0; auto it = 0;
if (val < 0) { if (val < 0) {
OX_RETURN_ERROR(writer.put('-')); OX_RETURN_ERROR(writer.put('-'));
val = ~val + 1;
}
while (mod) {
auto digit = val / mod;
val %= mod;
mod /= base;
if (it || digit) {
ox::ResizedInt_t<Integer, 64> start = '0';
if (digit >= 10) {
start = 'a';
digit -= 10;
}
OX_RETURN_ERROR(writer.put(static_cast<char>(start + digit)));
++it; ++it;
} }
while (mod) {
auto digit = val / mod;
val %= mod;
mod /= base;
if (it || digit) {
ox::ResizedInt_t<Integer, 64> start = '0';
if (digit >= 10) {
start = 'a';
digit -= 10;
}
OX_RETURN_ERROR(writer.put(static_cast<char>(start + digit)));
++it;
}
}
} else {
// 0 is a special case
OX_RETURN_ERROR(writer.put('0'));
} }
return {}; } else {
// 0 is a special case
OX_RETURN_ERROR(writer.put('0'));
}
return {};
} }
} }

View File

@@ -28,3 +28,4 @@ add_test("[ox/std] FromHex" ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/StdTest "FromHex")
add_test("[ox/std] ToHex" ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/StdTest "ToHex") add_test("[ox/std] ToHex" ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/StdTest "ToHex")
add_test("[ox/std] UUID" ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/StdTest "UUID") add_test("[ox/std] UUID" ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/StdTest "UUID")
add_test("[ox/std] UUID::generate" ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/StdTest "UUID::generate") add_test("[ox/std] UUID::generate" ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/StdTest "UUID::generate")
add_test("[ox/std] intToStr" ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/StdTest "intToStr")

View File

@@ -536,6 +536,20 @@ OX_CLANG_NOWARN_END
return ox::Error(0); return ox::Error(0);
} }
}, },
{
"intToStr",
[] {
oxExpect(ox::intToStr(5), "5");
oxExpect(ox::intToStr(5000), "5000");
oxExpect(ox::intToStr(50000), "50000");
oxExpect(ox::intToStr(500000), "500000");
oxExpect(ox::intToStr(-5), "-5");
oxExpect(ox::intToStr(-5000), "-5000");
oxExpect(ox::intToStr(-50000), "-50000");
oxExpect(ox::intToStr(-500000), "-500000");
return ox::Error{};
}
},
}; };
int main(int argc, const char **argv) { int main(int argc, const char **argv) {