From 22dc158a03762c22d75fca7500c32799130f21a7 Mon Sep 17 00:00:00 2001 From: Alejandro Colomar Date: Thu, 24 Aug 2023 01:12:27 +0200 Subject: String: added nxt_atoul(). This is similar to atoi(3) in usage, except that: - It's safe (doesn't have Undefined Behavior). - It receives a nxt_str_t instead of a string. - The base is 0, not 10. Errors are reported with the same error codes as in strtou(3bsd), but they are reported via errno, instead of passing a pointer to an int. Signed-off-by: Alejandro Colomar --- src/nxt_string.c | 38 ++++++++++++++++++++++++++++++++++++++ src/nxt_string.h | 3 +++ 2 files changed, 41 insertions(+) diff --git a/src/nxt_string.c b/src/nxt_string.c index ed4ff955..3a3fd5bf 100644 --- a/src/nxt_string.c +++ b/src/nxt_string.c @@ -8,8 +8,13 @@ #include #include +#include #include +#include + +#include "nxt_string.h" + static inline unsigned long nxt_strtoul_noneg(const char *nptr, char **restrict endptr, int base); @@ -852,6 +857,39 @@ nxt_base64_decode(u_char *dst, u_char *src, size_t length) } +unsigned long +nxt_atoul(const nxt_str_t *s) +{ + int e; + char *endptr; + unsigned long ul; + char buf[BUFSIZ]; + + if (s == NULL || s->length >= nxt_nitems(buf)) { + errno = ECANCELED; + return 0; + } + + stpcpy(nxt_cpymem(buf, s->start, s->length), ""); + + e = errno; + errno = 0; + ul = nxt_strtoul_noneg(buf, &endptr, 0); + + if (endptr == buf) { + errno = ECANCELED; + } else if (errno == ERANGE) { + errno = ERANGE; + } else if (*endptr == '\0') { + errno = ENOTSUP; + } else { + errno = e; + } + + return ul; +} + + static inline unsigned long nxt_strtoul_noneg(const char *nptr, char **restrict endptr, int base) { diff --git a/src/nxt_string.h b/src/nxt_string.h index 18ea5490..8afdc1e7 100644 --- a/src/nxt_string.h +++ b/src/nxt_string.h @@ -161,6 +161,9 @@ NXT_EXPORT nxt_bool_t nxt_is_complex_uri_encoded(u_char *s, size_t length); NXT_EXPORT ssize_t nxt_base64_decode(u_char *dst, u_char *src, size_t length); +NXT_EXPORT unsigned long nxt_atoul(const nxt_str_t *s); + + extern const uint8_t nxt_hex2int[256]; -- cgit