(suffixes): Prefer K to k for 1024.
[gnulib.git] / lib / human.c
1 /* human.c -- print human readable file size
2
3    Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001 Free Software
4    Foundation, Inc.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2, or (at your option)
9    any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software Foundation,
18    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
19
20 /* Originally contributed by lm@sgi.com;
21    --si, output block size selection, and large file support
22    added by eggert@twinsun.com.  */
23
24 #if HAVE_CONFIG_H
25 # include <config.h>
26 #endif
27
28 #include <sys/types.h>
29 #include <stdio.h>
30
31 #if HAVE_LIMITS_H
32 # include <limits.h>
33 #endif
34
35 #if HAVE_STRING_H
36 # include <string.h>
37 #else
38 # include <strings.h>
39 #endif
40
41 #ifndef CHAR_BIT
42 # define CHAR_BIT 8
43 #endif
44 #if HAVE_STDLIB_H
45 # include <stdlib.h>
46 #endif
47
48 #ifndef HAVE_DECL_GETENV
49 "this configure-time declaration test was not run"
50 #endif
51 #if !HAVE_DECL_GETENV
52 char *getenv ();
53 #endif
54
55 #if ENABLE_NLS
56 # include <libintl.h>
57 # define _(Text) gettext (Text)
58 #else
59 # define _(Text) Text
60 #endif
61
62 #include <argmatch.h>
63 #include <error.h>
64 #include <xstrtol.h>
65
66 #include "human.h"
67
68 static const char suffixes[] =
69 {
70   0,    /* not used */
71   'K',  /* kibi ('k' for kilo is a special case) */
72   'M',  /* mega or mebi */
73   'G',  /* giga or gibi */
74   'T',  /* tera or tebi */
75   'P',  /* peta or pebi */
76   'E',  /* exa or exbi */
77   'Z',  /* zetta or 2**70 */
78   'Y'   /* yotta or 2**80 */
79 };
80
81 /* Generate into P[-1] (and possibly P[-2]) the proper suffix for
82    POWER and BASE.  Return the address of the generated suffix.  */
83 static char *
84 generate_suffix_backwards (char *p, int power, int base)
85 {
86   char letter = suffixes[power];
87
88   if (base == 1000)
89     {
90       *--p = 'B';
91       if (power == 1)
92         letter = 'k';
93     }
94
95   *--p = letter;
96   return p;
97 }
98
99 /* If INEXACT_STYLE is not human_round_to_even, and if easily
100    possible, adjust VALUE according to the style.  */
101 static double
102 adjust_value (enum human_inexact_style inexact_style, double value)
103 {
104   /* Do not use the floor or ceil functions, as that would mean
105      linking with the standard math library, which is a porting pain.
106      So leave the value alone if it is too large to easily round.  */
107   if (inexact_style != human_round_to_even && value < (uintmax_t) -1)
108     {
109       uintmax_t u = value;
110       value = u + (inexact_style == human_ceiling && u != value);
111     }
112
113   return value;
114 }
115
116 /* Like human_readable_inexact, except always round to even.  */
117 char *
118 human_readable (uintmax_t n, char *buf,
119                 int from_block_size, int output_block_size)
120 {
121   return human_readable_inexact (n, buf, from_block_size, output_block_size,
122                                  human_round_to_even);
123 }
124
125 /* Convert N to a human readable format in BUF.
126
127    N is expressed in units of FROM_BLOCK_SIZE.  FROM_BLOCK_SIZE must
128    be nonnegative.
129
130    OUTPUT_BLOCK_SIZE must be nonzero.  If it is positive, use units of
131    OUTPUT_BLOCK_SIZE in the output number.
132
133    Use INEXACT_STYLE to determine whether to take the ceiling or floor
134    of any result that cannot be expressed exactly.
135
136    If OUTPUT_BLOCK_SIZE is negative, use a format like "127K" if
137    possible, using powers of -OUTPUT_BLOCK_SIZE; otherwise, use
138    ordinary decimal format.  Normally -OUTPUT_BLOCK_SIZE is either
139    1000 or 1024; it must be at least 2.  Most people visually process
140    strings of 3-4 digits effectively, but longer strings of digits are
141    more prone to misinterpretation.  Hence, converting to an
142    abbreviated form usually improves readability.  Use a suffix
143    indicating which power is being used.  For example, assuming
144    -OUTPUT_BLOCK_SIZE is 1024, 8500 would be converted to 8.3K,
145    133456345 to 127M, 56990456345 to 53G, and so on.  Numbers smaller
146    than -OUTPUT_BLOCK_SIZE aren't modified.  If -OUTPUT_BLOCK_SIZE is
147    1024, append a "B" after any size letter.  */
148
149 char *
150 human_readable_inexact (uintmax_t n, char *buf,
151                         int from_block_size, int output_block_size,
152                         enum human_inexact_style inexact_style)
153 {
154   uintmax_t amt;
155   int base;
156   int to_block_size;
157   int tenths = 0;
158   int power;
159   char *p;
160
161   /* 0 means adjusted N == AMT.TENTHS;
162      1 means AMT.TENTHS < adjusted N < AMT.TENTHS + 0.05;
163      2 means adjusted N == AMT.TENTHS + 0.05;
164      3 means AMT.TENTHS + 0.05 < adjusted N < AMT.TENTHS + 0.1.  */
165   int rounding = 0;
166
167   if (output_block_size < 0)
168     {
169       base = -output_block_size;
170       to_block_size = 1;
171     }
172   else
173     {
174       base = 0;
175       to_block_size = output_block_size;
176     }
177
178   p = buf + LONGEST_HUMAN_READABLE;
179   *p = '\0';
180
181 #ifdef lint
182   /* Suppress `used before initialized' warning.  */
183   power = 0;
184 #endif
185
186   /* Adjust AMT out of FROM_BLOCK_SIZE units and into TO_BLOCK_SIZE units.  */
187
188   {
189     int multiplier;
190     int divisor;
191     int r2;
192     int r10;
193     if (to_block_size <= from_block_size
194         ? (from_block_size % to_block_size != 0
195            || (multiplier = from_block_size / to_block_size,
196                (amt = n * multiplier) / multiplier != n))
197         : (from_block_size == 0
198            || to_block_size % from_block_size != 0
199            || (divisor = to_block_size / from_block_size,
200                r10 = (n % divisor) * 10,
201                r2 = (r10 % divisor) * 2,
202                amt = n / divisor,
203                tenths = r10 / divisor,
204                rounding = r2 < divisor ? 0 < r2 : 2 + (divisor < r2),
205                0)))
206       {
207         /* Either the result cannot be computed easily using uintmax_t,
208            or from_block_size is zero.  Fall back on floating point.
209            FIXME: This can yield answers that are slightly off.  */
210
211         double damt = n * (from_block_size / (double) to_block_size);
212
213         if (! base)
214           sprintf (buf, "%.0f", adjust_value (inexact_style, damt));
215         else
216           {
217             char suffix[3];
218             char const *psuffix;
219             double e = 1;
220             power = 0;
221
222             do
223               {
224                 e *= base;
225                 power++;
226               }
227             while (e * base <= damt && power < sizeof suffixes - 1);
228
229             damt /= e;
230
231             suffix[2] = '\0';
232             psuffix = generate_suffix_backwards (suffix + 2, power, base);
233             sprintf (buf, "%.1f%s",
234                      adjust_value (inexact_style, damt), psuffix);
235             if (4 + (base == 1000) < strlen (buf))
236               sprintf (buf, "%.0f%s",
237                        adjust_value (inexact_style, damt * 10) / 10, psuffix);
238           }
239
240         return buf;
241       }
242   }
243
244   /* Use power of BASE notation if adjusted AMT is large enough.  */
245
246   if (base && base <= amt)
247     {
248       power = 0;
249
250       do
251         {
252           int r10 = (amt % base) * 10 + tenths;
253           int r2 = (r10 % base) * 2 + (rounding >> 1);
254           amt /= base;
255           tenths = r10 / base;
256           rounding = (r2 < base
257                       ? 0 < r2 + rounding
258                       : 2 + (base < r2 + rounding));
259           power++;
260         }
261       while (base <= amt && power < sizeof suffixes - 1);
262
263       p = generate_suffix_backwards (p, power, base);
264
265       if (amt < 10)
266         {
267           if (2 * (1 - (int) inexact_style)
268               < rounding + (tenths & (inexact_style == human_round_to_even)))
269             {
270               tenths++;
271               rounding = 0;
272
273               if (tenths == 10)
274                 {
275                   amt++;
276                   tenths = 0;
277                 }
278             }
279
280           if (amt < 10)
281             {
282               *--p = '0' + tenths;
283               *--p = '.';
284               tenths = rounding = 0;
285             }
286         }
287     }
288
289   if (inexact_style == human_ceiling
290       ? 0 < tenths + rounding
291       : inexact_style == human_round_to_even
292       ? 5 < tenths + (2 < rounding + (amt & 1))
293       : /* inexact_style == human_floor */ 0)
294     {
295       amt++;
296
297       if (amt == base && power < sizeof suffixes - 1)
298         {
299           *p = suffixes[power + 1];
300           *--p = '0';
301           *--p = '.';
302           amt = 1;
303         }
304     }
305
306   do
307     *--p = '0' + (int) (amt % 10);
308   while ((amt /= 10) != 0);
309
310   return p;
311 }
312
313
314 /* The default block size used for output.  This number may change in
315    the future as disks get larger.  */
316 #ifndef DEFAULT_BLOCK_SIZE
317 # define DEFAULT_BLOCK_SIZE 1024
318 #endif
319
320 static char const *const block_size_args[] = { "human-readable", "si", 0 };
321 static int const block_size_types[] = { -1024, -1000 };
322
323 static int
324 default_block_size (void)
325 {
326   return getenv ("POSIXLY_CORRECT") ? 512 : DEFAULT_BLOCK_SIZE;
327 }
328
329 static strtol_error
330 humblock (char const *spec, int *block_size)
331 {
332   int i;
333
334   if (! spec && ! (spec = getenv ("BLOCK_SIZE")))
335     *block_size = default_block_size ();
336   else if (0 <= (i = ARGMATCH (spec, block_size_args, block_size_types)))
337     *block_size = block_size_types[i];
338   else
339     {
340       char *ptr;
341       unsigned long val;
342       strtol_error e = xstrtoul (spec, &ptr, 0, &val, "eEgGkKmMpPtTyYzZ0");
343       if (e != LONGINT_OK)
344         return e;
345       if (*ptr)
346         return LONGINT_INVALID_SUFFIX_CHAR;
347       if ((int) val < 0 || val != (int) val)
348         return LONGINT_OVERFLOW;
349       *block_size = (int) val;
350     }
351
352   return LONGINT_OK;
353 }
354
355 void
356 human_block_size (char const *spec, int report_errors, int *block_size)
357 {
358   strtol_error e = humblock (spec, block_size);
359   if (*block_size == 0)
360     {
361       *block_size = default_block_size ();
362       e = LONGINT_INVALID;
363     }
364   if (e != LONGINT_OK && report_errors)
365     STRTOL_FATAL_ERROR (spec, _("block size"), e);
366 }