forked from coreutils/coreutils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnumfmt.c
1651 lines (1371 loc) · 43.9 KB
/
numfmt.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Reformat numbers like 11505426432 to the more human-readable 11G
Copyright (C) 2012-2020 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>. */
#include <config.h>
#include <float.h>
#include <getopt.h>
#include <stdio.h>
#include <sys/types.h>
#include <langinfo.h>
#include "mbsalign.h"
#include "argmatch.h"
#include "c-ctype.h"
#include "die.h"
#include "error.h"
#include "quote.h"
#include "system.h"
#include "xstrtol.h"
#include "xstrndup.h"
#include "set-fields.h"
#if HAVE_FPSETPREC
# include <ieeefp.h>
#endif
/* The official name of this program (e.g., no 'g' prefix). */
#define PROGRAM_NAME "numfmt"
#define AUTHORS proper_name ("Assaf Gordon")
/* Exit code when some numbers fail to convert. */
enum { EXIT_CONVERSION_WARNINGS = 2 };
enum
{
FROM_OPTION = CHAR_MAX + 1,
FROM_UNIT_OPTION,
TO_OPTION,
TO_UNIT_OPTION,
ROUND_OPTION,
SUFFIX_OPTION,
GROUPING_OPTION,
PADDING_OPTION,
FIELD_OPTION,
DEBUG_OPTION,
DEV_DEBUG_OPTION,
HEADER_OPTION,
FORMAT_OPTION,
INVALID_OPTION
};
enum scale_type
{
scale_none, /* the default: no scaling. */
scale_auto, /* --from only. */
scale_SI,
scale_IEC,
scale_IEC_I /* 'i' suffix is required. */
};
static char const *const scale_from_args[] =
{
"none", "auto", "si", "iec", "iec-i", NULL
};
static enum scale_type const scale_from_types[] =
{
scale_none, scale_auto, scale_SI, scale_IEC, scale_IEC_I
};
static char const *const scale_to_args[] =
{
"none", "si", "iec", "iec-i", NULL
};
static enum scale_type const scale_to_types[] =
{
scale_none, scale_SI, scale_IEC, scale_IEC_I
};
enum round_type
{
round_ceiling,
round_floor,
round_from_zero,
round_to_zero,
round_nearest,
};
static char const *const round_args[] =
{
"up", "down", "from-zero", "towards-zero", "nearest", NULL
};
static enum round_type const round_types[] =
{
round_ceiling, round_floor, round_from_zero, round_to_zero, round_nearest
};
enum inval_type
{
inval_abort,
inval_fail,
inval_warn,
inval_ignore
};
static char const *const inval_args[] =
{
"abort", "fail", "warn", "ignore", NULL
};
static enum inval_type const inval_types[] =
{
inval_abort, inval_fail, inval_warn, inval_ignore
};
static struct option const longopts[] =
{
{"from", required_argument, NULL, FROM_OPTION},
{"from-unit", required_argument, NULL, FROM_UNIT_OPTION},
{"to", required_argument, NULL, TO_OPTION},
{"to-unit", required_argument, NULL, TO_UNIT_OPTION},
{"round", required_argument, NULL, ROUND_OPTION},
{"padding", required_argument, NULL, PADDING_OPTION},
{"suffix", required_argument, NULL, SUFFIX_OPTION},
{"grouping", no_argument, NULL, GROUPING_OPTION},
{"delimiter", required_argument, NULL, 'd'},
{"field", required_argument, NULL, FIELD_OPTION},
{"debug", no_argument, NULL, DEBUG_OPTION},
{"-debug", no_argument, NULL, DEV_DEBUG_OPTION},
{"header", optional_argument, NULL, HEADER_OPTION},
{"format", required_argument, NULL, FORMAT_OPTION},
{"invalid", required_argument, NULL, INVALID_OPTION},
{"zero-terminated", no_argument, NULL, 'z'},
{GETOPT_HELP_OPTION_DECL},
{GETOPT_VERSION_OPTION_DECL},
{NULL, 0, NULL, 0}
};
/* If delimiter has this value, blanks separate fields. */
enum { DELIMITER_DEFAULT = CHAR_MAX + 1 };
/* Maximum number of digits we can safely handle
without precision loss, if scaling is 'none'. */
enum { MAX_UNSCALED_DIGITS = LDBL_DIG };
/* Maximum number of digits we can work with.
This is equivalent to 999Y.
NOTE: 'long double' can handle more than that, but there's
no official suffix assigned beyond Yotta (1000^8). */
enum { MAX_ACCEPTABLE_DIGITS = 27 };
static enum scale_type scale_from = scale_none;
static enum scale_type scale_to = scale_none;
static enum round_type round_style = round_from_zero;
static enum inval_type inval_style = inval_abort;
static const char *suffix = NULL;
static uintmax_t from_unit_size = 1;
static uintmax_t to_unit_size = 1;
static int grouping = 0;
static char *padding_buffer = NULL;
static size_t padding_buffer_size = 0;
static long int padding_width = 0;
static long int zero_padding_width = 0;
static long int user_precision = -1;
static const char *format_str = NULL;
static char *format_str_prefix = NULL;
static char *format_str_suffix = NULL;
/* By default, any conversion error will terminate the program. */
static int conv_exit_code = EXIT_CONVERSION_WARNINGS;
/* auto-pad each line based on skipped whitespace. */
static int auto_padding = 0;
static mbs_align_t padding_alignment = MBS_ALIGN_RIGHT;
/* field delimiter */
static int delimiter = DELIMITER_DEFAULT;
/* line delimiter. */
static unsigned char line_delim = '\n';
/* if non-zero, the first 'header' lines from STDIN are skipped. */
static uintmax_t header = 0;
/* Debug for users: print warnings to STDERR about possible
error (similar to sort's debug). */
static bool debug;
/* will be set according to the current locale. */
static const char *decimal_point;
static int decimal_point_length;
/* debugging for developers. Enables devmsg(). */
static bool dev_debug = false;
static inline int
default_scale_base (enum scale_type scale)
{
switch (scale)
{
case scale_IEC:
case scale_IEC_I:
return 1024;
case scale_none:
case scale_auto:
case scale_SI:
default:
return 1000;
}
}
static inline int
valid_suffix (const char suf)
{
static const char *valid_suffixes = "KMGTPEZY";
return (strchr (valid_suffixes, suf) != NULL);
}
static inline int
suffix_power (const char suf)
{
switch (suf)
{
case 'K': /* kilo or kibi. */
return 1;
case 'M': /* mega or mebi. */
return 2;
case 'G': /* giga or gibi. */
return 3;
case 'T': /* tera or tebi. */
return 4;
case 'P': /* peta or pebi. */
return 5;
case 'E': /* exa or exbi. */
return 6;
case 'Z': /* zetta or 2**70. */
return 7;
case 'Y': /* yotta or 2**80. */
return 8;
default: /* should never happen. assert? */
return 0;
}
}
static inline const char *
suffix_power_char (unsigned int power)
{
switch (power)
{
case 0:
return "";
case 1:
return "K";
case 2:
return "M";
case 3:
return "G";
case 4:
return "T";
case 5:
return "P";
case 6:
return "E";
case 7:
return "Z";
case 8:
return "Y";
default:
return "(error)";
}
}
/* Similar to 'powl(3)' but without requiring 'libm'. */
static long double
powerld (long double base, unsigned int x)
{
long double result = base;
if (x == 0)
return 1; /* note for test coverage: this is never
reached, as 'powerld' won't be called if
there's no suffix, hence, no "power". */
/* TODO: check for overflow, inf? */
while (--x)
result *= base;
return result;
}
/* Similar to 'fabs(3)' but without requiring 'libm'. */
static inline long double
absld (long double val)
{
return val < 0 ? -val : val;
}
/* Scale down 'val', returns 'updated val' and 'x', such that
val*base^X = original val
Similar to "frexpl(3)" but without requiring 'libm',
allowing only integer scale, limited functionality and error checking. */
static long double
expld (long double val, unsigned int base, unsigned int /*output */ *x)
{
unsigned int power = 0;
if (val >= -LDBL_MAX && val <= LDBL_MAX)
{
while (absld (val) >= base)
{
++power;
val /= base;
}
}
if (x)
*x = power;
return val;
}
/* EXTREMELY limited 'ceil' - without 'libm'.
Assumes values that fit in intmax_t. */
static inline intmax_t
simple_round_ceiling (long double val)
{
intmax_t intval = val;
if (intval < val)
intval++;
return intval;
}
/* EXTREMELY limited 'floor' - without 'libm'.
Assumes values that fit in intmax_t. */
static inline intmax_t
simple_round_floor (long double val)
{
return -simple_round_ceiling (-val);
}
/* EXTREMELY limited 'round away from zero'.
Assumes values that fit in intmax_t. */
static inline intmax_t
simple_round_from_zero (long double val)
{
return val < 0 ? simple_round_floor (val) : simple_round_ceiling (val);
}
/* EXTREMELY limited 'round away to zero'.
Assumes values that fit in intmax_t. */
static inline intmax_t
simple_round_to_zero (long double val)
{
return val;
}
/* EXTREMELY limited 'round' - without 'libm'.
Assumes values that fit in intmax_t. */
static inline intmax_t
simple_round_nearest (long double val)
{
return val < 0 ? val - 0.5 : val + 0.5;
}
static inline long double _GL_ATTRIBUTE_CONST
simple_round (long double val, enum round_type t)
{
intmax_t rval;
intmax_t intmax_mul = val / INTMAX_MAX;
val -= (long double) INTMAX_MAX * intmax_mul;
switch (t)
{
case round_ceiling:
rval = simple_round_ceiling (val);
break;
case round_floor:
rval = simple_round_floor (val);
break;
case round_from_zero:
rval = simple_round_from_zero (val);
break;
case round_to_zero:
rval = simple_round_to_zero (val);
break;
case round_nearest:
rval = simple_round_nearest (val);
break;
default:
/* to silence the compiler - this should never happen. */
return 0;
}
return (long double) INTMAX_MAX * intmax_mul + rval;
}
enum simple_strtod_error
{
SSE_OK = 0,
SSE_OK_PRECISION_LOSS,
SSE_OVERFLOW,
SSE_INVALID_NUMBER,
/* the following are returned by 'simple_strtod_human'. */
SSE_VALID_BUT_FORBIDDEN_SUFFIX,
SSE_INVALID_SUFFIX,
SSE_MISSING_I_SUFFIX
};
/* Read an *integer* INPUT_STR,
but return the integer value in a 'long double' VALUE
hence, no UINTMAX_MAX limitation.
NEGATIVE is updated, and is stored separately from the VALUE
so that signbit() isn't required to determine the sign of -0..
ENDPTR is required (unlike strtod) and is used to store a pointer
to the character after the last character used in the conversion.
Note locale'd grouping is not supported,
nor is skipping of white-space supported.
Returns:
SSE_OK - valid number.
SSE_OK_PRECISION_LOSS - if more than 18 digits were used.
SSE_OVERFLOW - if more than 27 digits (999Y) were used.
SSE_INVALID_NUMBER - if no digits were found. */
static enum simple_strtod_error
simple_strtod_int (const char *input_str,
char **endptr, long double *value, bool *negative)
{
enum simple_strtod_error e = SSE_OK;
long double val = 0;
unsigned int digits = 0;
bool found_digit = false;
if (*input_str == '-')
{
input_str++;
*negative = true;
}
else
*negative = false;
*endptr = (char *) input_str;
while (*endptr && c_isdigit (**endptr))
{
int digit = (**endptr) - '0';
found_digit = true;
if (val || digit)
digits++;
if (digits > MAX_UNSCALED_DIGITS)
e = SSE_OK_PRECISION_LOSS;
if (digits > MAX_ACCEPTABLE_DIGITS)
return SSE_OVERFLOW;
val *= 10;
val += digit;
++(*endptr);
}
if (! found_digit
&& ! STREQ_LEN (*endptr, decimal_point, decimal_point_length))
return SSE_INVALID_NUMBER;
if (*negative)
val = -val;
if (value)
*value = val;
return e;
}
/* Read a floating-point INPUT_STR represented as "NNNN[.NNNNN]",
and return the value in a 'long double' VALUE.
ENDPTR is required (unlike strtod) and is used to store a pointer
to the character after the last character used in the conversion.
PRECISION is optional and used to indicate fractions are present.
Note locale'd grouping is not supported,
nor is skipping of white-space supported.
Returns:
SSE_OK - valid number.
SSE_OK_PRECISION_LOSS - if more than 18 digits were used.
SSE_OVERFLOW - if more than 27 digits (999Y) were used.
SSE_INVALID_NUMBER - if no digits were found. */
static enum simple_strtod_error
simple_strtod_float (const char *input_str,
char **endptr,
long double *value,
size_t *precision)
{
bool negative;
enum simple_strtod_error e = SSE_OK;
if (precision)
*precision = 0;
/* TODO: accept locale'd grouped values for the integral part. */
e = simple_strtod_int (input_str, endptr, value, &negative);
if (e != SSE_OK && e != SSE_OK_PRECISION_LOSS)
return e;
/* optional decimal point + fraction. */
if (STREQ_LEN (*endptr, decimal_point, decimal_point_length))
{
char *ptr2;
long double val_frac = 0;
bool neg_frac;
(*endptr) += decimal_point_length;
enum simple_strtod_error e2 =
simple_strtod_int (*endptr, &ptr2, &val_frac, &neg_frac);
if (e2 != SSE_OK && e2 != SSE_OK_PRECISION_LOSS)
return e2;
if (e2 == SSE_OK_PRECISION_LOSS)
e = e2; /* propagate warning. */
if (neg_frac)
return SSE_INVALID_NUMBER;
/* number of digits in the fractions. */
size_t exponent = ptr2 - *endptr;
val_frac = ((long double) val_frac) / powerld (10, exponent);
/* TODO: detect loss of precision (only really 18 digits
of precision across all digits (before and after '.')). */
if (value)
{
if (negative)
*value -= val_frac;
else
*value += val_frac;
}
if (precision)
*precision = exponent;
*endptr = ptr2;
}
return e;
}
/* Read a 'human' INPUT_STR represented as "NNNN[.NNNNN] + suffix",
and return the value in a 'long double' VALUE,
with the precision of the input returned in PRECISION.
ENDPTR is required (unlike strtod) and is used to store a pointer
to the character after the last character used in the conversion.
ALLOWED_SCALING determines the scaling supported.
TODO:
support locale'd grouping
accept scentific and hex floats (probably use strtold directly)
Returns:
SSE_OK - valid number.
SSE_OK_PRECISION_LOSS - if more than LDBL_DIG digits were used.
SSE_OVERFLOW - if more than 27 digits (999Y) were used.
SSE_INVALID_NUMBER - if no digits were found.
SSE_VALID_BUT_FORBIDDEN_SUFFIX
SSE_INVALID_SUFFIX
SSE_MISSING_I_SUFFIX */
static enum simple_strtod_error
simple_strtod_human (const char *input_str,
char **endptr, long double *value, size_t *precision,
enum scale_type allowed_scaling)
{
int power = 0;
/* 'scale_auto' is checked below. */
int scale_base = default_scale_base (allowed_scaling);
devmsg ("simple_strtod_human:\n input string: %s\n"
" locale decimal-point: %s\n"
" MAX_UNSCALED_DIGITS: %d\n",
quote_n (0, input_str),
quote_n (1, decimal_point),
MAX_UNSCALED_DIGITS);
enum simple_strtod_error e =
simple_strtod_float (input_str, endptr, value, precision);
if (e != SSE_OK && e != SSE_OK_PRECISION_LOSS)
return e;
devmsg (" parsed numeric value: %Lf\n"
" input precision = %d\n", *value, (int)*precision);
if (**endptr != '\0')
{
/* process suffix. */
/* Skip any blanks between the number and suffix. */
while (isblank (to_uchar (**endptr)))
(*endptr)++;
if (!valid_suffix (**endptr))
return SSE_INVALID_SUFFIX;
if (allowed_scaling == scale_none)
return SSE_VALID_BUT_FORBIDDEN_SUFFIX;
power = suffix_power (**endptr);
(*endptr)++; /* skip first suffix character. */
if (allowed_scaling == scale_auto && **endptr == 'i')
{
/* auto-scaling enabled, and the first suffix character
is followed by an 'i' (e.g. Ki, Mi, Gi). */
scale_base = 1024;
(*endptr)++; /* skip second ('i') suffix character. */
devmsg (" Auto-scaling, found 'i', switching to base %d\n",
scale_base);
}
*precision = 0; /* Reset, to select precision based on scale. */
}
if (allowed_scaling == scale_IEC_I)
{
if (**endptr == 'i')
(*endptr)++;
else
return SSE_MISSING_I_SUFFIX;
}
long double multiplier = powerld (scale_base, power);
devmsg (" suffix power=%d^%d = %Lf\n", scale_base, power, multiplier);
/* TODO: detect loss of precision and overflows. */
(*value) = (*value) * multiplier;
devmsg (" returning value: %Lf (%LG)\n", *value, *value);
return e;
}
static void
simple_strtod_fatal (enum simple_strtod_error err, char const *input_str)
{
char const *msgid = NULL;
switch (err)
{
case SSE_OK_PRECISION_LOSS:
case SSE_OK:
/* should never happen - this function isn't called when OK. */
abort ();
case SSE_OVERFLOW:
msgid = N_("value too large to be converted: %s");
break;
case SSE_INVALID_NUMBER:
msgid = N_("invalid number: %s");
break;
case SSE_VALID_BUT_FORBIDDEN_SUFFIX:
msgid = N_("rejecting suffix in input: %s (consider using --from)");
break;
case SSE_INVALID_SUFFIX:
msgid = N_("invalid suffix in input: %s");
break;
case SSE_MISSING_I_SUFFIX:
msgid = N_("missing 'i' suffix in input: %s (e.g Ki/Mi/Gi)");
break;
}
if (inval_style != inval_ignore)
error (conv_exit_code, 0, gettext (msgid), quote (input_str));
}
/* Convert VAL to a human format string in BUF. */
static void
double_to_human (long double val, int precision,
char *buf, size_t buf_size,
enum scale_type scale, int group, enum round_type round)
{
int num_size;
char fmt[64];
verify (sizeof (fmt) > (INT_BUFSIZE_BOUND (zero_padding_width)
+ INT_BUFSIZE_BOUND (precision)
+ 10 /* for %.Lf etc. */));
char *pfmt = fmt;
*pfmt++ = '%';
if (group)
*pfmt++ = '\'';
if (zero_padding_width)
pfmt += snprintf (pfmt, sizeof (fmt) - 2, "0%ld", zero_padding_width);
devmsg ("double_to_human:\n");
if (scale == scale_none)
{
val *= powerld (10, precision);
val = simple_round (val, round);
val /= powerld (10, precision);
devmsg ((group) ?
" no scaling, returning (grouped) value: %'.*Lf\n" :
" no scaling, returning value: %.*Lf\n", precision, val);
stpcpy (pfmt, ".*Lf");
num_size = snprintf (buf, buf_size, fmt, precision, val);
if (num_size < 0 || num_size >= (int) buf_size)
die (EXIT_FAILURE, 0,
_("failed to prepare value '%Lf' for printing"), val);
return;
}
/* Scaling requested by user. */
double scale_base = default_scale_base (scale);
/* Normalize val to scale. */
unsigned int power = 0;
val = expld (val, scale_base, &power);
devmsg (" scaled value to %Lf * %0.f ^ %u\n", val, scale_base, power);
/* Perform rounding. */
unsigned int power_adjust = 0;
if (user_precision != -1)
power_adjust = MIN (power * 3, user_precision);
else if (absld (val) < 10)
{
/* for values less than 10, we allow one decimal-point digit,
so adjust before rounding. */
power_adjust = 1;
}
val *= powerld (10, power_adjust);
val = simple_round (val, round);
val /= powerld (10, power_adjust);
/* two special cases after rounding:
1. a "999.99" can turn into 1000 - so scale down
2. a "9.99" can turn into 10 - so don't display decimal-point. */
if (absld (val) >= scale_base)
{
val /= scale_base;
power++;
}
/* should "7.0" be printed as "7" ?
if removing the ".0" is preferred, enable the fourth condition. */
int show_decimal_point = (val != 0) && (absld (val) < 10) && (power > 0);
/* && (absld (val) > simple_round_floor (val))) */
devmsg (" after rounding, value=%Lf * %0.f ^ %u\n", val, scale_base, power);
stpcpy (pfmt, ".*Lf%s");
int prec = user_precision == -1 ? show_decimal_point : user_precision;
/* buf_size - 1 used here to ensure place for possible scale_IEC_I suffix. */
num_size = snprintf (buf, buf_size - 1, fmt, prec, val,
suffix_power_char (power));
if (num_size < 0 || num_size >= (int) buf_size - 1)
die (EXIT_FAILURE, 0,
_("failed to prepare value '%Lf' for printing"), val);
if (scale == scale_IEC_I && power > 0)
strncat (buf, "i", buf_size - num_size - 1);
devmsg (" returning value: %s\n", quote (buf));
return;
}
/* Convert a string of decimal digits, N_STRING, with an optional suffix
to an integral value. Suffixes are handled as with --from=auto.
Upon successful conversion, return that value.
If it cannot be converted, give a diagnostic and exit. */
static uintmax_t
unit_to_umax (const char *n_string)
{
strtol_error s_err;
const char *c_string = n_string;
char *t_string = NULL;
size_t n_len = strlen (n_string);
char *end = NULL;
uintmax_t n;
const char *suffixes = "KMGTPEZY";
/* Adjust suffixes so K=1000, Ki=1024, KiB=invalid. */
if (n_len && ! c_isdigit (n_string[n_len - 1]))
{
t_string = xmalloc (n_len + 2);
end = t_string + n_len - 1;
memcpy (t_string, n_string, n_len);
if (*end == 'i' && 2 <= n_len && ! c_isdigit (*(end - 1)))
*end = '\0';
else
{
*++end = 'B';
*++end = '\0';
suffixes = "KMGTPEZY0";
}
c_string = t_string;
}
s_err = xstrtoumax (c_string, &end, 10, &n, suffixes);
if (s_err != LONGINT_OK || *end || n == 0)
{
free (t_string);
die (EXIT_FAILURE, 0, _("invalid unit size: %s"), quote (n_string));
}
free (t_string);
return n;
}
static void
setup_padding_buffer (size_t min_size)
{
if (padding_buffer_size > min_size)
return;
padding_buffer_size = min_size + 1;
padding_buffer = xrealloc (padding_buffer, padding_buffer_size);
}
void
usage (int status)
{
if (status != EXIT_SUCCESS)
emit_try_help ();
else
{
printf (_("\
Usage: %s [OPTION]... [NUMBER]...\n\
"), program_name);
fputs (_("\
Reformat NUMBER(s), or the numbers from standard input if none are specified.\n\
"), stdout);
emit_mandatory_arg_note ();
fputs (_("\
--debug print warnings about invalid input\n\
"), stdout);
fputs (_("\
-d, --delimiter=X use X instead of whitespace for field delimiter\n\
"), stdout);
fputs (_("\
--field=FIELDS replace the numbers in these input fields (default=1)\n\
see FIELDS below\n\
"), stdout);
fputs (_("\
--format=FORMAT use printf style floating-point FORMAT;\n\
see FORMAT below for details\n\
"), stdout);
fputs (_("\
--from=UNIT auto-scale input numbers to UNITs; default is 'none';\n\
see UNIT below\n\
"), stdout);
fputs (_("\
--from-unit=N specify the input unit size (instead of the default 1)\n\
"), stdout);
fputs (_("\
--grouping use locale-defined grouping of digits, e.g. 1,000,000\n\
(which means it has no effect in the C/POSIX locale)\n\
"), stdout);
fputs (_("\
--header[=N] print (without converting) the first N header lines;\n\
N defaults to 1 if not specified\n\
"), stdout);
fputs (_("\
--invalid=MODE failure mode for invalid numbers: MODE can be:\n\
abort (default), fail, warn, ignore\n\
"), stdout);
fputs (_("\
--padding=N pad the output to N characters; positive N will\n\
right-align; negative N will left-align;\n\
padding is ignored if the output is wider than N;\n\
the default is to automatically pad if a whitespace\n\
is found\n\
"), stdout);
fputs (_("\
--round=METHOD use METHOD for rounding when scaling; METHOD can be:\n\
up, down, from-zero (default), towards-zero, nearest\n\
"), stdout);
fputs (_("\
--suffix=SUFFIX add SUFFIX to output numbers, and accept optional\n\
SUFFIX in input numbers\n\
"), stdout);
fputs (_("\
--to=UNIT auto-scale output numbers to UNITs; see UNIT below\n\
"), stdout);
fputs (_("\
--to-unit=N the output unit size (instead of the default 1)\n\
"), stdout);
fputs (_("\
-z, --zero-terminated line delimiter is NUL, not newline\n\
"), stdout);
fputs (HELP_OPTION_DESCRIPTION, stdout);
fputs (VERSION_OPTION_DESCRIPTION, stdout);
fputs (_("\
\n\
UNIT options:\n"), stdout);
fputs (_("\
none no auto-scaling is done; suffixes will trigger an error\n\
"), stdout);
fputs (_("\
auto accept optional single/two letter suffix:\n\
1K = 1000,\n\
1Ki = 1024,\n\
1M = 1000000,\n\
1Mi = 1048576,\n"), stdout);
fputs (_("\
si accept optional single letter suffix:\n\
1K = 1000,\n\
1M = 1000000,\n\
...\n"), stdout);
fputs (_("\
iec accept optional single letter suffix:\n\
1K = 1024,\n\
1M = 1048576,\n\
...\n"), stdout);
fputs (_("\
iec-i accept optional two-letter suffix:\n\
1Ki = 1024,\n\
1Mi = 1048576,\n\
...\n"), stdout);
fputs (_("\n\
FIELDS supports cut(1) style field ranges:\n\
N N'th field, counted from 1\n\
N- from N'th field, to end of line\n\
N-M from N'th to M'th field (inclusive)\n\
-M from first to M'th field (inclusive)\n\
- all fields\n\
Multiple fields/ranges can be separated with commas\n\
"), stdout);
fputs (_("\n\
FORMAT must be suitable for printing one floating-point argument '%f'.\n\
Optional quote (%'f) will enable --grouping (if supported by current locale).\n\
Optional width value (%10f) will pad output. Optional zero (%010f) width\n\
will zero pad the number. Optional negative values (%-10f) will left align.\n\
Optional precision (%.1f) will override the input determined precision.\n\
"), stdout);
printf (_("\n\
Exit status is 0 if all input numbers were successfully converted.\n\
By default, %s will stop at the first conversion error with exit status 2.\n\
With --invalid='fail' a warning is printed for each conversion error\n\