procfs-util: modernize convert_meminfo_value_to_uint64_bytes()

This commit is contained in:
Mike Yuan
2025-03-24 16:45:10 +01:00
parent 110d0ff1fa
commit 40d54c2da0

View File

@@ -175,46 +175,34 @@ int procfs_cpu_get_usage(nsec_t *ret) {
return 0;
}
int convert_meminfo_value_to_uint64_bytes(const char *word, uint64_t *ret) {
int convert_meminfo_value_to_uint64_bytes(const char *s, uint64_t *ret) {
_cleanup_free_ char *w = NULL;
char *digits, *e;
uint64_t v;
size_t n;
int r;
assert(word);
assert(s);
assert(ret);
w = strdup(word);
if (!w)
return -ENOMEM;
/* Determine length of numeric value */
n = strspn(w, WHITESPACE);
digits = w + n;
n = strspn(digits, DIGITS);
if (n == 0)
return -EINVAL;
e = digits + n;
/* Ensure the line ends in " kB" */
n = strspn(e, WHITESPACE);
if (n == 0)
return -EINVAL;
if (!streq(e + n, "kB"))
r = extract_first_word(&s, &w, /* separators = */ NULL, /* flags = */ 0);
if (r < 0)
return r;
if (r == 0)
return -EINVAL;
*e = 0;
r = safe_atou64(digits, &v);
/* Ensure the line ends in "kB" */
if (!streq(s, "kB"))
return -EINVAL;
r = safe_atou64(w, &v);
if (r < 0)
return r;
if (v == UINT64_MAX)
return -EINVAL;
if (v > UINT64_MAX/1024)
if (!MUL_ASSIGN_SAFE(&v, U64_KB))
return -EOVERFLOW;
*ret = v * 1024U;
*ret = v;
return 0;
}