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