From fbcc7f4168827bf7c956bd83eaa42e1f449e95bd Mon Sep 17 00:00:00 2001 From: Franck Bui Date: Wed, 26 Apr 2017 18:18:03 +0200 Subject: [PATCH] parse-util: introduce parse_dev() helper --- src/basic/parse-util.c | 15 +++++++++++++++ src/basic/parse-util.h | 1 + src/test/test-parse-util.c | 14 ++++++++++++++ 3 files changed, 30 insertions(+) diff --git a/src/basic/parse-util.c b/src/basic/parse-util.c index d86700736d7..4532f222c8a 100644 --- a/src/basic/parse-util.c +++ b/src/basic/parse-util.c @@ -589,3 +589,18 @@ int parse_ip_port(const char *s, uint16_t *ret) { return 0; } + +int parse_dev(const char *s, dev_t *ret) { + unsigned x, y; + dev_t d; + + if (sscanf(s, "%u:%u", &x, &y) != 2) + return -EINVAL; + + d = makedev(x, y); + if ((unsigned) major(d) != x || (unsigned) minor(d) != y) + return -EINVAL; + + *ret = d; + return 0; +} diff --git a/src/basic/parse-util.h b/src/basic/parse-util.h index 4d132f0de5a..dc09782ca89 100644 --- a/src/basic/parse-util.h +++ b/src/basic/parse-util.h @@ -30,6 +30,7 @@ #define MODE_INVALID ((mode_t) -1) int parse_boolean(const char *v) _pure_; +int parse_dev(const char *s, dev_t *ret); int parse_pid(const char *s, pid_t* ret_pid); int parse_mode(const char *s, mode_t *ret); int parse_ifindex(const char *s, int *ret); diff --git a/src/test/test-parse-util.c b/src/test/test-parse-util.c index d08014100b6..099c8e88f58 100644 --- a/src/test/test-parse-util.c +++ b/src/test/test-parse-util.c @@ -526,6 +526,19 @@ static void test_parse_nice(void) { assert_se(parse_nice("+20", &n) == -ERANGE); } +static void test_parse_dev(void) { + dev_t dev; + + assert_se(parse_dev("0", &dev) == -EINVAL); + assert_se(parse_dev("5", &dev) == -EINVAL); + assert_se(parse_dev("5:", &dev) == -EINVAL); + assert_se(parse_dev(":5", &dev) == -EINVAL); +#if SIZEOF_DEV_T < 8 + assert_se(parse_dev("4294967295:4294967295", &dev) == -EINVAL); +#endif + assert_se(parse_dev("8:11", &dev) >= 0 && major(dev) == 8 && minor(dev) == 11); +} + int main(int argc, char *argv[]) { log_parse_environment(); log_open(); @@ -542,6 +555,7 @@ int main(int argc, char *argv[]) { test_parse_percent(); test_parse_percent_unbounded(); test_parse_nice(); + test_parse_dev(); return 0; }