Fix #1521 - add mg_tou64()

This commit is contained in:
Sergey Lyubka 2022-04-12 10:20:43 +01:00
parent db941e2627
commit 66376885e9
6 changed files with 34 additions and 0 deletions

View File

@ -2442,6 +2442,7 @@ mg_snprintf(buf, sizeof(buf), "%%-%3s", "a"); // %- a
```c
int64_t mg_to64(struct mg_str str);
uint64_t mg_tou64(struct mg_str str);
```
Parse 64-bit integer value held by string `s`.

View File

@ -4049,6 +4049,19 @@ size_t mg_asprintf(char **buf, size_t size, const char *fmt, ...) {
return ret;
}
uint64_t mg_tou64(struct mg_str str) {
uint64_t result = 0;
size_t i = 0;
while (i < str.len && (str.ptr[i] == ' ' || str.ptr[i] == '\t')) i++;
while (i < str.len && str.ptr[i] >= '0' && str.ptr[i] <= '9') {
result *= 10;
result += (unsigned) (str.ptr[i] - '0');
MG_INFO(("[%.*s] %llu", (int) str.len, str.ptr, result));
i++;
}
return result;
}
int64_t mg_to64(struct mg_str str) {
int64_t result = 0, neg = 1, max = 922337203685477570 /* INT64_MAX/10-10 */;
size_t i = 0;

View File

@ -632,6 +632,7 @@ size_t mg_asprintf(char **, size_t, const char *fmt, ...) PRINTF_LIKE(3, 4);
size_t mg_vasprintf(char **buf, size_t size, const char *fmt, va_list ap);
int mg_check_ip_acl(struct mg_str acl, uint32_t remote_ip);
int64_t mg_to64(struct mg_str str);
uint64_t mg_tou64(struct mg_str str);
size_t mg_lld(char *buf, int64_t val, bool is_signed, bool is_hex);

View File

@ -254,6 +254,19 @@ size_t mg_asprintf(char **buf, size_t size, const char *fmt, ...) {
return ret;
}
uint64_t mg_tou64(struct mg_str str) {
uint64_t result = 0;
size_t i = 0;
while (i < str.len && (str.ptr[i] == ' ' || str.ptr[i] == '\t')) i++;
while (i < str.len && str.ptr[i] >= '0' && str.ptr[i] <= '9') {
result *= 10;
result += (unsigned) (str.ptr[i] - '0');
MG_INFO(("[%.*s] %llu", (int) str.len, str.ptr, result));
i++;
}
return result;
}
int64_t mg_to64(struct mg_str str) {
int64_t result = 0, neg = 1, max = 922337203685477570 /* INT64_MAX/10-10 */;
size_t i = 0;

View File

@ -41,4 +41,5 @@ size_t mg_asprintf(char **, size_t, const char *fmt, ...) PRINTF_LIKE(3, 4);
size_t mg_vasprintf(char **buf, size_t size, const char *fmt, va_list ap);
int mg_check_ip_acl(struct mg_str acl, uint32_t remote_ip);
int64_t mg_to64(struct mg_str str);
uint64_t mg_tou64(struct mg_str str);
size_t mg_lld(char *buf, int64_t val, bool is_signed, bool is_hex);

View File

@ -1499,6 +1499,11 @@ static void test_util(void) {
ASSERT(mg_to64(mg_str("-9223372036854775809")) == 0);
ASSERT(mg_to64(mg_str("9223372036854775800")) == 0);
ASSERT(mg_to64(mg_str("9223372036854775700")) > 0);
ASSERT(mg_tou64(mg_str("0")) == 0);
ASSERT(mg_tou64(mg_str("123")) == 123);
ASSERT(mg_tou64(mg_str("")) == 0);
ASSERT(mg_tou64(mg_str("-")) == 0);
ASSERT(mg_tou64(mg_str("18446744073709551615")) == 18446744073709551615U);
}
static void test_crc32(void) {