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 <zab@versity.com>
This commit is contained in:
Zach Brown
2019-05-24 10:37:37 -07:00
committed by Zach Brown
parent 57da5fae4c
commit ffe15c2d82
2 changed files with 81 additions and 0 deletions

71
utils/src/parse.c Normal file
View File

@@ -0,0 +1,71 @@
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <stdio.h>
#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;
}

10
utils/src/parse.h Normal file
View File

@@ -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