summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorZbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>2023-09-16 10:08:12 +0200
committerZbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>2023-09-19 09:35:52 +0200
commit3b6cabd806c6eb5eec4ac21c903a5033bea94e9d (patch)
treea0e1c673d70a4288bafd5142e150d01b947bc502 /src
parentsd-network: modernize log error messages (diff)
downloadsystemd-3b6cabd806c6eb5eec4ac21c903a5033bea94e9d.tar.xz
systemd-3b6cabd806c6eb5eec4ac21c903a5033bea94e9d.zip
basic/parse-util: add helper to parse bounded unsigned values
"parse_range" is already used for stuff like "a-b", so use "bounded" here to avoid confusion.
Diffstat (limited to 'src')
-rw-r--r--src/basic/parse-util.c15
-rw-r--r--src/basic/parse-util.h3
-rw-r--r--src/test/test-parse-util.c26
3 files changed, 43 insertions, 1 deletions
diff --git a/src/basic/parse-util.c b/src/basic/parse-util.c
index b8fbe3f1c7..d39082ed15 100644
--- a/src/basic/parse-util.c
+++ b/src/basic/parse-util.c
@@ -425,6 +425,21 @@ int safe_atou_full(const char *s, unsigned base, unsigned *ret_u) {
return 0;
}
+int safe_atou_bounded(const char *s, unsigned min, unsigned max, unsigned *ret) {
+ unsigned v;
+ int r;
+
+ r = safe_atou(s, &v);
+ if (r < 0)
+ return r;
+
+ if (v < min || v > max)
+ return -ERANGE;
+
+ *ret = v;
+ return 0;
+}
+
int safe_atoi(const char *s, int *ret_i) {
unsigned base = 0;
char *x = NULL;
diff --git a/src/basic/parse-util.h b/src/basic/parse-util.h
index ca0252005a..e586077efb 100644
--- a/src/basic/parse-util.h
+++ b/src/basic/parse-util.h
@@ -30,11 +30,12 @@ int parse_fd(const char *t);
#define SAFE_ATO_MASK_FLAGS(base) ((base) & ~SAFE_ATO_ALL_FLAGS)
int safe_atou_full(const char *s, unsigned base, unsigned *ret_u);
-
static inline int safe_atou(const char *s, unsigned *ret_u) {
return safe_atou_full(s, 0, ret_u);
}
+int safe_atou_bounded(const char *s, unsigned min, unsigned max, unsigned *ret);
+
int safe_atoi(const char *s, int *ret_i);
int safe_atolli(const char *s, long long int *ret_i);
diff --git a/src/test/test-parse-util.c b/src/test/test-parse-util.c
index 1ba8c8987f..7a485f390f 100644
--- a/src/test/test-parse-util.c
+++ b/src/test/test-parse-util.c
@@ -417,6 +417,32 @@ TEST(parse_range) {
assert_se(upper == 9999);
}
+TEST(safe_atou_bounded) {
+ int r;
+ unsigned x;
+
+ r = safe_atou_bounded("12345", 12, 20000, &x);
+ assert_se(r == 0);
+ assert_se(x == 12345);
+
+ r = safe_atou_bounded("12", 12, 20000, &x);
+ assert_se(r == 0);
+ assert_se(x == 12);
+
+ r = safe_atou_bounded("20000", 12, 20000, &x);
+ assert_se(r == 0);
+ assert_se(x == 20000);
+
+ r = safe_atou_bounded("-1", 12, 20000, &x);
+ assert_se(r == -ERANGE);
+
+ r = safe_atou_bounded("11", 12, 20000, &x);
+ assert_se(r == -ERANGE);
+
+ r = safe_atou_bounded("20001", 12, 20000, &x);
+ assert_se(r == -ERANGE);
+}
+
TEST(safe_atolli) {
int r;
long long l;