2 * Copyright (c) 2011 Alex Hornung <alex@alexhornung.com>.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in
13 * the documentation and/or other materials provided with the
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
19 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
20 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
22 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
26 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39 static const char prefixes[] = " KMGTPE";
41 _humanize_number(char *buf, size_t bufsz, uint64_t num)
51 while ((i > 1024) && (*prefixp != '\0')) {
58 ret = snprintf(buf, bufsz, "%"PRIu64".%"PRIu64" %c",
61 ret = snprintf(buf, bufsz, "%"PRIu64" %c", i, *prefixp);
64 if ((ret < 0) || ((size_t)ret >= bufsz)) {
73 _dehumanize_number(const char *buf, uint64_t *dest)
76 uint64_t n, n_check, d;
86 if (tolower(buf[len-1]) == 'b')
91 switch (tolower(buf[len-1])) {
118 * only set error if string ends in a character that
119 * is not a valid unit.
121 if (isalpha(buf[len-1])) {
128 n = n_check = strtoull(buf, &endptr, 10);
130 if ((*endptr != '.') && (*endptr != '\0') &&
131 (*endptr != ' ') && (endptr != &buf[len-1])) {
136 if (*endptr == '.') {
137 d = strtoull(endptr+1, &endptr, 10);
138 if (endptr && (*endptr != '\0') &&
140 (endptr != &buf[len-1])) {
155 d *= (multiplier/1024);
158 if ((uint64_t)(n/multiplier) != n_check) {
169 #ifdef __TEST_HUMANIZE__
172 int main(int argc, char *argv[])
181 n = strtoull(argv[1], NULL, 10);
183 err = _humanize_number(buf, 1024, n);
186 err = _dehumanize_number(buf, &out);
189 printf("Converting: %"PRIu64" => %s => %"PRIu64"\n", n, buf, out);
191 err = _dehumanize_number(argv[2], &out);
194 printf("Converting: %s => %"PRIu64"\n", argv[2], out);