1
0
mirror of https://github.com/systemd/systemd.git synced 2024-10-30 14:55:37 +03:00

Merge pull request #24568 from poettering/atou16-atou-rework

parse-util: simplify safe_atou8() + safe_atou16()
This commit is contained in:
Yu Watanabe 2022-09-06 03:38:41 +09:00 committed by GitHub
commit 559bf6b351
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 54 deletions

View File

@ -476,69 +476,31 @@ int safe_atolli(const char *s, long long int *ret_lli) {
return 0; return 0;
} }
int safe_atou8(const char *s, uint8_t *ret) { int safe_atou8_full(const char *s, unsigned base, uint8_t *ret) {
unsigned base = 0; unsigned u;
unsigned long l; int r;
char *x = NULL;
assert(s); r = safe_atou_full(s, base, &u);
if (r < 0)
s += strspn(s, WHITESPACE); return r;
s = mangle_base(s, &base); if (u > UINT8_MAX)
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)
return -ERANGE; return -ERANGE;
if (ret) *ret = (uint8_t) u;
*ret = (uint8_t) l;
return 0; return 0;
} }
int safe_atou16_full(const char *s, unsigned base, uint16_t *ret) { int safe_atou16_full(const char *s, unsigned base, uint16_t *ret) {
char *x = NULL; unsigned u;
unsigned long l; int r;
assert(s); r = safe_atou_full(s, base, &u);
assert(SAFE_ATO_MASK_FLAGS(base) <= 16); if (r < 0)
return r;
if (FLAGS_SET(base, SAFE_ATO_REFUSE_LEADING_WHITESPACE) && if (u > UINT16_MAX)
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)
return -ERANGE; return -ERANGE;
if (ret) *ret = (uint16_t) u;
*ret = (uint16_t) l;
return 0; return 0;
} }

View File

@ -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_atoi(const char *s, int *ret_i);
int safe_atolli(const char *s, long long 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); int safe_atou16_full(const char *s, unsigned base, uint16_t *ret);