summaryrefslogtreecommitdiff
path: root/util.c
diff options
context:
space:
mode:
authorJoel Rosdahl <joel@rosdahl.net>2011-04-25 14:06:36 +0200
committerJoel Rosdahl <joel@rosdahl.net>2011-05-30 21:35:53 +0200
commit512ead128699ccc960c3d6b218e81c688de628f0 (patch)
tree0e2cfd3208cfdd3159899224a7ccba1739f95c14 /util.c
parent2ec589ec1968001fcdf0cee66ae69e8b09c1e9ba (diff)
downloadccache-512ead128699ccc960c3d6b218e81c688de628f0.tar.gz
Rename value_units to parse_size_with_suffix and handle errors
Diffstat (limited to 'util.c')
-rw-r--r--util.c36
1 files changed, 22 insertions, 14 deletions
diff --git a/util.c b/util.c
index 1b7c950c..67aa4314 100644
--- a/util.c
+++ b/util.c
@@ -828,31 +828,39 @@ format_size(size_t v)
return s;
}
-/* return a value in multiples of 1024 give a string that can end
- in K, M or G
-*/
-size_t
-value_units(const char *s)
+/*
+ * Parse a value in multiples of 1024 given a string that can end in K, M or G.
+ * Default suffix: G.
+ */
+bool
+parse_size_with_suffix(const char *str, size_t *size)
{
- char m;
- double v = atof(s);
- m = s[strlen(s)-1];
- switch (m) {
+ char *endptr;
+ long x;
+ errno = 0;
+ x = strtol(str, &endptr, 10);
+ if (errno != 0 || x < 0 || endptr == str || *str == '\0') {
+ return false;
+ }
+
+ *size = x;
+ switch (*endptr) {
case 'G':
case 'g':
- default:
- v *= 1024*1024;
+ case '\0':
+ *size *= 1024 * 1024;
break;
case 'M':
case 'm':
- v *= 1024;
+ *size *= 1024;
break;
case 'K':
case 'k':
- v *= 1;
break;
+ default:
+ return false;
}
- return (size_t)v;
+ return true;
}
/*