]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
procfs-util: modernize convert_meminfo_value_to_uint64_bytes()
authorMike Yuan <me@yhndnzj.com>
Mon, 24 Mar 2025 15:45:10 +0000 (16:45 +0100)
committerMike Yuan <me@yhndnzj.com>
Fri, 4 Apr 2025 13:34:51 +0000 (15:34 +0200)
src/basic/procfs-util.c

index 060ea7adad8d5f95e6bca9d0c3971fe5e668c2d3..98f390e49ab13690ddabb44996c12e4a33e74e63 100644 (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)
+        r = extract_first_word(&s, &w, /* separators = */ NULL, /* flags = */ 0);
+        if (r < 0)
+                return r;
+        if (r == 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"))
+        /* Ensure the line ends in "kB" */
+        if (!streq(s, "kB"))
                 return -EINVAL;
 
-        *e = 0;
-        r = safe_atou64(digits, &v);
+        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;
 }