From 649e9ccc8e79565c00ce82c6bce5b5409ed09cac Mon Sep 17 00:00:00 2001 From: Alexander Mikhalitsyn Date: Wed, 30 Nov 2022 17:25:24 +0100 Subject: [PATCH] utils: add safe_uint32() helper Signed-off-by: Alexander Mikhalitsyn --- src/utils.c | 23 +++++++++++++++++++++++ src/utils.h | 1 + 2 files changed, 24 insertions(+) diff --git a/src/utils.c b/src/utils.c index 926760d..6bfedeb 100644 --- a/src/utils.c +++ b/src/utils.c @@ -529,6 +529,29 @@ int safe_uint64(const char *numstr, uint64_t *converted, int base) return 0; } +int safe_uint32(const char *numstr, uint32_t *converted, int base) +{ + char *err = NULL; + unsigned long uli; + + while (isspace(*numstr)) + numstr++; + + if (*numstr == '-') + return -EINVAL; + + errno = 0; + uli = strtoul(numstr, &err, base); + if (errno == ERANGE && uli == UINT32_MAX) + return -ERANGE; + + if (err == numstr || *err != '\0') + return -EINVAL; + + *converted = (uint32_t)uli; + return 0; +} + static int char_left_gc(const char *buffer, size_t len) { size_t i; diff --git a/src/utils.h b/src/utils.h index eb01aca..dc0ec3a 100644 --- a/src/utils.h +++ b/src/utils.h @@ -62,6 +62,7 @@ extern FILE *fdopen_cached(int fd, const char *mode, void **caller_freed_buffer) extern DIR *opendir_flags(const char *path, int oflags); extern ssize_t write_nointr(int fd, const void *buf, size_t count); extern int safe_uint64(const char *numstr, uint64_t *converted, int base); +extern int safe_uint32(const char *numstr, uint32_t *converted, int base); extern char *trim_whitespace_in_place(char *buffer); static inline bool file_exists(const char *f) -- 2.39.5