mirror of
https://github.com/systemd/systemd.git
synced 2024-10-30 06:25:37 +03:00
Merge pull request #24568 from poettering/atou16-atou-rework
parse-util: simplify safe_atou8() + safe_atou16()
This commit is contained in:
commit
559bf6b351
@ -476,69 +476,31 @@ int safe_atolli(const char *s, long long int *ret_lli) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int safe_atou8(const char *s, uint8_t *ret) {
|
||||
unsigned base = 0;
|
||||
unsigned long l;
|
||||
char *x = NULL;
|
||||
int safe_atou8_full(const char *s, unsigned base, uint8_t *ret) {
|
||||
unsigned u;
|
||||
int r;
|
||||
|
||||
assert(s);
|
||||
|
||||
s += strspn(s, WHITESPACE);
|
||||
s = mangle_base(s, &base);
|
||||
|
||||
errno = 0;
|
||||
l = strtoul(s, &x, base);
|
||||
if (errno > 0)
|
||||
return -errno;
|
||||
if (!x || x == s || *x != 0)
|
||||
return -EINVAL;
|
||||
if (l != 0 && s[0] == '-')
|
||||
return -ERANGE;
|
||||
if ((unsigned long) (uint8_t) l != l)
|
||||
r = safe_atou_full(s, base, &u);
|
||||
if (r < 0)
|
||||
return r;
|
||||
if (u > UINT8_MAX)
|
||||
return -ERANGE;
|
||||
|
||||
if (ret)
|
||||
*ret = (uint8_t) l;
|
||||
*ret = (uint8_t) u;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int safe_atou16_full(const char *s, unsigned base, uint16_t *ret) {
|
||||
char *x = NULL;
|
||||
unsigned long l;
|
||||
unsigned u;
|
||||
int r;
|
||||
|
||||
assert(s);
|
||||
assert(SAFE_ATO_MASK_FLAGS(base) <= 16);
|
||||
|
||||
if (FLAGS_SET(base, SAFE_ATO_REFUSE_LEADING_WHITESPACE) &&
|
||||
strchr(WHITESPACE, s[0]))
|
||||
return -EINVAL;
|
||||
|
||||
s += strspn(s, WHITESPACE);
|
||||
|
||||
if (FLAGS_SET(base, SAFE_ATO_REFUSE_PLUS_MINUS) &&
|
||||
IN_SET(s[0], '+', '-'))
|
||||
return -EINVAL;
|
||||
|
||||
if (FLAGS_SET(base, SAFE_ATO_REFUSE_LEADING_ZERO) &&
|
||||
s[0] == '0' && s[1] != 0)
|
||||
return -EINVAL;
|
||||
|
||||
s = mangle_base(s, &base);
|
||||
|
||||
errno = 0;
|
||||
l = strtoul(s, &x, SAFE_ATO_MASK_FLAGS(base));
|
||||
if (errno > 0)
|
||||
return -errno;
|
||||
if (!x || x == s || *x != 0)
|
||||
return -EINVAL;
|
||||
if (l != 0 && s[0] == '-')
|
||||
return -ERANGE;
|
||||
if ((unsigned long) (uint16_t) l != l)
|
||||
r = safe_atou_full(s, base, &u);
|
||||
if (r < 0)
|
||||
return r;
|
||||
if (u > UINT16_MAX)
|
||||
return -ERANGE;
|
||||
|
||||
if (ret)
|
||||
*ret = (uint16_t) l;
|
||||
|
||||
*ret = (uint16_t) u;
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
@ -36,7 +36,11 @@ static inline int safe_atou(const char *s, unsigned *ret_u) {
|
||||
int safe_atoi(const char *s, int *ret_i);
|
||||
int safe_atolli(const char *s, long long int *ret_i);
|
||||
|
||||
int safe_atou8(const char *s, uint8_t *ret);
|
||||
int safe_atou8_full(const char *s, unsigned base, uint8_t *ret);
|
||||
|
||||
static inline int safe_atou8(const char *s, uint8_t *ret) {
|
||||
return safe_atou8_full(s, 0, ret);
|
||||
}
|
||||
|
||||
int safe_atou16_full(const char *s, unsigned base, uint16_t *ret);
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user