]> git.ipfire.org Git - thirdparty/shadow.git/commitdiff
lib/atoi/strtou_noneg.[ch]: Add strtou_noneg()
authorAlejandro Colomar <alx@kernel.org>
Sat, 6 Jan 2024 18:46:20 +0000 (19:46 +0100)
committerSerge Hallyn <serge@hallyn.com>
Thu, 1 Feb 2024 04:26:19 +0000 (22:26 -0600)
It's like strtou_(), but rejects negative input, instead of silently
converting it to unsigned.

Link: <https://softwareengineering.stackexchange.com/a/449060/332848>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
lib/atoi/strtou_noneg.c
lib/atoi/strtou_noneg.h

index 14602a9b1dcd7f7a79dffedfbf5d5d7015c82a94..ec8773d78ff4c4ef42b284e0eb730b0d16ca73b9 100644 (file)
@@ -6,6 +6,11 @@
 
 #include "atoi/strtou_noneg.h"
 
+#include <stdint.h>
+
+
+extern inline uintmax_t strtou_noneg(const char *s, char **restrict endp,
+    int base, uintmax_t min, uintmax_t max, int *restrict status);
 
 extern inline unsigned long strtoul_noneg(const char *s,
     char **restrict endp, int base);
index 5670dc9ba4c21f82d7da71d1f95b9dfe959ce245..a1d1556967c79215f644c01810e18d0fbe7b79e5 100644 (file)
@@ -9,11 +9,17 @@
 #include <config.h>
 
 #include <errno.h>
+#include <stdint.h>
 #include <stdlib.h>
 
+#include "atoi/strtoi.h"
 #include "attr.h"
 
 
+ATTR_STRING(1) ATTR_ACCESS(write_only, 2) ATTR_ACCESS(write_only, 6)
+inline uintmax_t strtou_noneg(const char *s, char **restrict endp,
+    int base, uintmax_t min, uintmax_t max, int *restrict status);
+
 ATTR_STRING(1) ATTR_ACCESS(write_only, 2)
 inline unsigned long strtoul_noneg(const char *s,
     char **restrict endp, int base);
@@ -22,6 +28,21 @@ inline unsigned long long strtoull_noneg(const char *s,
     char **restrict endp, int base);
 
 
+inline uintmax_t
+strtou_noneg(const char *s, char **restrict endp, int base,
+    uintmax_t min, uintmax_t max, int *restrict status)
+{
+       int  st;
+
+       if (status == NULL)
+               status = &st;
+       if (strtoi_(s, endp, base, 0, 1, status) == 0 && *status == ERANGE)
+               return min;
+
+       return strtou_(s, endp, base, min, max, status);
+}
+
+
 inline unsigned long
 strtoul_noneg(const char *s, char **restrict endp, int base)
 {