From 6fc645c9d281bcfd018423f113a90541709b336f Mon Sep 17 00:00:00 2001 From: Kevin Trogant Date: Wed, 3 Dec 2025 17:29:26 +0100 Subject: [PATCH] parse s8 to int --- rtcore.h | 86 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ test.c | 16 +++++++++++ 2 files changed, 102 insertions(+) diff --git a/rtcore.h b/rtcore.h index 573726b..36705ad 100644 --- a/rtcore.h +++ b/rtcore.h @@ -215,6 +215,14 @@ RTC_API split_result S8Split(s8 s, u8 c); /* Creates a clone of string s on arena a */ RTC_API s8 S8Clone(s8 s, arena *a); +typedef struct { i64 i; b32 ok; } s8_parse_i64_result; +typedef struct { i32 i; b32 ok; } s8_parse_i32_result; + +/* Parses a integer from string s */ +RTC_API s8_parse_i64_result S8ParseI64(s8 s, int base); +/* Parses an integer from string s */ +RTC_API s8_parse_i32_result S8ParseI32(s8 s, int base); + /* Basic file io */ typedef struct file_buffer { @@ -392,6 +400,84 @@ S8Clone(s8 s, arena *a) memcpy(c.data, s.data, s.length); return s; } +RTC_API s8_parse_i64_result +S8ParseI64(s8 s, int base) +{ + isize at = s.length - 1; + i64 exp = 1; + i64 val = 0; + while (at >= 0) + { + u8 c = s.data[at]; + int digit = 0; + if (c >= '0' && c <= '9') + digit = c - '0'; + else if (c >= 'A' && c <= 'Z') + digit = c - 'A'; + else if (c >= 'a' && c <= 'z') + digit = c - 'a'; + else if (c == '-') + { + val *= -1; + break; + } + else if (c == '+') + { + break; + } + else + return (s8_parse_i64_result){0}; + if (digit >= base) + return (s8_parse_i64_result){0}; + + val += digit * exp; + exp *= base; + --at; + } + return (s8_parse_i64_result){ + .i = val, + .ok = 1, + }; +} +RTC_API s8_parse_i32_result +S8ParseI32(s8 s, int base) +{ + isize at = s.length - 1; + i32 exp = 1; + i32 val = 0; + while (at >= 0) + { + u8 c = s.data[at]; + int digit = 0; + if (c >= '0' && c <= '9') + digit = c - '0'; + else if (c >= 'A' && c <= 'Z') + digit = c - 'A'; + else if (c >= 'a' && c <= 'z') + digit = c - 'a'; + else if (c == '-') + { + val *= -1; + break; + } + else if (c == '+') + { + break; + } + else + return (s8_parse_i32_result){0}; + if (digit >= base) + return (s8_parse_i32_result){0}; + + val += digit * exp; + exp *= base; + --at; + } + return (s8_parse_i32_result){ + .i = val, + .ok = 1, + }; +} /* Basic file io */ RTC_API file_buffer diff --git a/test.c b/test.c index 2e688a3..4d3ed96 100644 --- a/test.c +++ b/test.c @@ -47,6 +47,20 @@ ThreadTest(void) return AtomicLoad(&p) == 42; } +internal int +ParseIntTest(void) +{ + if (S8ParseI32(S8("123"), 10).i != 123) + return 0; + if (S8ParseI32(S8("-124"), 10).i != -124) + return 0; + if (S8ParseI64(S8("9223372036854775807"), 10).i != 9223372036854775807) + return 0; + if (S8ParseI32(S8("Not a number"), 10).ok) + return 0; + return 1; +} + int main() { @@ -56,5 +70,7 @@ main() return 2; if (!ThreadTest()) return 3; + if (!ParseIntTest()) + return 4; return 0; }