Patchwork [2/6] Support human unit formats in strtosz, eg. 1.0G

login
register
mail settings
Submitter Jes Sorensen
Date Oct. 7, 2010, 3:01 p.m.
Message ID <1286463710-28262-3-git-send-email-Jes.Sorensen@redhat.com>
Download mbox | patch
Permalink /patch/67066/
State New
Headers show

Comments

Jes Sorensen - Oct. 7, 2010, 3:01 p.m.
From: Jes Sorensen <Jes.Sorensen@redhat.com>

Signed-off-by: Jes Sorensen <Jes.Sorensen@redhat.com>
---
 cutils.c |   34 ++++++++++++++++++++++++++--------
 1 files changed, 26 insertions(+), 8 deletions(-)

Patch

diff --git a/cutils.c b/cutils.c
index ee591c5..0782032 100644
--- a/cutils.c
+++ b/cutils.c
@@ -291,34 +291,52 @@  int fcntl_setfl(int fd, int flag)
  */
 ssize_t strtosz(const char *nptr, char **end)
 {
-    int64_t value;
+    ssize_t retval = -1;
     char *endptr;
+    int mul_required = 0;
+    double val, mul = 1;
+
+    endptr = (char *)nptr + strspn(nptr, " 0123456789");
+    if (*endptr == '.') {
+        mul_required = 1;
+    }
+
+    val = strtod(nptr, &endptr);
+
+    if (val < 0)
+        goto fail;
 
-    value = strtoll(nptr, &endptr, 0);
     switch (*endptr++) {
     case 'K':
     case 'k':
-        value <<= 10;
+        mul = 1 << 10;
         break;
     case 0:
+    case ' ':
+        if (mul_required) {
+            goto fail;
+        }
     case 'M':
     case 'm':
-        value <<= 20;
+        mul = 1ULL << 20;
         break;
     case 'G':
     case 'g':
-        value <<= 30;
+        mul = 1ULL << 30;
         break;
     case 'T':
     case 't':
-        value <<= 40;
+        mul = 1ULL << 40;
         break;
     default:
-        value = -1;
+        goto fail;
     }
 
+    retval = (ssize_t)(val * mul);
+
     if (end)
         *end = endptr;
 
-    return value;
+fail:
+    return retval;
 }