From 22f1625002ccffb4e0279f4c28cd2dbd9d9f9200 Mon Sep 17 00:00:00 2001 From: Alex Kotov Date: Tue, 18 Jan 2022 12:39:28 +0500 Subject: [PATCH] Add func kernaux_utoa10 --- include/kernaux/itoa.h | 8 +++++++ src/itoa.c | 21 ++++++++++++++++++ tests/test_itoa.c | 50 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 79 insertions(+) diff --git a/include/kernaux/itoa.h b/include/kernaux/itoa.h index 94aa19b..b9eddd2 100644 --- a/include/kernaux/itoa.h +++ b/include/kernaux/itoa.h @@ -5,8 +5,16 @@ extern "C" { #endif +#include + +// uint64_t: "18446744073709551615" +#define KERNAUX_ITOA_BUFFER_SIZE 21 + +// TODO: remove this void kernaux_itoa(int d, char *buf, int base); +void kernaux_utoa10(uint64_t value, char *buffer); + #ifdef __cplusplus } #endif diff --git a/src/itoa.c b/src/itoa.c index ece68c6..34cd603 100644 --- a/src/itoa.c +++ b/src/itoa.c @@ -3,6 +3,7 @@ #endif #include +#include void kernaux_itoa(const int d, char *buf, const int base) { @@ -43,3 +44,23 @@ void kernaux_itoa(const int d, char *buf, const int base) p2--; } } + +void kernaux_utoa10(uint64_t value, char *buffer) +{ + char *pos = buffer; + + if (value == 0) *(pos++) = '0'; + + while (value > 0) { + *(pos++) = value % 10 + '0'; + value = value / 10; + } + + *(pos--) = '\0'; + + while (buffer < pos) { + const char tmp = *buffer; + *(buffer++) = *pos; + *(pos--) = tmp; + } +} diff --git a/tests/test_itoa.c b/tests/test_itoa.c index bd74a56..09ec675 100644 --- a/tests/test_itoa.c +++ b/tests/test_itoa.c @@ -7,6 +7,45 @@ #include #include +static const struct { + uint64_t value; + const char *result; +} utoa10_cases[] = { + { 0, "0" }, + { 1, "1" }, + { 2, "2" }, + { 9, "9" }, + { 10, "10" }, + { 11, "11" }, + { 12, "12" }, + { 19, "19" }, + { 20, "20" }, + { 21, "21" }, + { 99, "99" }, + { 100, "100" }, + { 101, "101" }, + { 199, "199" }, + { 200, "200" }, + { 201, "201" }, + { 999, "999" }, + { 1000, "1000" }, + { 1001, "1001" }, + { 1999, "1999" }, + { 2000, "2000" }, + { 2001, "2001" }, + { 9999, "9999" }, + { 10000, "10000" }, + { 10001, "10001" }, + { UINT16_MAX, "65535" }, + { UINT16_MAX + 1, "65536" }, + { UINT32_MAX, "4294967295" }, + { (uint64_t)UINT32_MAX + 1, "4294967296" }, + { UINT64_MAX - 6, "18446744073709551609" }, + { UINT64_MAX - 5, "18446744073709551610" }, + { UINT64_MAX - 1, "18446744073709551614" }, + { UINT64_MAX, "18446744073709551615" }, +}; + int main() { { @@ -33,5 +72,16 @@ int main() assert(buffer[5] == '\0'); } + char buffer[KERNAUX_ITOA_BUFFER_SIZE]; + + for ( + size_t index = 0; + index < sizeof(utoa10_cases) / sizeof(utoa10_cases[0]); + ++index + ) { + kernaux_utoa10(utoa10_cases[index].value, buffer); + assert(strcmp(buffer, utoa10_cases[index].result) == 0); + } + return 0; }