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