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