[PATCH v4 08/17] cutils: qemu_strtou32 function added

Nicolas Eder posted 17 patches 11 months, 3 weeks ago
Maintainers: Nicolas Eder <nicolas.eder@lauterbach.com>, "Alex Bennée" <alex.bennee@linaro.org>, "Philippe Mathieu-Daudé" <philmd@linaro.org>, Richard Henderson <richard.henderson@linaro.org>, Paolo Bonzini <pbonzini@redhat.com>, Peter Xu <peterx@redhat.com>, David Hildenbrand <david@redhat.com>, Eduardo Habkost <eduardo@habkost.net>, Marcel Apfelbaum <marcel.apfelbaum@gmail.com>, Yanan Wang <wangyanan55@huawei.com>, "Marc-André Lureau" <marcandre.lureau@redhat.com>, "Daniel P. Berrangé" <berrange@redhat.com>, Thomas Huth <thuth@redhat.com>
There is a newer version of this series
[PATCH v4 08/17] cutils: qemu_strtou32 function added
Posted by Nicolas Eder 11 months, 3 weeks ago
---
 include/qemu/cutils.h |  2 ++
 util/cutils.c         | 30 ++++++++++++++++++++++++++++++
 2 files changed, 32 insertions(+)

diff --git a/include/qemu/cutils.h b/include/qemu/cutils.h
index 5ab1a4ffb0..14f492ba61 100644
--- a/include/qemu/cutils.h
+++ b/include/qemu/cutils.h
@@ -158,6 +158,8 @@ int qemu_strtoul(const char *nptr, const char **endptr, int base,
                  unsigned long *result);
 int qemu_strtoi64(const char *nptr, const char **endptr, int base,
                   int64_t *result);
+int qemu_strtou32(const char *nptr, const char **endptr, int base,
+                  uint32_t *result);
 int qemu_strtou64(const char *nptr, const char **endptr, int base,
                   uint64_t *result);
 int qemu_strtod(const char *nptr, const char **endptr, double *result);
diff --git a/util/cutils.c b/util/cutils.c
index 42364039a5..5e00a4ec14 100644
--- a/util/cutils.c
+++ b/util/cutils.c
@@ -665,6 +665,36 @@ int qemu_strtoi64(const char *nptr, const char **endptr, int base,
     return check_strtox_error(nptr, ep, endptr, *result == 0, errno);
 }
 
+/**
+ * Convert string @nptr to an uint32_t.
+ *
+ * Works like qemu_strtoul(), except it stores UINT32_MAX on overflow.
+ * (If you want to prohibit negative numbers that wrap around to
+ * positive, use parse_uint()).
+ */
+int qemu_strtou32(const char *nptr, const char **endptr, int base,
+                  uint32_t *result)
+{
+    char *ep;
+
+    assert((unsigned) base <= 36 && base != 1);
+    if (!nptr) {
+        *result = 0;
+        if (endptr) {
+            *endptr = nptr;
+        }
+        return -EINVAL;
+    }
+
+    errno = 0;
+    *result = strtoul(nptr, &ep, base);
+    /* Windows returns 1 for negative out-of-range values.  */
+    if (errno == ERANGE) {
+        *result = -1;
+    }
+    return check_strtox_error(nptr, ep, endptr, *result == 0, errno);
+}
+
 /**
  * Convert string @nptr to an uint64_t.
  *
-- 
2.34.1