aboutsummaryrefslogtreecommitdiff
path: root/util
diff options
context:
space:
mode:
authorCarlos L. Torres <carlos.torres@rackspace.com>2015-07-19 18:02:17 -0500
committerPaolo Bonzini <pbonzini@redhat.com>2015-09-09 15:34:54 +0200
commit764e0fa497ff5bbc9c9d7c116da2f00f34e71716 (patch)
tree3cefe45e5dca9385edd29e6c7ee025631bb5a26b /util
parentd1142fb83efdcf8a6c2dee825569892203e16d2c (diff)
cutils: Add qemu_strtol() wrapper
Add wrapper for strtol() function. Include unit tests. Signed-off-by: Carlos L. Torres <carlos.torres@rackspace.com> Message-Id: <07199f1c0ff3892790c6322123aee1e92f580550.1437346779.git.carlos.torres@rackspace.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
Diffstat (limited to 'util')
-rw-r--r--util/cutils.c58
1 files changed, 58 insertions, 0 deletions
diff --git a/util/cutils.c b/util/cutils.c
index 5d1c9ebe05..3330360abf 100644
--- a/util/cutils.c
+++ b/util/cutils.c
@@ -359,6 +359,64 @@ int64_t strtosz(const char *nptr, char **end)
}
/**
+ * Helper function for qemu_strto*l() functions.
+ */
+static int check_strtox_error(const char **next, char *endptr,
+ int err)
+{
+ if (!next && *endptr) {
+ return -EINVAL;
+ }
+ if (next) {
+ *next = endptr;
+ }
+ return -err;
+}
+
+/**
+ * QEMU wrappers for strtol(), strtoll(), strtoul(), strotull() C functions.
+ *
+ * Convert ASCII string @nptr to a long integer value
+ * from the given @base. Parameters @nptr, @endptr, @base
+ * follows same semantics as strtol() C function.
+ *
+ * Unlike from strtol() function, if @endptr is not NULL, this
+ * function will return -EINVAL whenever it cannot fully convert
+ * the string in @nptr with given @base to a long. This function returns
+ * the result of the conversion only through the @result parameter.
+ *
+ * If NULL is passed in @endptr, then the whole string in @ntpr
+ * is a number otherwise it returns -EINVAL.
+ *
+ * RETURN VALUE
+ * Unlike from strtol() function, this wrapper returns either
+ * -EINVAL or the errno set by strtol() function (e.g -ERANGE).
+ * If the conversion overflows, -ERANGE is returned, and @result
+ * is set to the max value of the desired type
+ * (e.g. LONG_MAX, LLONG_MAX, ULONG_MAX, ULLONG_MAX). If the case
+ * of underflow, -ERANGE is returned, and @result is set to the min
+ * value of the desired type. For strtol(), strtoll(), @result is set to
+ * LONG_MIN, LLONG_MIN, respectively, and for strtoul(), strtoull() it
+ * is set to 0.
+ */
+int qemu_strtol(const char *nptr, const char **endptr, int base,
+ long *result)
+{
+ char *p;
+ int err = 0;
+ if (!nptr) {
+ if (endptr) {
+ *endptr = nptr;
+ }
+ err = -EINVAL;
+ } else {
+ errno = 0;
+ *result = strtol(nptr, &p, base);
+ err = check_strtox_error(endptr, p, errno);
+ }
+ return err;
+}
+/**
* parse_uint:
*
* @s: String to parse