From ffe15c2d82d9527a53dc32ab34739b8f339bda35 Mon Sep 17 00:00:00 2001 From: Zach Brown Date: Fri, 24 May 2019 10:37:37 -0700 Subject: [PATCH] scoutfs-utils: add string parsing functions We're starting to collect a few of these. Let's put them in one place. Signed-off-by: Zach Brown --- utils/src/parse.c | 71 +++++++++++++++++++++++++++++++++++++++++++++++ utils/src/parse.h | 10 +++++++ 2 files changed, 81 insertions(+) create mode 100644 utils/src/parse.c create mode 100644 utils/src/parse.h diff --git a/utils/src/parse.c b/utils/src/parse.c new file mode 100644 index 00000000..6e01b9d7 --- /dev/null +++ b/utils/src/parse.c @@ -0,0 +1,71 @@ +#include +#include +#include +#include +#include + +#include "sparse.h" +#include "util.h" +#include "format.h" + +#include "parse.h" + +int parse_u64(char *str, u64 *val_ret) +{ + unsigned long long ull; + char *endptr = NULL; + + ull = strtoull(str, &endptr, 0); + if (*endptr != '\0' || + ((ull == LLONG_MIN || ull == LLONG_MAX) && + errno == ERANGE)) { + fprintf(stderr, "invalid 64bit value: '%s'\n", str); + *val_ret = 0; + return -EINVAL; + } + + *val_ret = ull; + + return 0; +} + +int parse_u32(char *str, u32 *val_ret) +{ + u64 val; + int ret; + + ret = parse_u64(str, &val); + if (ret) + return ret; + + if (val > UINT_MAX) + return -EINVAL; + + *val_ret = val; + return 0; +} + +int parse_timespec(char *str, struct scoutfs_timespec *ts) +{ + unsigned long long sec; + unsigned int nsec; + int ret; + + memset(ts, 0, sizeof(struct scoutfs_timespec)); + + ret = sscanf(str, "%llu.%u", &sec, &nsec); + if (ret != 2) { + fprintf(stderr, "invalid timespec string: '%s'\n", str); + return -EINVAL; + } + + if (nsec > 1000000000) { + fprintf(stderr, "invalid timespec nsec value: '%s'\n", str); + return -EINVAL; + } + + ts->sec = cpu_to_le64(sec); + ts->nsec = cpu_to_le32(nsec); + + return 0; +} diff --git a/utils/src/parse.h b/utils/src/parse.h new file mode 100644 index 00000000..e1361853 --- /dev/null +++ b/utils/src/parse.h @@ -0,0 +1,10 @@ +#ifndef _PARSE_H_ +#define _PARSE_H_ + +struct scoutfs_timespec; + +int parse_u64(char *str, u64 *val_ret); +int parse_u32(char *str, u32 *val_ret); +int parse_timespec(char *str, struct scoutfs_timespec *ts); + +#endif