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])) {
111 * only set error if string ends in a character that
112 * is not a valid unit.
114 if (isalpha(buf
[len
-1])) {
121 n
= n_check
= strtoull(buf
, &endptr
, 10);
123 if ((*endptr
!= '.') && (*endptr
!= '\0') &&
124 (*endptr
!= ' ') && (endptr
!= &buf
[len
-1])) {
129 if (*endptr
== '.') {
130 d
= strtoull(endptr
+1, &endptr
, 10);
131 if (endptr
&& (*endptr
!= '\0') &&
133 (endptr
!= &buf
[len
-1])) {
148 d
*= (multiplier
/1024);
151 if ((uint64_t)(n
/multiplier
) != n_check
) {
162 #ifdef __TEST_HUMANIZE__
165 int main(int argc
, char *argv
[])
174 n
= strtoull(argv
[1], NULL
, 10);
176 err
= _humanize_number(buf
, 1024, n
);
179 err
= _dehumanize_number(buf
, &out
);
182 printf("Converting: %"PRIu64
" => %s => %"PRIu64
"\n", n
, buf
, out
);
184 err
= _dehumanize_number(argv
[2], &out
);
187 printf("Converting: %s => %"PRIu64
"\n", argv
[2], out
);