mirror of
https://github.com/versity/scoutfs.git
synced 2026-01-06 20:16:25 +00:00
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:
71
utils/src/parse.c
Normal file
71
utils/src/parse.c
Normal 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
10
utils/src/parse.h
Normal 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
|
||||
Reference in New Issue
Block a user