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