numfmt: a new command to format numbers
[platform/upstream/coreutils.git] / src / numfmt.c
1 /* Reformat numbers like 11505426432 to the more human-readable 11G
2    Copyright (C) 2012 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 3 of the License, or
7    (at your option) 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, see <http://www.gnu.org/licenses/>.  */
16
17 #include <config.h>
18 #include <float.h>
19 #include <getopt.h>
20 #include <stdio.h>
21 #include <sys/types.h>
22 #include <langinfo.h>
23
24 #include "mbsalign.h"
25 #include "argmatch.h"
26 #include "error.h"
27 #include "quote.h"
28 #include "system.h"
29 #include "xstrtol.h"
30 #include "xstrndup.h"
31
32 /* The official name of this program (e.g., no 'g' prefix).  */
33 #define PROGRAM_NAME "numfmt"
34
35 #define AUTHORS proper_name ("Assaf Gordon")
36
37 /* Exit code when some numbers fail to convert.  */
38 enum { EXIT_CONVERSION_WARNINGS = 2 };
39
40 enum
41 {
42   FROM_OPTION = CHAR_MAX + 1,
43   FROM_UNIT_OPTION,
44   TO_OPTION,
45   TO_UNIT_OPTION,
46   ROUND_OPTION,
47   SUFFIX_OPTION,
48   GROUPING_OPTION,
49   PADDING_OPTION,
50   FIELD_OPTION,
51   DEBUG_OPTION,
52   DEV_DEBUG_OPTION,
53   HEADER_OPTION,
54   FORMAT_OPTION,
55   INVALID_OPTION
56 };
57
58 enum scale_type
59 {
60   scale_none,                   /* the default: no scaling.  */
61   scale_auto,                   /* --from only.  */
62   scale_SI,
63   scale_IEC,
64   scale_IEC_I                   /* 'i' suffix is required.  */
65 };
66
67 static char const *const scale_from_args[] =
68 {
69   "none", "auto", "si", "iec", "iec-i", NULL
70 };
71
72 static enum scale_type const scale_from_types[] =
73 {
74   scale_none, scale_auto, scale_SI, scale_IEC, scale_IEC_I
75 };
76
77 static char const *const scale_to_args[] =
78 {
79   "none", "si", "iec", "iec-i", NULL
80 };
81
82 static enum scale_type const scale_to_types[] =
83 {
84   scale_none, scale_SI, scale_IEC, scale_IEC_I
85 };
86
87
88 enum round_type
89 {
90   round_ceiling,
91   round_floor,
92   round_from_zero,
93   round_to_zero,
94   round_nearest,
95 };
96
97 static char const *const round_args[] =
98 {
99   "up", "down", "from-zero", "towards-zero", "nearest", NULL
100 };
101
102 static enum round_type const round_types[] =
103 {
104   round_ceiling, round_floor, round_from_zero, round_to_zero, round_nearest
105 };
106
107
108 enum inval_type
109 {
110   inval_abort,
111   inval_fail,
112   inval_warn,
113   inval_ignore
114 };
115
116 static char const *const inval_args[] =
117 {
118   "abort", "fail", "warn", "ignore", NULL
119 };
120
121 static enum inval_type const inval_types[] =
122 {
123   inval_abort, inval_fail, inval_warn, inval_ignore
124 };
125
126 static struct option const longopts[] =
127 {
128   {"from", required_argument, NULL, FROM_OPTION},
129   {"from-unit", required_argument, NULL, FROM_UNIT_OPTION},
130   {"to", required_argument, NULL, TO_OPTION},
131   {"to-unit", required_argument, NULL, TO_UNIT_OPTION},
132   {"round", required_argument, NULL, ROUND_OPTION},
133   {"padding", required_argument, NULL, PADDING_OPTION},
134   {"suffix", required_argument, NULL, SUFFIX_OPTION},
135   {"grouping", no_argument, NULL, GROUPING_OPTION},
136   {"delimiter", required_argument, NULL, 'd'},
137   {"field", required_argument, NULL, FIELD_OPTION},
138   {"debug", no_argument, NULL, DEBUG_OPTION},
139   {"-devdebug", no_argument, NULL, DEV_DEBUG_OPTION},
140   {"header", optional_argument, NULL, HEADER_OPTION},
141   {"format", required_argument, NULL, FORMAT_OPTION},
142   {"invalid", required_argument, NULL, INVALID_OPTION},
143   {GETOPT_HELP_OPTION_DECL},
144   {GETOPT_VERSION_OPTION_DECL},
145   {NULL, 0, NULL, 0}
146 };
147
148 /* If delimiter has this value, blanks separate fields.  */
149 enum { DELIMITER_DEFAULT = CHAR_MAX + 1 };
150
151 /* Maximum number of digits we can safely handle
152    without precision loss, if scaling is 'none'.  */
153 enum { MAX_UNSCALED_DIGITS = 18 };
154
155 /* Maximum number of digits we can work with.
156    This is equivalent to 999Y.
157    NOTE: 'long double' can handle more than that, but there's
158          no official suffix assigned beyond Yotta (1000^8).  */
159 enum { MAX_ACCEPTABLE_DIGITS = 27 };
160
161 static enum scale_type scale_from = scale_none;
162 static enum scale_type scale_to = scale_none;
163 static enum round_type _round = round_from_zero;
164 static enum inval_type _invalid = inval_abort;
165 static const char *suffix = NULL;
166 static uintmax_t from_unit_size = 1;
167 static uintmax_t to_unit_size = 1;
168 static int grouping = 0;
169 static char *padding_buffer = NULL;
170 static size_t padding_buffer_size = 0;
171 static long int padding_width = 0;
172 static const char *format_str = NULL;
173 static char *format_str_prefix = NULL;
174 static char *format_str_suffix = NULL;
175
176 /* By default, any conversion error will terminate the program.  */
177 static int conv_exit_code = EXIT_CONVERSION_WARNINGS;
178
179
180 /* auto-pad each line based on skipped whitespace.  */
181 static int auto_padding = 0;
182 static mbs_align_t padding_alignment = MBS_ALIGN_RIGHT;
183 static long int field = 1;
184 static int delimiter = DELIMITER_DEFAULT;
185
186 /* if non-zero, the first 'header' lines from STDIN are skipped.  */
187 static uintmax_t header = 0;
188
189 /* Debug for users: print warnings to STDERR about possible
190    error (similar to sort's debug).  */
191 static int debug = 0;
192
193 /* debugging for developers - to be removed in final version?  */
194 static int dev_debug = 0;
195
196 /* will be set according to the current locale.  */
197 static const char *decimal_point;
198 static int decimal_point_length;
199
200
201 static inline int
202 default_scale_base (enum scale_type scale)
203 {
204   switch (scale)
205     {
206     case scale_IEC:
207     case scale_IEC_I:
208       return 1024;
209
210     case scale_none:
211     case scale_auto:
212     case scale_SI:
213     default:
214       return 1000;
215     }
216 }
217
218 static inline int
219 valid_suffix (const char suf)
220 {
221   static const char *valid_suffixes = "KMGTPEZY";
222   return (strchr (valid_suffixes, suf) != NULL);
223 }
224
225 static inline int
226 suffix_power (const char suf)
227 {
228   switch (suf)
229     {
230     case 'K':                  /* kilo or kibi.  */
231       return 1;
232
233     case 'M':                  /* mega or mebi.  */
234       return 2;
235
236     case 'G':                  /* giga or gibi.  */
237       return 3;
238
239     case 'T':                  /* tera or tebi.  */
240       return 4;
241
242     case 'P':                  /* peta or pebi.  */
243       return 5;
244
245     case 'E':                  /* exa or exbi.  */
246       return 6;
247
248     case 'Z':                  /* zetta or 2**70.  */
249       return 7;
250
251     case 'Y':                  /* yotta or 2**80.  */
252       return 8;
253
254     default:                   /* should never happen. assert?  */
255       return 0;
256     }
257 }
258
259 static inline const char *
260 suffix_power_character (unsigned int power)
261 {
262   switch (power)
263     {
264     case 0:
265       return "";
266
267     case 1:
268       return "K";
269
270     case 2:
271       return "M";
272
273     case 3:
274       return "G";
275
276     case 4:
277       return "T";
278
279     case 5:
280       return "P";
281
282     case 6:
283       return "E";
284
285     case 7:
286       return "Z";
287
288     case 8:
289       return "Y";
290
291     default:
292       return "(error)";
293     }
294 }
295
296 /* Similar to 'powl(3)' but without requiring 'libm'.  */
297 static long double
298 powerld (long double base, unsigned int x)
299 {
300   long double result = base;
301   if (x == 0)
302     return 1;                   /* note for test coverage: this is never
303                                    reached, as 'powerld' won't be called if
304                                    there's no suffix, hence, no "power".  */
305
306   /* TODO: check for overflow, inf?  */
307   while (--x)
308     result *= base;
309   return result;
310 }
311
312 /* Similar to 'fabs(3)' but without requiring 'libm'.  */
313 static inline long double
314 absld (long double val)
315 {
316   return val < 0 ? -val : val;
317 }
318
319 /* Scale down 'val', returns 'updated val' and 'x', such that
320      val*base^X = original val
321      Similar to "frexpl(3)" but without requiring 'libm',
322      allowing only integer scale, limited functionality and error checking.  */
323 static long double
324 expld (long double val, unsigned int base, unsigned int /*output */ *x)
325 {
326   unsigned int power = 0;
327
328   if (val >= -LDBL_MAX && val <= LDBL_MAX)
329     {
330       while (absld (val) >= base)
331         {
332           ++power;
333           val /= base;
334         }
335     }
336   if (x)
337     *x = power;
338   return val;
339 }
340
341 /* EXTREMELY limited 'ceil' - without 'libm'.
342    Assumes values that fit in intmax_t.  */
343 static inline intmax_t
344 simple_round_ceiling (long double val)
345 {
346   intmax_t intval = val;
347   if (intval < val)
348     intval++;
349   return intval;
350 }
351
352 /* EXTREMELY limited 'floor' - without 'libm'.
353    Assumes values that fit in intmax_t.  */
354 static inline intmax_t
355 simple_round_floor (long double val)
356 {
357   return -simple_round_ceiling (-val);
358 }
359
360 /* EXTREMELY limited 'round away from zero'.
361    Assumes values that fit in intmax_t.  */
362 static inline intmax_t
363 simple_round_from_zero (long double val)
364 {
365   return val < 0 ? simple_round_floor (val) : simple_round_ceiling (val);
366 }
367
368 /* EXTREMELY limited 'round away to zero'.
369    Assumes values that fit in intmax_t.  */
370 static inline intmax_t
371 simple_round_to_zero (long double val)
372 {
373   return val;
374 }
375
376 /* EXTREMELY limited 'round' - without 'libm'.
377    Assumes values that fit in intmax_t.  */
378 static inline intmax_t
379 simple_round_nearest (long double val)
380 {
381   return val < 0 ? val - 0.5 : val + 0.5;
382 }
383
384 static inline intmax_t
385 simple_round (long double val, enum round_type t)
386 {
387   switch (t)
388     {
389     case round_ceiling:
390       return simple_round_ceiling (val);
391
392     case round_floor:
393       return simple_round_floor (val);
394
395     case round_from_zero:
396       return simple_round_from_zero (val);
397
398     case round_to_zero:
399       return simple_round_to_zero (val);
400
401     case round_nearest:
402       return simple_round_nearest (val);
403
404     default:
405       /* to silence the compiler - this should never happen.  */
406       return 0;
407     }
408 }
409
410 enum simple_strtod_error
411 {
412   SSE_OK = 0,
413   SSE_OK_PRECISION_LOSS,
414   SSE_OVERFLOW,
415   SSE_INVALID_NUMBER,
416
417   /* the following are returned by 'simple_strtod_human'.  */
418   SSE_VALID_BUT_FORBIDDEN_SUFFIX,
419   SSE_INVALID_SUFFIX,
420   SSE_MISSING_I_SUFFIX
421 };
422
423 /* Read an *integer* INPUT_STR,
424    but return the integer value in a 'long double' VALUE
425    hence, no UINTMAX_MAX limitation.
426    NEGATIVE is updated, and is stored separately from the VALUE
427    so that signbit() isn't required to determine the sign of -0..
428    ENDPTR is required (unlike strtod) and is used to store a pointer
429    to the character after the last character used in the conversion.
430
431    Note locale'd grouping is not supported,
432    nor is skipping of white-space supported.
433
434    Returns:
435       SSE_OK - valid number.
436       SSE_OK_PRECISION_LOSS - if more than 18 digits were used.
437       SSE_OVERFLOW          - if more than 27 digits (999Y) were used.
438       SSE_INVALID_NUMBER    - if no digits were found.  */
439 static enum simple_strtod_error
440 simple_strtod_int (const char *input_str,
441                    char **endptr, long double *value, bool *negative)
442 {
443   enum simple_strtod_error e = SSE_OK;
444
445   long double val = 0;
446   unsigned int digits = 0;
447
448   if (*input_str == '-')
449     {
450       input_str++;
451       *negative = true;
452     }
453   else
454     *negative = false;
455
456   *endptr = (char *) input_str;
457   while (*endptr && isdigit (**endptr))
458     {
459       int digit = (**endptr) - '0';
460
461       /* can this happen in some strange locale?  */
462       if (digit < 0 || digit > 9)
463         return SSE_INVALID_NUMBER;
464
465       if (digits > MAX_UNSCALED_DIGITS)
466         e = SSE_OK_PRECISION_LOSS;
467
468       ++digits;
469       if (digits > MAX_ACCEPTABLE_DIGITS)
470         return SSE_OVERFLOW;
471
472       val *= 10;
473       val += digit;
474
475       ++(*endptr);
476     }
477   if (digits == 0)
478     return SSE_INVALID_NUMBER;
479   if (*negative)
480     val = -val;
481
482   if (value)
483     *value = val;
484
485   return e;
486 }
487
488 /* Read a floating-point INPUT_STR represented as "NNNN[.NNNNN]",
489    and return the value in a 'long double' VALUE.
490    ENDPTR is required (unlike strtod) and is used to store a pointer
491    to the character after the last character used in the conversion.
492    PRECISION is optional and used to indicate fractions are present.
493
494    Note locale'd grouping is not supported,
495    nor is skipping of white-space supported.
496
497    Returns:
498       SSE_OK - valid number.
499       SSE_OK_PRECISION_LOSS - if more than 18 digits were used.
500       SSE_OVERFLOW          - if more than 27 digits (999Y) were used.
501       SSE_INVALID_NUMBER    - if no digits were found.  */
502 static enum simple_strtod_error
503 simple_strtod_float (const char *input_str,
504                      char **endptr,
505                      long double *value,
506                      size_t *precision)
507 {
508   bool negative;
509   enum simple_strtod_error e = SSE_OK;
510
511   if (precision)
512     *precision = 0;
513
514   /* TODO: accept locale'd grouped values for the integral part.  */
515   e = simple_strtod_int (input_str, endptr, value, &negative);
516   if (e != SSE_OK && e != SSE_OK_PRECISION_LOSS)
517     return e;
518
519
520   /* optional decimal point + fraction.  */
521   if (STREQ_LEN (*endptr, decimal_point, decimal_point_length))
522     {
523       char *ptr2;
524       long double val_frac = 0;
525       bool neg_frac;
526
527       (*endptr) += decimal_point_length;
528       enum simple_strtod_error e2 =
529         simple_strtod_int (*endptr, &ptr2, &val_frac, &neg_frac);
530       if (e2 != SSE_OK && e2 != SSE_OK_PRECISION_LOSS)
531         return e2;
532       if (e2 == SSE_OK_PRECISION_LOSS)
533         e = e2;                       /* propagate warning.  */
534       if (neg_frac)
535         return SSE_INVALID_NUMBER;
536
537       /* number of digits in the fractions.  */
538       size_t exponent = ptr2 - *endptr;
539
540       val_frac = ((long double) val_frac) / powerld (10, exponent);
541
542       if (value)
543         {
544           if (negative)
545             *value -= val_frac;
546           else
547             *value += val_frac;
548         }
549
550       if (precision)
551         *precision = exponent;
552
553       *endptr = ptr2;
554     }
555   return e;
556 }
557
558 /* Read a 'human' INPUT_STR represented as "NNNN[.NNNNN] + suffix",
559    and return the value in a 'long double' VALUE,
560    with the precision of the input returned in PRECISION.
561    ENDPTR is required (unlike strtod) and is used to store a pointer
562    to the character after the last character used in the conversion.
563    ALLOWED_SCALING determines the scaling supported.
564
565    TODO:
566      support locale'd grouping
567      accept scentific and hex floats (probably use strtold directly)
568
569    Returns:
570       SSE_OK - valid number.
571       SSE_OK_PRECISION_LOSS - if more than 18 digits were used.
572       SSE_OVERFLOW          - if more than 27 digits (999Y) were used.
573       SSE_INVALID_NUMBER    - if no digits were found.
574       SSE_VALID_BUT_FORBIDDEN_SUFFIX
575       SSE_INVALID_SUFFIX
576       SSE_MISSING_I_SUFFIX  */
577 static enum simple_strtod_error
578 simple_strtod_human (const char *input_str,
579                      char **endptr, long double *value, size_t *precision,
580                      enum scale_type allowed_scaling)
581 {
582   int power = 0;
583   /* 'scale_auto' is checked below.  */
584   int scale_base = default_scale_base (allowed_scaling);
585
586   if (dev_debug)
587     error (0, 0, _("simple_strtod_human:\n  input string: '%s'\n  "
588                    "locale decimal-point: '%s'\n"), input_str, decimal_point);
589
590   enum simple_strtod_error e =
591     simple_strtod_float (input_str, endptr, value, precision);
592   if (e != SSE_OK && e != SSE_OK_PRECISION_LOSS)
593     return e;
594
595   if (dev_debug)
596     error (0, 0, _("  parsed numeric value: %Lf\n"
597                    "  input precision = %d\n"), *value, (int)*precision);
598
599   if (**endptr != '\0')
600     {
601       /* process suffix.  */
602
603       /* Skip any blanks between the number and suffix.  */
604       while (isblank (**endptr))
605         (*endptr)++;
606
607       if (!valid_suffix (**endptr))
608         return SSE_INVALID_SUFFIX;
609
610       if (allowed_scaling == scale_none)
611         return SSE_VALID_BUT_FORBIDDEN_SUFFIX;
612
613       power = suffix_power (**endptr);
614       (*endptr)++;                     /* skip first suffix character.  */
615
616       if (allowed_scaling == scale_auto && **endptr == 'i')
617         {
618           /* auto-scaling enabled, and the first suffix character
619               is followed by an 'i' (e.g. Ki, Mi, Gi).  */
620           scale_base = 1024;
621           (*endptr)++;              /* skip second  ('i') suffix character.  */
622           if (dev_debug)
623             error (0, 0, _("  Auto-scaling, found 'i', switching to base %d\n"),
624                     scale_base);
625         }
626
627       *precision = 0;  /* Reset, to select precision based on scale.  */
628     }
629
630   if (allowed_scaling == scale_IEC_I)
631     {
632       if (**endptr == 'i')
633         (*endptr)++;
634       else
635         return SSE_MISSING_I_SUFFIX;
636     }
637
638   long double multiplier = powerld (scale_base, power);
639
640   if (dev_debug)
641     error (0, 0, _("  suffix power=%d^%d = %Lf\n"),
642            scale_base, power, multiplier);
643
644   /* TODO: detect loss of precision and overflows.  */
645   (*value) = (*value) * multiplier;
646
647   if (dev_debug)
648     error (0, 0, _("  returning value: %Lf (%LG)\n"), *value, *value);
649
650   return e;
651 }
652
653
654 static void
655 simple_strtod_fatal (enum simple_strtod_error err, char const *input_str)
656 {
657   char const *msgid = NULL;
658
659   switch (err)
660     {
661     case SSE_OK_PRECISION_LOSS:
662     case SSE_OK:
663       /* should never happen - this function isn't called when OK.  */
664       abort ();
665
666     case SSE_OVERFLOW:
667       msgid = N_("value too large to be converted: '%s'");
668       break;
669
670     case SSE_INVALID_NUMBER:
671       msgid = N_("invalid number: '%s'");
672       break;
673
674     case SSE_VALID_BUT_FORBIDDEN_SUFFIX:
675       msgid = N_("rejecting suffix in input: '%s' (consider using --from)");
676       break;
677
678     case SSE_INVALID_SUFFIX:
679       msgid = N_("invalid suffix in input: '%s'");
680       break;
681
682     case SSE_MISSING_I_SUFFIX:
683       msgid = N_("missing 'i' suffix in input: '%s' (e.g Ki/Mi/Gi)");
684       break;
685
686     }
687
688   if (_invalid != inval_ignore)
689     error (conv_exit_code, 0, gettext (msgid), input_str);
690 }
691
692 /* Convert VAL to a human format string in BUF.  */
693 static void
694 double_to_human (long double val, int precision,
695                  char *buf, size_t buf_size,
696                  enum scale_type scale, int group, enum round_type round)
697 {
698   if (dev_debug)
699     error (0, 0, _("double_to_human:\n"));
700
701   if (scale == scale_none)
702     {
703       val *= powerld (10, precision);
704       val = simple_round (val, round);
705       val /= powerld (10, precision);
706
707       if (dev_debug)
708         error (0, 0,
709                (group) ?
710                _("  no scaling, returning (grouped) value: %'.*Lf\n") :
711                _("  no scaling, returning value: %.*Lf\n"), precision, val);
712
713       int i = snprintf (buf, buf_size, (group) ? "%'.*Lf" : "%.*Lf",
714                         precision, val);
715       if (i < 0 || i >= (int) buf_size)
716         error (EXIT_FAILURE, 0,
717                _("failed to prepare value '%Lf' for printing"), val);
718       return;
719     }
720
721   /* Scaling requested by user. */
722   double scale_base = default_scale_base (scale);
723
724   /* Normalize val to scale. */
725   unsigned int power = 0;
726   val = expld (val, scale_base, &power);
727   if (dev_debug)
728     error (0, 0, _("  scaled value to %Lf * %0.f ^ %d\n"),
729            val, scale_base, power);
730
731   /* Perform rounding. */
732   int ten_or_less = 0;
733   if (absld (val) < 10)
734     {
735       /* for values less than 10, we allow one decimal-point digit,
736          so adjust before rounding. */
737       ten_or_less = 1;
738       val *= 10;
739     }
740   val = simple_round (val, round);
741   /* two special cases after rounding:
742      1. a "999.99" can turn into 1000 - so scale down
743      2. a "9.99" can turn into 10 - so don't display decimal-point.  */
744   if (absld (val) >= scale_base)
745     {
746       val /= scale_base;
747       power++;
748     }
749   if (ten_or_less)
750     val /= 10;
751
752   /* should "7.0" be printed as "7" ?
753      if removing the ".0" is preferred, enable the fourth condition.  */
754   int show_decimal_point = (val != 0) && (absld (val) < 10) && (power > 0);
755   /* && (absld (val) > simple_round_floor (val))) */
756
757   if (dev_debug)
758     error (0, 0, _("  after rounding, value=%Lf * %0.f ^ %d\n"),
759            val, scale_base, power);
760
761   snprintf (buf, buf_size, (show_decimal_point) ? "%.1Lf%s" : "%.0Lf%s",
762             val, suffix_power_character (power));
763
764   if (scale == scale_IEC_I && power > 0)
765     strncat (buf, "i", buf_size - strlen (buf) - 1);
766
767   if (dev_debug)
768     error (0, 0, _("  returning value: '%s'\n"), buf);
769
770   return;
771 }
772
773 /* Convert a string of decimal digits, N_STRING, with an optional suffix
774    to an integral value.  Upon successful conversion, return that value.
775    If it cannot be converted, give a diagnostic and exit.  */
776 static uintmax_t
777 unit_to_umax (const char *n_string)
778 {
779   strtol_error s_err;
780   char *end = NULL;
781   uintmax_t n;
782
783   s_err = xstrtoumax (n_string, &end, 10, &n, "KMGTPEZY");
784
785   if (s_err != LONGINT_OK || *end || n == 0)
786     error (EXIT_FAILURE, 0, _("invalid unit size: '%s'"), n_string);
787
788   return n;
789 }
790
791
792 static void
793 setup_padding_buffer (size_t min_size)
794 {
795   if (padding_buffer_size > min_size)
796     return;
797
798   padding_buffer_size = min_size + 1;
799   padding_buffer = realloc (padding_buffer, padding_buffer_size);
800   if (!padding_buffer)
801     error (EXIT_FAILURE, 0, _("out of memory (requested %zu bytes)"),
802            padding_buffer_size);
803 }
804
805 void
806 usage (int status)
807 {
808   if (status != EXIT_SUCCESS)
809     emit_try_help ();
810   else
811     {
812       printf (_("\
813 Usage: %s [OPTIONS] [NUMBER]\n\
814 "), program_name);
815       fputs (_("\
816 Reformat NUMBER(s) from stdin or command arguments.\n\
817 "), stdout);
818       emit_mandatory_arg_note ();
819       fputs (_("\
820   --from=UNIT     auto-scale input numbers to UNITs. Default is 'none'.\n\
821                   See UNIT below.\n\
822   --from-unit=N   specify the input unit size (instead of the default 1).\n\
823   --to=UNIT       auto-scale output numbers to UNITs.\n\
824                   See UNIT below.\n\
825   --to-unit=N     the output unit size (instead of the default 1).\n\
826   --round=METHOD  the rounding method to use when scaling. METHOD can be:\n\
827                   up, down, from-zero (default), towards-zero, nearest\n\
828   --suffix=SUFFIX add SUFFIX to output numbers, and accept optional SUFFIX\n\
829                   in input numbers.\n\
830   --padding=N     pad the output to N characters.\n\
831                   Positive N will right-aligned. Negative N will left-align.\n\
832                   Note: if the output is wider than N, padding is ignored.\n\
833                   Default is to automatically pad if whitespace is found.\n\
834   --grouping      group digits together (e.g. 1,000,000).\n\
835                   Uses the locale-defined grouping (i.e. have no effect\n\
836                   in C/POSIX locales).\n\
837   --header[=N]    print (without converting) the first N header lines.\n\
838                   N defaults to 1 if not specified.\n\
839   --field N       replace the number in input field N (default is 1)\n\
840   -d, --delimiter=X  use X instead of whitespace for field delimiter\n\
841   --format=FORMAT use printf style floating-point FORMAT.\n\
842                   See FORMAT below for details.\n\
843   --invalid=MODE  failure mode for invalid numbers: MODE can be:\n\
844                   abort (the default), fail, warn, ignore.\n\
845   --debug         print warnings about invalid input.\n\
846   \n\
847 "), stdout);
848       fputs (HELP_OPTION_DESCRIPTION, stdout);
849       fputs (VERSION_OPTION_DESCRIPTION, stdout);
850
851
852       fputs (_("\
853 \n\
854 UNIT options:\n\
855   none       No auto-scaling is done. Suffixes will trigger an error.\n\
856   auto       Accept optional single-letter/two-letter suffix:\n\
857              1K  = 1000\n\
858              1Ki = 1024\n\
859              1G  = 1000000\n\
860              1Gi = 1048576\n\
861   si         Accept optional single letter suffix:\n\
862              1K = 1000\n\
863              1G  = 1000000\n\
864              ...\n\
865   iec        Accept optional single letter suffix:\n\
866              1K = 1024\n\
867              1G = 1048576\n\
868              ...\n\
869   iec-i      Accept optional two-letter suffix:\n\
870              1Ki = 1024\n\
871              1Gi = 1048576\n\
872              ...\n\
873 \n\
874 "), stdout);
875
876       fputs (_("\
877 \n\
878 FORMAT must be suitable for printing one floating-point argument '%f'.\n\
879 Optional quote (%'f) will enable --grouping (if supported by current locale).\n\
880 Optional width value (%10f) will pad output. Optional negative width values\n\
881 (%-10f) will left-pad output.\n\
882 \n\
883 "), stdout);
884
885       printf (_("\
886 \n\
887 Exit status is 0 if all input numbers were successfully converted.\n\
888 By default, %s will stop at the first conversion error with exit status 2.\n\
889 With --invalid='fail' a warning is printed for each conversion error\n\
890 and the exit status is 2.  With --invalid='warn' each conversion error is\n\
891 diagnosed, but the exit status is 0.  With --invalid='ignore' conversion\n\
892 errors are not diagnosed and the exit status is 0.\n\
893 \n\
894 "), program_name);
895
896
897
898       printf (_("\
899 \n\
900 Examples:\n\
901   $ %s --to=si 1000\n\
902             -> \"1.0K\"\n\
903   $ %s --to=iec 2048\n\
904            -> \"2.0K\"\n\
905   $ %s --to=iec-i 4096\n\
906            -> \"4.0Ki\"\n\
907   $ echo 1K | %s --from=si\n\
908            -> \"1000\"\n\
909   $ echo 1K | %s --from=iec\n\
910            -> \"1024\"\n\
911   $ df | %s --header --field 2 --to=si\n\
912   $ ls -l | %s --header --field 5 --to=iec\n\
913   $ ls -lh | %s --header --field 5 --from=iec --padding=10\n\
914   $ ls -lh | %s --header --field 5 --from=iec --format %%10f\n\
915 "),
916               program_name, program_name, program_name,
917               program_name, program_name, program_name,
918               program_name, program_name, program_name);
919       emit_ancillary_info ();
920     }
921   exit (status);
922 }
923
924 /* Given 'fmt' (a printf(3) compatible format string), extracts the following:
925     1. padding (e.g. %20f)
926     2. alignment (e.g. %-20f)
927     3. grouping (e.g. %'f)
928
929    Only a limited subset of printf(3) syntax is supported.
930
931    TODO:
932      support .precision
933      support %e %g etc. rather than just %f
934
935    NOTES:
936    1. This function sets the global variables:
937        padding_width, padding_alignment, grouping,
938        format_str_prefix, format_str_suffix
939    2. The function aborts on any errors.  */
940 static void
941 parse_format_string (char const *fmt)
942 {
943   size_t i;
944   size_t prefix_len = 0;
945   size_t suffix_pos;
946   long int pad = 0;
947   char *endptr = NULL;
948
949   for (i = 0; !(fmt[i] == '%' && fmt[i + 1] != '%'); i += (fmt[i] == '%') + 1)
950     {
951       if (!fmt[i])
952         error (EXIT_FAILURE, 0,
953                _("format %s has no %% directive"), quote (fmt));
954       prefix_len++;
955     }
956
957   i++;
958   i += strspn (fmt + i, " ");
959   if (fmt[i] == '\'')
960     {
961       grouping = 1;
962       i++;
963     }
964   i += strspn (fmt + i, " ");
965   errno = 0;
966   pad = strtol (fmt + i, &endptr, 10);
967   if (errno != 0)
968     error (EXIT_FAILURE, 0,
969            _("invalid format %s (width overflow)"), quote (fmt));
970
971   if (endptr != (fmt + i) && pad != 0)
972     {
973       if (pad < 0)
974         {
975           padding_alignment = MBS_ALIGN_LEFT;
976           padding_width = -pad;
977         }
978       else
979         {
980           padding_width = pad;
981         }
982     }
983   i = endptr - fmt;
984
985   if (fmt[i] == '\0')
986     error (EXIT_FAILURE, 0, _("format %s ends in %%"), quote (fmt));
987
988   if (fmt[i] != 'f')
989     error (EXIT_FAILURE, 0, _("invalid format %s,"
990                               " directive must be %%['][-][N]f"),
991            quote (fmt));
992   i++;
993   suffix_pos = i;
994
995   for (; fmt[i] != '\0'; i += (fmt[i] == '%') + 1)
996     if (fmt[i] == '%' && fmt[i + 1] != '%')
997       error (EXIT_FAILURE, 0, _("format %s has too many %% directives"),
998              quote (fmt));
999
1000   if (prefix_len)
1001     {
1002       format_str_prefix = xstrndup (fmt, prefix_len);
1003       if (!format_str_prefix)
1004         error (EXIT_FAILURE, 0, _("out of memory (requested %zu bytes)"),
1005                prefix_len + 1);
1006     }
1007   if (fmt[suffix_pos] != '\0')
1008     {
1009       format_str_suffix = strdup (fmt + suffix_pos);
1010       if (!format_str_suffix)
1011         error (EXIT_FAILURE, 0, _("out of memory (requested %zu bytes)"),
1012                strlen (fmt + suffix_pos));
1013     }
1014
1015   if (dev_debug)
1016     error (0, 0, _("format String:\n  input: %s\n  grouping: %s\n"
1017                    "  padding width: %zu\n  alignment: %s\n"
1018                    "  prefix: '%s'\n  suffix: '%s'\n"),
1019            quote (fmt), (grouping) ? "yes" : "no",
1020            padding_width,
1021            (padding_alignment == MBS_ALIGN_LEFT) ? "Left" : "Right",
1022            format_str_prefix, format_str_suffix);
1023 }
1024
1025 /* Parse a numeric value (with optional suffix) from a string.
1026    Returns a long double value, with input precision.
1027
1028    If there's an error converting the string to value - exits with
1029    an error.
1030
1031    If there are any trailing characters after the number
1032    (besides a valid suffix) - exits with an error.  */
1033 static enum simple_strtod_error
1034 parse_human_number (const char *str, long double /*output */ *value,
1035                     size_t *precision)
1036 {
1037   char *ptr = NULL;
1038
1039   enum simple_strtod_error e =
1040     simple_strtod_human (str, &ptr, value, precision, scale_from);
1041   if (e != SSE_OK && e != SSE_OK_PRECISION_LOSS)
1042     {
1043       simple_strtod_fatal (e, str);
1044       return e;
1045     }
1046
1047   if (ptr && *ptr != '\0')
1048     {
1049       if (_invalid != inval_ignore)
1050         error (conv_exit_code, 0, _("invalid suffix in input '%s': '%s'"),
1051                str, ptr);
1052       e = SSE_INVALID_SUFFIX;
1053     }
1054   return e;
1055 }
1056
1057
1058 /* Print the given VAL, using the requested representation.
1059    The number is printed to STDOUT, with padding and alignment.  */
1060 static int
1061 prepare_padded_number (const long double val, size_t precision)
1062 {
1063   /* Generate Output. */
1064   char buf[128];
1065
1066   /* Can't reliably print too-large values without auto-scaling. */
1067   unsigned int x;
1068   expld (val, 10, &x);
1069   if (scale_to == scale_none && x > MAX_UNSCALED_DIGITS)
1070     {
1071       if (_invalid != inval_ignore)
1072         error (conv_exit_code, 0, _("value too large to be printed: '%Lg'"
1073                                     " (consider using --to)"), val);
1074       return 0;
1075     }
1076
1077   if (x > MAX_ACCEPTABLE_DIGITS - 1)
1078     {
1079       if (_invalid != inval_ignore)
1080         error (conv_exit_code, 0, _("value too large to be printed: '%Lg'"
1081                                     " (cannot handle values > 999Y)"), val);
1082       return 0;
1083     }
1084
1085   double_to_human (val, precision, buf, sizeof (buf), scale_to, grouping,
1086                    _round);
1087   if (suffix)
1088     strncat (buf, suffix, sizeof (buf) - strlen (buf) -1);
1089
1090   if (dev_debug)
1091     error (0, 0, _("formatting output:\n  value: %Lf\n  humanized: '%s'\n"),
1092            val, buf);
1093
1094
1095   if (padding_width && strlen (buf) < padding_width)
1096     {
1097       size_t w = padding_width;
1098       mbsalign (buf, padding_buffer, padding_buffer_size, &w,
1099                 padding_alignment, MBA_UNIBYTE_ONLY);
1100
1101       if (dev_debug)
1102         error (0, 0, _("  After padding: '%s'\n"), padding_buffer);
1103
1104     }
1105   else
1106     {
1107       setup_padding_buffer (strlen (buf) + 1);
1108       strcpy (padding_buffer, buf);
1109     }
1110
1111   return 1;
1112 }
1113
1114 static void
1115 print_padded_number (void)
1116 {
1117   if (format_str_prefix)
1118     fputs (format_str_prefix, stdout);
1119
1120   fputs (padding_buffer, stdout);
1121
1122   if (format_str_suffix)
1123     fputs (format_str_suffix, stdout);
1124 }
1125
1126 /* Converts the TEXT number string to the requested representation,
1127    and handles automatic suffix addition.  */
1128 static int
1129 process_suffixed_number (char *text, long double *result, size_t *precision)
1130 {
1131   if (suffix && strlen (text) > strlen (suffix))
1132     {
1133       char *possible_suffix = text + strlen (text) - strlen (suffix);
1134
1135       if (STREQ (suffix, possible_suffix))
1136         {
1137           /* trim suffix, ONLY if it's at the end of the text.  */
1138           *possible_suffix = '\0';
1139           if (dev_debug)
1140             error (0, 0, _("trimming suffix '%s'\n"), suffix);
1141         }
1142       else
1143         {
1144           if (dev_debug)
1145             error (0, 0, _("no valid suffix found\n"));
1146         }
1147     }
1148
1149   /* Skip white space - always.  */
1150   char *p = text;
1151   while (*p && isblank (*p))
1152     ++p;
1153   const unsigned int skip_count = text - p;
1154
1155   /* setup auto-padding.  */
1156   if (auto_padding)
1157     {
1158       if (skip_count > 0 || field > 1)
1159         {
1160           padding_width = strlen (text);
1161           setup_padding_buffer (padding_width);
1162         }
1163       else
1164         {
1165           padding_width = 0;
1166         }
1167       if (dev_debug)
1168         error (0, 0, _("setting Auto-Padding to %ld characters\n"),
1169                padding_width);
1170     }
1171
1172   long double val = 0;
1173   enum simple_strtod_error e = parse_human_number (p, &val, precision);
1174   if (e == SSE_OK_PRECISION_LOSS && debug)
1175     error (0, 0, _("large input value '%s': possible precision loss"), p);
1176
1177   if (from_unit_size != 1 || to_unit_size != 1)
1178     val = (val * from_unit_size) / to_unit_size;
1179
1180   *result = val;
1181
1182   return (e == SSE_OK || e == SSE_OK_PRECISION_LOSS);
1183 }
1184
1185 /* Skip the requested number of fields in the input string.
1186    Returns a pointer to the *delimiter* of the requested field,
1187    or a pointer to NUL (if reached the end of the string).  */
1188 static inline char *
1189 __attribute ((pure))
1190 skip_fields (char *buf, int fields)
1191 {
1192   char *ptr = buf;
1193   if (delimiter != DELIMITER_DEFAULT)
1194     {
1195       if (*ptr == delimiter)
1196         fields--;
1197       while (*ptr && fields--)
1198         {
1199           while (*ptr && *ptr == delimiter)
1200             ++ptr;
1201           while (*ptr && *ptr != delimiter)
1202             ++ptr;
1203         }
1204     }
1205   else
1206     while (*ptr && fields--)
1207       {
1208         while (*ptr && isblank (*ptr))
1209           ++ptr;
1210         while (*ptr && !isblank (*ptr))
1211           ++ptr;
1212       }
1213   return ptr;
1214 }
1215
1216 /* Parse a delimited string, and extracts the requested field.
1217    NOTE: the input buffer is modified.
1218
1219    TODO:
1220      Maybe support multiple fields, though can always pipe output
1221      into another numfmt to process other fields.
1222      Maybe default to processing all fields rather than just first?
1223
1224    Output:
1225      _PREFIX, _DATA, _SUFFIX will point to the relevant positions
1226      in the input string, or be NULL if such a part doesn't exist.  */
1227 static void
1228 extract_fields (char *line, int _field,
1229                 char ** _prefix, char ** _data, char ** _suffix)
1230 {
1231   char *ptr = line;
1232   *_prefix = NULL;
1233   *_data = NULL;
1234   *_suffix = NULL;
1235
1236   if (dev_debug)
1237     error (0, 0, _("extracting Fields:\n  input: '%s'\n  field: %d\n"),
1238            line, _field);
1239
1240   if (field > 1)
1241     {
1242       /* skip the requested number of fields.  */
1243       *_prefix = line;
1244       ptr = skip_fields (line, field - 1);
1245       if (*ptr == '\0')
1246         {
1247           /* not enough fields in the input - print warning?  */
1248           if (dev_debug)
1249             error (0, 0, _("  TOO FEW FIELDS!\n  prefix: '%s'\n"), *_prefix);
1250           return;
1251         }
1252
1253       *ptr = '\0';
1254       ++ptr;
1255     }
1256
1257   *_data = ptr;
1258   *_suffix = skip_fields (*_data, 1);
1259   if (**_suffix)
1260     {
1261       /* there is a suffix (i.e. the field is not the last on the line),
1262          so null-terminate the _data before it.  */
1263       **_suffix = '\0';
1264       ++(*_suffix);
1265     }
1266   else
1267     *_suffix = NULL;
1268
1269   if (dev_debug)
1270     error (0, 0, _("  prefix: '%s'\n  number: '%s'\n  suffix: '%s'\n"),
1271            *_prefix, *_data, *_suffix);
1272 }
1273
1274
1275 /* Convert a number in a given line of text.
1276    NEWLINE specifies whether to output a '\n' for this "line".  */
1277 static int
1278 process_line (char *line, bool newline)
1279 {
1280   char *pre, *num, *suf;
1281   long double val = 0;
1282   size_t precision = 0;
1283   int valid_number = 0;
1284
1285   extract_fields (line, field, &pre, &num, &suf);
1286   if (!num)
1287     if (_invalid != inval_ignore)
1288       error (conv_exit_code, 0, _("input line is too short, "
1289                                   "no numbers found to convert in field %ld"),
1290            field);
1291
1292   if (num)
1293     {
1294       valid_number = process_suffixed_number (num, &val, &precision);
1295       if (valid_number)
1296         valid_number = prepare_padded_number (val, precision);
1297     }
1298
1299   if (pre)
1300     fputs (pre, stdout);
1301
1302   if (pre && num)
1303     fputc ((delimiter == DELIMITER_DEFAULT) ? ' ' : delimiter, stdout);
1304
1305   if (valid_number)
1306     {
1307       print_padded_number ();
1308     }
1309   else
1310     {
1311       if (num)
1312         fputs (num, stdout);
1313     }
1314
1315   if (suf)
1316     {
1317       fputc ((delimiter == DELIMITER_DEFAULT) ? ' ' : delimiter, stdout);
1318       fputs (suf, stdout);
1319     }
1320
1321   if (newline)
1322     putchar ('\n');
1323
1324   return valid_number;
1325 }
1326
1327 int
1328 main (int argc, char **argv)
1329 {
1330   int valid_numbers = 1;
1331
1332   initialize_main (&argc, &argv);
1333   set_program_name (argv[0]);
1334   setlocale (LC_ALL, "");
1335   bindtextdomain (PACKAGE, LOCALEDIR);
1336   textdomain (PACKAGE);
1337
1338   decimal_point = nl_langinfo (RADIXCHAR);
1339   if (decimal_point == NULL || strlen (decimal_point) == 0)
1340     decimal_point = ".";
1341   decimal_point_length = strlen (decimal_point);
1342
1343   atexit (close_stdout);
1344
1345   while (true)
1346     {
1347       int c = getopt_long (argc, argv, "d:", longopts, NULL);
1348
1349       if (c == -1)
1350         break;
1351
1352       switch (c)
1353         {
1354         case FROM_OPTION:
1355           scale_from = XARGMATCH ("--from", optarg,
1356                                   scale_from_args, scale_from_types);
1357           break;
1358
1359         case FROM_UNIT_OPTION:
1360           from_unit_size = unit_to_umax (optarg);
1361           break;
1362
1363         case TO_OPTION:
1364           scale_to =
1365             XARGMATCH ("--to", optarg, scale_to_args, scale_to_types);
1366           break;
1367
1368         case TO_UNIT_OPTION:
1369           to_unit_size = unit_to_umax (optarg);
1370           break;
1371
1372         case ROUND_OPTION:
1373           _round = XARGMATCH ("--round", optarg, round_args, round_types);
1374           break;
1375
1376         case GROUPING_OPTION:
1377           grouping = 1;
1378           break;
1379
1380         case PADDING_OPTION:
1381           if (xstrtol (optarg, NULL, 10, &padding_width, "") != LONGINT_OK
1382               || padding_width == 0)
1383             error (EXIT_FAILURE, 0, _("invalid padding value '%s'"), optarg);
1384           if (padding_width < 0)
1385             {
1386               padding_alignment = MBS_ALIGN_LEFT;
1387               padding_width = -padding_width;
1388             }
1389           /* TODO: We probably want to apply a specific --padding
1390              to --header lines too.  */
1391           break;
1392
1393         case FIELD_OPTION:
1394           if (xstrtol (optarg, NULL, 10, &field, "") != LONGINT_OK
1395               || field <= 0)
1396             error (EXIT_FAILURE, 0, _("invalid field value '%s'"), optarg);
1397           break;
1398
1399         case 'd':
1400           /* Interpret -d '' to mean 'use the NUL byte as the delimiter.'  */
1401           if (optarg[0] != '\0' && optarg[1] != '\0')
1402             error (EXIT_FAILURE, 0,
1403                    _("the delimiter must be a single character"));
1404           delimiter = optarg[0];
1405           break;
1406
1407         case SUFFIX_OPTION:
1408           suffix = optarg;
1409           break;
1410
1411         case DEBUG_OPTION:
1412           debug = 1;
1413           break;
1414
1415         case DEV_DEBUG_OPTION:
1416           dev_debug = 1;
1417           debug = 1;
1418           break;
1419
1420         case HEADER_OPTION:
1421           if (optarg)
1422             {
1423               if (xstrtoumax (optarg, NULL, 10, &header, "") != LONGINT_OK
1424                   || header == 0)
1425                 error (EXIT_FAILURE, 0, _("invalid header value '%s'"),
1426                        optarg);
1427             }
1428           else
1429             {
1430               header = 1;
1431             }
1432           break;
1433
1434         case FORMAT_OPTION:
1435           format_str = optarg;
1436           break;
1437
1438         case INVALID_OPTION:
1439           _invalid = XARGMATCH ("--invalid", optarg, inval_args, inval_types);
1440           break;
1441
1442           case_GETOPT_HELP_CHAR;
1443           case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1444
1445         default:
1446           usage (EXIT_FAILURE);
1447         }
1448     }
1449
1450   if (format_str != NULL && grouping)
1451     error (EXIT_FAILURE, 0, _("--grouping cannot be combined with --format"));
1452   if (format_str != NULL && padding_width > 0)
1453     error (EXIT_FAILURE, 0, _("--padding cannot be combined with --format"));
1454
1455   /* Warn about no-op.  */
1456   if (debug && scale_from == scale_none && scale_to == scale_none
1457       && !grouping && (padding_width == 0) && (format_str == NULL))
1458     error (0, 0, _("no conversion option specified"));
1459
1460   if (format_str)
1461     parse_format_string (format_str);
1462
1463   if (grouping)
1464     {
1465       if (scale_to != scale_none)
1466         error (EXIT_FAILURE, 0, _("grouping cannot be combined with --to"));
1467       if (debug && (strlen (nl_langinfo (THOUSEP)) == 0))
1468         error (0, 0, _("grouping has no effect in this locale"));
1469     }
1470
1471
1472   setup_padding_buffer (padding_width);
1473   auto_padding = (padding_width == 0 && delimiter == DELIMITER_DEFAULT);
1474
1475   if (_invalid != inval_abort)
1476     conv_exit_code = 0;
1477
1478   if (argc > optind)
1479     {
1480       if (debug && header)
1481         error (0, 0, _("--header ignored with command-line input"));
1482
1483       for (; optind < argc; optind++)
1484         valid_numbers &= process_line (argv[optind], true);
1485     }
1486   else
1487     {
1488       char *line = NULL;
1489       size_t line_allocated = 0;
1490       ssize_t len;
1491
1492       while (header-- && getline (&line, &line_allocated, stdin) > 0)
1493         fputs (line, stdout);
1494
1495       while ((len = getline (&line, &line_allocated, stdin)) > 0)
1496         {
1497           bool newline = line[len - 1] == '\n';
1498           if (newline)
1499             line[len - 1] = '\0';
1500           valid_numbers &= process_line (line, newline);
1501         }
1502
1503       IF_LINT (free (line));
1504
1505       if (ferror (stdin))
1506         error (0, errno, _("error reading input"));
1507     }
1508
1509   free (padding_buffer);
1510   free (format_str_prefix);
1511   free (format_str_suffix);
1512
1513
1514   if (debug && !valid_numbers)
1515     error (0, 0, _("failed to convert some of the input numbers"));
1516
1517   int exit_status = EXIT_SUCCESS;
1518   if (!valid_numbers && _invalid != inval_warn && _invalid != inval_ignore)
1519     exit_status = EXIT_CONVERSION_WARNINGS;
1520
1521   exit (exit_status);
1522 }