1 package io.jawk.jrt;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 import java.math.BigDecimal;
26 import java.math.BigInteger;
27 import java.math.MathContext;
28 import java.math.RoundingMode;
29 import java.text.DecimalFormatSymbols;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.IllegalFormatException;
33 import java.util.List;
34 import java.util.Locale;
35 import java.util.concurrent.ConcurrentHashMap;
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 public final class AwkPrintf {
72
73
74 public static final String DEFAULT_CONVFMT = "%.6g";
75
76
77 private static final String CONVERSION_CHARS = "diouxXeEfFgGaAcs";
78
79
80 private static final String LENGTH_MODIFIERS = "hjlLtz";
81
82
83 private static final String NUL_STRING = Character.toString((char) 0);
84
85
86 private static final double TWO_POW_63 = 9.223372036854775808e18;
87
88
89 private static final BigInteger TWO_POW_64 = BigInteger.ONE.shiftLeft(64);
90
91
92 private static final int OPERAND_NONE = 0;
93
94
95 private static final int OPERAND_FIXED = 1;
96
97
98 private static final int OPERAND_STAR = 2;
99
100
101 private static final int OPERAND_STAR_POSITIONAL = 3;
102
103
104 private static final Flags NO_FLAGS = new Flags(false, false, false, false, false, false);
105
106
107 private static final int FORMAT_CACHE_LIMIT = 256;
108
109
110
111
112
113
114 private static final ConcurrentHashMap<String, Segment[]> FORMAT_CACHE = new ConcurrentHashMap<String, Segment[]>();
115
116
117 private static final int LOCALE_SYMBOLS_CACHE_LIMIT = 64;
118
119
120
121
122
123
124 private static final ConcurrentHashMap<Locale, LocaleSymbols> LOCALE_SYMBOLS_CACHE = new ConcurrentHashMap<Locale, LocaleSymbols>();
125
126 private AwkPrintf() {
127 throw new UnsupportedOperationException();
128 }
129
130
131
132
133
134
135
136
137
138
139
140 public static String sprintf(final String format, final Object... args) {
141 return sprintf(Locale.US, DEFAULT_CONVFMT, format, args);
142 }
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157 public static String sprintf(final Locale locale, final String convfmt, final String format, final Object... args) {
158 Locale actualLocale = locale == null ? Locale.US : locale;
159
160
161 String actualConvfmt = convfmt == null ? DEFAULT_CONVFMT : convfmt;
162 Object[] actualArgs = args == null ? new Object[0] : args;
163 return new AwkPrintfFormatter(actualLocale, actualConvfmt, format, actualArgs).format();
164 }
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182 public static String toAwkString(final Object value, final String conversionFormat, final Locale locale) {
183 if (value == null) {
184 return "";
185 }
186 if (value instanceof Long || value instanceof Integer || value instanceof Short || value instanceof Byte) {
187
188 return Long.toString(((Number) value).longValue());
189 }
190 if (!(value instanceof Number)) {
191 return value.toString();
192 }
193 return numberToAwkString(((Number) value).doubleValue(), conversionFormat, locale);
194 }
195
196 private static String numberToAwkString(final double number, final String conversionFormat, final Locale locale) {
197 if (Double.isNaN(number)) {
198 return "nan";
199 }
200 if (Double.isInfinite(number)) {
201 return number > 0 ? "inf" : "-inf";
202 }
203 if (JRT.isActuallyLong(number)) {
204 double rounded = Math.rint(number);
205 if (rounded >= -TWO_POW_63 && rounded < TWO_POW_63) {
206 return Long.toString((long) rounded);
207 }
208
209 return new BigDecimal(rounded).toBigInteger().toString();
210 }
211
212
213 String fmt = conversionFormat == null ? DEFAULT_CONVFMT : conversionFormat;
214 return sprintf(locale, DEFAULT_CONVFMT, fmt, Double.valueOf(number));
215 }
216
217
218
219
220 private static final class Flags {
221
222 private final boolean leftJustify;
223 private final boolean plusSign;
224 private final boolean spaceSign;
225 private final boolean zeroPad;
226 private final boolean alternate;
227 private final boolean grouping;
228
229 Flags(boolean leftJustify, boolean plusSign, boolean spaceSign, boolean zeroPad, boolean alternate,
230 boolean grouping) {
231 this.leftJustify = leftJustify;
232 this.plusSign = plusSign;
233 this.spaceSign = spaceSign;
234 this.zeroPad = zeroPad;
235 this.alternate = alternate;
236 this.grouping = grouping;
237 }
238
239
240
241
242
243
244
245 Flags withoutGrouping() {
246 return grouping ? new Flags(leftJustify, plusSign, spaceSign, zeroPad, alternate, false) : this;
247 }
248
249
250
251
252
253
254
255 Flags withLeftJustify() {
256 return leftJustify ? this : new Flags(true, plusSign, spaceSign, zeroPad, alternate, grouping);
257 }
258 }
259
260
261
262
263 private static final class LocaleSymbols {
264
265 private final char decimalSeparator;
266 private final char groupingSeparator;
267
268 LocaleSymbols(char decimalSeparator, char groupingSeparator) {
269 this.decimalSeparator = decimalSeparator;
270 this.groupingSeparator = groupingSeparator;
271 }
272 }
273
274
275
276
277
278
279
280
281 private static final class Segment {
282
283
284 private final String literal;
285
286
287 private final int argPosition;
288
289 private final Flags flags;
290
291
292 private final int widthKind;
293
294
295 private final int width;
296
297
298 private final int precisionKind;
299
300
301 private final int precision;
302
303
304 private final char conversion;
305
306
307
308
309
310 private final String parseError;
311
312 Segment(String literal, int argPosition, Flags flags, int widthKind, int width, int precisionKind, int precision,
313 char conversion, String parseError) {
314 this.literal = literal;
315 this.argPosition = argPosition;
316 this.flags = flags;
317 this.widthKind = widthKind;
318 this.width = width;
319 this.precisionKind = precisionKind;
320 this.precision = precision;
321 this.conversion = conversion;
322 this.parseError = parseError;
323 }
324 }
325
326
327
328
329
330 private static LocaleSymbols localeSymbolsFor(Locale locale) {
331 LocaleSymbols symbols = LOCALE_SYMBOLS_CACHE.get(locale);
332 if (symbols == null) {
333 DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(locale);
334 symbols = new LocaleSymbols(dfs.getDecimalSeparator(), dfs.getGroupingSeparator());
335 if (LOCALE_SYMBOLS_CACHE.size() >= LOCALE_SYMBOLS_CACHE_LIMIT) {
336 LOCALE_SYMBOLS_CACHE.clear();
337 }
338 LOCALE_SYMBOLS_CACHE.putIfAbsent(locale, symbols);
339 }
340 return symbols;
341 }
342
343
344
345
346
347 private static Segment[] compiledFormat(String format) {
348 Segment[] segments = FORMAT_CACHE.get(format);
349 if (segments == null) {
350 segments = compileFormat(format);
351 if (FORMAT_CACHE.size() >= FORMAT_CACHE_LIMIT) {
352
353
354
355 FORMAT_CACHE.clear();
356 }
357 Segment[] winner = FORMAT_CACHE.putIfAbsent(format, segments);
358 if (winner != null) {
359 return winner;
360 }
361 }
362 return segments;
363 }
364
365
366
367
368
369
370
371 private static Segment[] compileFormat(String format) {
372 List<Segment> segments = new ArrayList<Segment>();
373 StringBuilder literal = new StringBuilder();
374 int length = format.length();
375 int i = 0;
376 while (i < length) {
377 char c = format.charAt(i);
378 if (c != '%') {
379 literal.append(c);
380 i++;
381 continue;
382 }
383 if (i + 1 >= length) {
384
385 literal.append('%');
386 break;
387 }
388 if (format.charAt(i + 1) == '%') {
389 literal.append('%');
390 i += 2;
391 continue;
392 }
393 i = compileSpecifier(format, i, segments, literal);
394 if (i < 0) {
395
396
397 break;
398 }
399 }
400 flushLiteral(segments, literal);
401 return segments.toArray(new Segment[0]);
402 }
403
404
405
406
407
408
409
410 private static int compileSpecifier(String format, int start, List<Segment> segments, StringBuilder literal) {
411 int length = format.length();
412 int i = start + 1;
413
414
415 int argPosition = 0;
416 int digitsEnd = i;
417 while (digitsEnd < length && isAsciiDigit(format.charAt(digitsEnd))) {
418 digitsEnd++;
419 }
420 if (digitsEnd > i && digitsEnd < length && format.charAt(digitsEnd) == '$') {
421 argPosition = parseInt(format, i, digitsEnd);
422 if (argPosition <= 0) {
423 emitError(segments, literal, OPERAND_NONE, 0, "argument index with `$' must be > 0 in `" + format + "'");
424 return -1;
425 }
426 i = digitsEnd + 1;
427 }
428
429
430 boolean leftJustify = false;
431 boolean plusSign = false;
432 boolean spaceSign = false;
433 boolean zeroPad = false;
434 boolean alternate = false;
435 boolean grouping = false;
436 flagLoop: while (i < length) {
437 switch (format.charAt(i)) {
438 case '-':
439 leftJustify = true;
440 break;
441 case '+':
442 plusSign = true;
443 break;
444 case ' ':
445 spaceSign = true;
446 break;
447 case '0':
448 zeroPad = true;
449 break;
450 case '#':
451 alternate = true;
452 break;
453 case '\'':
454 grouping = true;
455 break;
456 default:
457 break flagLoop;
458 }
459 i++;
460 }
461
462
463 int widthKind = OPERAND_NONE;
464 int width = -1;
465 if (i < length && format.charAt(i) == '*') {
466 i++;
467 int starArgEnd = starPositionEnd(format, i);
468 if (starArgEnd == i && i < length && isAsciiDigit(format.charAt(i))) {
469
470
471 emitError(
472 segments,
473 literal,
474 OPERAND_NONE,
475 0,
476 "no `$' supplied for positional field width or precision in `" + format + "'");
477 return -1;
478 }
479 if (starArgEnd > i) {
480 widthKind = OPERAND_STAR_POSITIONAL;
481 width = parseInt(format, i, starArgEnd - 1);
482 i = starArgEnd;
483 } else {
484 widthKind = OPERAND_STAR;
485 }
486 } else {
487 int widthEnd = i;
488 while (widthEnd < length && isAsciiDigit(format.charAt(widthEnd))) {
489 widthEnd++;
490 }
491 if (widthEnd > i) {
492 widthKind = OPERAND_FIXED;
493 width = parseInt(format, i, widthEnd);
494 i = widthEnd;
495 }
496 }
497
498
499 int precisionKind = OPERAND_NONE;
500 int precision = -1;
501 if (i < length && format.charAt(i) == '.') {
502 i++;
503 if (i < length && format.charAt(i) == '*') {
504 i++;
505 int starArgEnd = starPositionEnd(format, i);
506 if (starArgEnd == i && i < length && isAsciiDigit(format.charAt(i))) {
507
508
509 emitError(
510 segments,
511 literal,
512 widthKind,
513 width,
514 "no `$' supplied for positional field width or precision in `" + format + "'");
515 return -1;
516 }
517 if (starArgEnd > i) {
518 precisionKind = OPERAND_STAR_POSITIONAL;
519 precision = parseInt(format, i, starArgEnd - 1);
520 i = starArgEnd;
521 } else {
522 precisionKind = OPERAND_STAR;
523 }
524 } else {
525 int precisionEnd = i;
526 while (precisionEnd < length && isAsciiDigit(format.charAt(precisionEnd))) {
527 precisionEnd++;
528 }
529 precisionKind = OPERAND_FIXED;
530 precision = precisionEnd == i ? 0 : parseInt(format, i, precisionEnd);
531 i = precisionEnd;
532 }
533 }
534
535
536
537
538 int modifierMask = 0;
539 while (i < length) {
540 int modifierIndex = LENGTH_MODIFIERS.indexOf(format.charAt(i));
541 if (modifierIndex < 0 || (modifierMask & 1 << modifierIndex) != 0) {
542 break;
543 }
544 modifierMask |= 1 << modifierIndex;
545 i++;
546 }
547
548 if (i < length && format.charAt(i) == '%') {
549
550
551
552
553
554 emitVerbatim(
555 segments,
556 literal,
557 new Segment("%", argPosition, NO_FLAGS, widthKind, width, precisionKind, precision, (char) 0, null));
558 return i + 1;
559 }
560
561 if (i >= length || CONVERSION_CHARS.indexOf(format.charAt(i)) < 0) {
562
563
564
565
566
567 int end = i < length ? i + 1 : length;
568 emitVerbatim(
569 segments,
570 literal,
571 new Segment(
572 format.substring(start, end),
573 argPosition,
574 NO_FLAGS,
575 widthKind,
576 width,
577 precisionKind,
578 precision,
579 (char) 0,
580 null));
581 return end;
582 }
583
584 char conversion = format.charAt(i);
585 i++;
586
587 flushLiteral(segments, literal);
588 segments.add(
589 new Segment(
590 null,
591 argPosition,
592 new Flags(leftJustify, plusSign, spaceSign, zeroPad, alternate, grouping),
593 widthKind,
594 width,
595 precisionKind,
596 precision,
597 conversion,
598 null));
599 return i;
600 }
601
602
603
604
605
606
607
608
609 private static void emitVerbatim(List<Segment> segments, StringBuilder literal, Segment segment) {
610 boolean sideEffectFree = segment.argPosition == 0
611 && segment.widthKind != OPERAND_STAR
612 && segment.widthKind != OPERAND_STAR_POSITIONAL
613 && segment.precisionKind != OPERAND_STAR
614 && segment.precisionKind != OPERAND_STAR_POSITIONAL;
615 if (sideEffectFree) {
616 literal.append(segment.literal);
617 return;
618 }
619 flushLiteral(segments, literal);
620 segments.add(segment);
621 }
622
623
624
625
626
627 private static void emitError(
628 List<Segment> segments,
629 StringBuilder literal,
630 int widthKind,
631 int width,
632 String message) {
633 flushLiteral(segments, literal);
634 segments.add(new Segment(null, 0, NO_FLAGS, widthKind, width, OPERAND_NONE, -1, (char) 0, message));
635 }
636
637
638 private static void flushLiteral(List<Segment> segments, StringBuilder literal) {
639 if (literal.length() > 0) {
640 segments.add(new Segment(literal.toString(), 0, NO_FLAGS, OPERAND_NONE, -1, OPERAND_NONE, -1, (char) 0, null));
641 literal.setLength(0);
642 }
643 }
644
645
646
647
648
649 private static int starPositionEnd(String format, int i) {
650 int length = format.length();
651 int digitsEnd = i;
652 while (digitsEnd < length && isAsciiDigit(format.charAt(digitsEnd))) {
653 digitsEnd++;
654 }
655 if (digitsEnd > i && digitsEnd < length && format.charAt(digitsEnd) == '$') {
656 return digitsEnd + 1;
657 }
658 return i;
659 }
660
661
662
663
664
665 private static final class AwkPrintfFormatter {
666
667 private final Locale locale;
668 private final String convfmt;
669 private final String format;
670 private final Object[] args;
671 private final StringBuilder out;
672 private final char decimalSeparator;
673 private final char groupingSeparator;
674
675
676 private int argIndex;
677
678
679 private boolean sawPositional;
680
681
682 private boolean sawSequential;
683
684 AwkPrintfFormatter(Locale locale, String convfmt, String format, Object[] args) {
685 this.locale = locale;
686 this.convfmt = convfmt;
687 this.format = format;
688 this.args = args;
689 this.out = new StringBuilder(format.length() + 16);
690 LocaleSymbols symbols = localeSymbolsFor(locale);
691 this.decimalSeparator = symbols.decimalSeparator;
692 this.groupingSeparator = symbols.groupingSeparator;
693 }
694
695 String format() {
696 for (Segment segment : compiledFormat(format)) {
697 renderSegment(segment);
698 }
699 return out.toString();
700 }
701
702
703
704
705
706
707 private void renderSegment(Segment segment) {
708 Flags flags = segment.flags;
709 int width = -1;
710 if (segment.widthKind != OPERAND_NONE) {
711 if (segment.widthKind == OPERAND_FIXED) {
712 width = segment.width;
713 } else {
714 long dynamicWidth;
715 if (segment.widthKind == OPERAND_STAR) {
716
717
718
719 recordArgumentMode(false);
720 dynamicWidth = (long) JRT.toDouble(nextArg());
721 } else {
722
723
724 dynamicWidth = segment.width == 0 ? 0 : (long) JRT.toDouble(argAt(segment.width));
725 }
726 if (dynamicWidth < 0) {
727 flags = flags.withLeftJustify();
728 dynamicWidth = -dynamicWidth;
729 }
730 width = (int) Math.min(dynamicWidth, Integer.MAX_VALUE);
731 }
732 }
733 if (segment.parseError != null) {
734 throw new AwkRuntimeException(segment.parseError);
735 }
736 int precision = -1;
737 if (segment.precisionKind != OPERAND_NONE) {
738 if (segment.precisionKind == OPERAND_FIXED) {
739 precision = segment.precision;
740 } else {
741 long dynamicPrecision;
742 if (segment.precisionKind == OPERAND_STAR) {
743
744 recordArgumentMode(false);
745 dynamicPrecision = (long) JRT.toDouble(nextArg());
746 } else {
747
748 dynamicPrecision = segment.precision == 0 ? 0 : (long) JRT.toDouble(argAt(segment.precision));
749 }
750
751 if (dynamicPrecision >= 0) {
752 precision = (int) Math.min(dynamicPrecision, Integer.MAX_VALUE);
753 }
754 }
755 }
756 if (segment.literal != null) {
757
758
759 if (segment.argPosition > 0) {
760 recordArgumentMode(true);
761 requireArgumentIndex(segment.argPosition);
762 }
763 out.append(segment.literal);
764 return;
765 }
766 recordArgumentMode(segment.argPosition > 0);
767 Object arg = segment.argPosition > 0 ? argAt(segment.argPosition) : nextArg();
768 render(segment.conversion, flags, width, precision, arg);
769 }
770
771 private Object nextArg() {
772 if (argIndex >= args.length) {
773 throw new AwkRuntimeException("not enough arguments to satisfy format string `" + format + "'");
774 }
775 return args[argIndex++];
776 }
777
778 private Object argAt(int position) {
779 requireArgumentIndex(position);
780 return args[position - 1];
781 }
782
783
784
785
786
787
788 private void requireArgumentIndex(int position) {
789 if (position <= 0) {
790 throw new AwkRuntimeException("argument index with `$' must be > 0 in `" + format + "'");
791 }
792 if (position > args.length) {
793 throw new AwkRuntimeException(
794 "argument index " + position + " greater than total number of supplied arguments in `" + format + "'");
795 }
796 }
797
798
799
800
801
802
803
804
805
806
807 private void recordArgumentMode(boolean positional) {
808 if (positional) {
809 sawPositional = true;
810 } else {
811 sawSequential = true;
812 }
813 if (sawPositional && sawSequential) {
814 throw new AwkRuntimeException("must use `count$' on all formats or none in `" + format + "'");
815 }
816 }
817
818 private void render(char conversion, Flags flags, int width, int precision, Object arg) {
819 switch (conversion) {
820 case 'c':
821 appendPadded(characterOf(arg), flags.leftJustify, false, width);
822 break;
823 case 's':
824 String s = toAwkString(arg, convfmt, locale);
825 if (precision >= 0 && s.codePointCount(0, s.length()) > precision) {
826
827
828 s = s.substring(0, s.offsetByCodePoints(0, precision));
829 }
830 appendPadded(s, flags.leftJustify, false, width);
831 break;
832 case 'd':
833 case 'i':
834 renderSignedInteger(flags, width, precision, arg);
835 break;
836 case 'u':
837 case 'o':
838 case 'x':
839 case 'X':
840 renderUnsignedInteger(conversion, flags, width, precision, arg);
841 break;
842 case 'e':
843 case 'E':
844 case 'f':
845 case 'F':
846 case 'g':
847 case 'G':
848 case 'a':
849 case 'A':
850 renderFloat(conversion, flags, width, precision, arg);
851 break;
852 default:
853
854 break;
855 }
856 }
857
858
859 private String characterOf(Object arg) {
860 if (arg == null) {
861 return NUL_STRING;
862 }
863 boolean numeric = arg instanceof Number || (arg instanceof StrNum && ((StrNum) arg).isNumber());
864 if (numeric) {
865 long code = (long) JRT.toDouble(arg);
866 StringBuilder sb = new StringBuilder(2);
867 if (code >= 0 && code <= Character.MAX_CODE_POINT) {
868 sb.appendCodePoint((int) code);
869 } else {
870 sb.append((char) code);
871 }
872 return sb.toString();
873 }
874 String s = arg.toString();
875 if (s.isEmpty()) {
876 return NUL_STRING;
877 }
878 StringBuilder sb = new StringBuilder(2);
879 sb.appendCodePoint(s.codePointAt(0));
880 return sb.toString();
881 }
882
883 private void renderSignedInteger(Flags flags, int width, int precision, Object arg) {
884 double d = JRT.toDouble(arg);
885 if (renderNonFinite('d', flags, width, d)) {
886 return;
887 }
888
889 boolean negative;
890 String magnitude;
891 if (arg instanceof Long || arg instanceof Integer || arg instanceof Short || arg instanceof Byte) {
892 long v = ((Number) arg).longValue();
893 negative = v < 0;
894 magnitude = negative ? Long.toUnsignedString(-v) : Long.toString(v);
895 } else if (d >= -TWO_POW_63 && d < TWO_POW_63) {
896 long v = (long) d;
897 negative = v < 0;
898 magnitude = negative ? Long.toUnsignedString(-v) : Long.toString(v);
899 } else {
900
901
902
903 BigInteger bi = new BigDecimal(d).toBigInteger();
904 negative = bi.signum() < 0;
905 magnitude = bi.abs().toString();
906 }
907
908 String sign = negative ? "-" : flags.plusSign ? "+" : flags.spaceSign ? " " : "";
909 appendInteger(sign, "", magnitude, flags, width, precision, isZeroMagnitude(magnitude));
910 }
911
912 private void renderUnsignedInteger(char conversion, Flags flags, int width, int precision, Object arg) {
913 double d = JRT.toDouble(arg);
914 if (renderNonFinite(conversion, flags, width, d)) {
915 return;
916 }
917
918 int radix = conversion == 'o' ? 8 : conversion == 'u' ? 10 : 16;
919 String magnitude;
920 if (arg instanceof Long || arg instanceof Integer || arg instanceof Short || arg instanceof Byte) {
921 magnitude = Long.toUnsignedString(((Number) arg).longValue(), radix);
922 } else if (d >= -TWO_POW_63 && d < TWO_POW_63) {
923 magnitude = Long.toUnsignedString((long) d, radix);
924 } else {
925
926 BigInteger bi = new BigDecimal(d).toBigInteger();
927 if (bi.signum() >= 0 && bi.compareTo(TWO_POW_64) < 0) {
928 magnitude = bi.toString(radix);
929 } else {
930
931
932
933 renderFloat('g', flags, width, precision, Double.valueOf(d));
934 return;
935 }
936 }
937 if (conversion == 'X') {
938 magnitude = magnitude.toUpperCase(Locale.ROOT);
939 }
940
941 boolean zeroValue = d == 0;
942 boolean zeroMagnitude = isZeroMagnitude(magnitude);
943 int actualPrecision = precision;
944 if (zeroMagnitude && precision == 0 && (flags.alternate || !zeroValue)) {
945
946
947
948
949 actualPrecision = 1;
950 }
951
952
953
954
955 String prefix = "";
956 if (flags.alternate && !zeroValue) {
957 if (conversion == 'x') {
958 prefix = "0x";
959 } else if (conversion == 'X') {
960 prefix = "0X";
961 } else if (conversion == 'o') {
962 prefix = "0";
963 }
964 }
965
966
967 Flags integerFlags = conversion == 'u' ? flags : flags.withoutGrouping();
968 appendInteger("", prefix, magnitude, integerFlags, width, actualPrecision, zeroMagnitude);
969 }
970
971
972
973
974
975 private void appendInteger(
976 String sign,
977 String prefix,
978 String magnitude,
979 Flags flags,
980 int width,
981 int precision,
982 boolean zeroMagnitude) {
983 String digits = magnitude;
984 if (precision == 0 && zeroMagnitude) {
985
986
987 appendPadded("", flags.leftJustify, false, width);
988 return;
989 }
990 if (precision > digits.length()) {
991 digits = zeros(precision - digits.length()) + digits;
992 }
993 if (flags.grouping) {
994 digits = groupDigits(digits);
995 }
996 String body = sign + prefix + digits;
997 if (width > body.length() && flags.zeroPad && !flags.leftJustify && precision < 0) {
998
999 out.append(sign).append(prefix);
1000 out.append(zeros(width - body.length()));
1001 out.append(digits);
1002 return;
1003 }
1004 appendPadded(body, flags.leftJustify, false, width);
1005 }
1006
1007 private void renderFloat(char conversion, Flags flags, int width, int precision, Object arg) {
1008 double d = JRT.toDouble(arg);
1009 if (renderNonFinite(conversion, flags, width, d)) {
1010 return;
1011 }
1012 String magnitude = floatBody(conversion, flags, precision, d);
1013 if (magnitude == null) {
1014 return;
1015 }
1016 boolean negative = d < 0 || (d == 0 && Double.doubleToRawLongBits(d) != 0L);
1017 String sign = negative ? "-" : flags.plusSign ? "+" : flags.spaceSign ? " " : "";
1018
1019
1020 String prefix = "";
1021 if (magnitude.startsWith("0x") || magnitude.startsWith("0X")) {
1022 prefix = magnitude.substring(0, 2);
1023 magnitude = magnitude.substring(2);
1024 }
1025 String full = sign + prefix + magnitude;
1026 if (width > full.length() && flags.zeroPad && !flags.leftJustify) {
1027 out.append(sign).append(prefix);
1028 out.append(zeros(width - full.length()));
1029 out.append(magnitude);
1030 return;
1031 }
1032 appendPadded(full, flags.leftJustify, false, width);
1033 }
1034
1035
1036
1037
1038
1039
1040 private String floatBody(char conversion, Flags flags, int precision, double d) {
1041 double abs = Math.abs(d);
1042 switch (conversion) {
1043 case 'f':
1044 case 'F': {
1045 int p = precision < 0 ? 6 : precision;
1046 String s = decimalString(roundHalfEvenToScale(abs, p));
1047 if (flags.alternate && p == 0) {
1048 s = forceDecimalSeparator(s);
1049 }
1050 if (flags.grouping) {
1051 s = groupDigits(s);
1052 }
1053 return s;
1054 }
1055 case 'e':
1056 case 'E': {
1057 int p = precision < 0 ? 6 : precision;
1058 String s = scientific(abs, p);
1059 if (flags.alternate && p == 0) {
1060 int exponentStart = s.indexOf('e');
1061 s = forceDecimalSeparator(s.substring(0, exponentStart)) + s.substring(exponentStart);
1062 }
1063 return conversion == 'E' ? s.toUpperCase(Locale.ROOT) : s;
1064 }
1065 case 'g':
1066 case 'G': {
1067 int p = precision < 0 ? 6 : precision == 0 ? 1 : precision;
1068 String s = generalFloat(abs, p, flags.alternate, flags.grouping);
1069 return conversion == 'G' ? s.toUpperCase(Locale.ROOT) : s;
1070 }
1071 case 'a':
1072 case 'A':
1073 default: {
1074
1075
1076 StringBuilder spec = new StringBuilder("%");
1077 if (precision >= 0) {
1078 spec.append('.').append(precision);
1079 }
1080 spec.append(conversion);
1081 try {
1082 String s = String.format(locale, spec.toString(), Double.valueOf(abs));
1083 return s;
1084 } catch (IllegalFormatException e) {
1085 out.append(spec);
1086 return null;
1087 }
1088 }
1089 }
1090 }
1091
1092
1093 private String scientific(double abs, int precision) {
1094 BigDecimal mantissa;
1095 int exponent;
1096 if (abs == 0) {
1097 mantissa = BigDecimal.ZERO.setScale(precision);
1098 exponent = 0;
1099 } else {
1100 BigDecimal rounded = roundHalfEvenToSignificant(abs, precision + 1);
1101 exponent = rounded.precision() - rounded.scale() - 1;
1102 mantissa = rounded.movePointLeft(exponent).setScale(precision, RoundingMode.UNNECESSARY);
1103 }
1104 return decimalString(mantissa) + "e" + (exponent < 0 ? "-" : "+") + exponentDigits(Math.abs(exponent));
1105 }
1106
1107
1108 private String generalFloat(double abs, int precision, boolean alternate, boolean grouping) {
1109 if (abs == 0) {
1110 return alternate ? forceDecimalSeparator("0") + zeros(precision - 1) : "0";
1111 }
1112 BigDecimal rounded = roundHalfEvenToSignificant(abs, precision);
1113 int exponent = rounded.precision() - rounded.scale() - 1;
1114 if (exponent >= -4 && exponent < precision) {
1115 String s = decimalString(rounded.setScale(precision - 1 - exponent, RoundingMode.UNNECESSARY));
1116 s = alternate ? forceDecimalSeparator(s) : stripTrailingFractionZeros(s);
1117
1118
1119 return grouping ? groupDigits(s) : s;
1120 }
1121 String mantissa = decimalString(
1122 rounded.movePointLeft(exponent).setScale(precision - 1, RoundingMode.UNNECESSARY));
1123 mantissa = alternate ? forceDecimalSeparator(mantissa) : stripTrailingFractionZeros(mantissa);
1124 return mantissa + "e" + (exponent < 0 ? "-" : "+") + exponentDigits(Math.abs(exponent));
1125 }
1126
1127
1128
1129
1130
1131
1132 private boolean renderNonFinite(char conversion, Flags flags, int width, double d) {
1133 if (!Double.isNaN(d) && !Double.isInfinite(d)) {
1134 return false;
1135 }
1136 String body;
1137 if (Double.isNaN(d)) {
1138 body = flags.plusSign ? "+nan" : flags.spaceSign ? " nan" : "nan";
1139 } else if (d > 0) {
1140 body = flags.plusSign ? "+inf" : flags.spaceSign ? " inf" : "inf";
1141 } else {
1142 body = "-inf";
1143 }
1144 if (isUpperCaseConversion(conversion)) {
1145 body = body.toUpperCase(Locale.ROOT);
1146 }
1147
1148 appendPadded(body, flags.leftJustify, false, width);
1149 return true;
1150 }
1151
1152
1153 private String decimalString(BigDecimal value) {
1154 String s = value.toPlainString();
1155 return decimalSeparator == '.' ? s : s.replace('.', decimalSeparator);
1156 }
1157
1158
1159 private String groupDigits(String s) {
1160 int end = s.indexOf(decimalSeparator);
1161 if (end < 0) {
1162 end = s.length();
1163 }
1164 StringBuilder sb = new StringBuilder(s.length() + 8);
1165 for (int i = 0; i < end; i++) {
1166 sb.append(s.charAt(i));
1167 int remaining = end - 1 - i;
1168 if (remaining > 0 && remaining % 3 == 0 && isAsciiDigit(s.charAt(i))) {
1169 sb.append(groupingSeparator);
1170 }
1171 }
1172 sb.append(s, end, s.length());
1173 return sb.toString();
1174 }
1175
1176
1177
1178
1179
1180
1181 private String forceDecimalSeparator(String s) {
1182 return s.indexOf(decimalSeparator) < 0 ? s + decimalSeparator : s;
1183 }
1184
1185 private String stripTrailingFractionZeros(String s) {
1186 if (s.indexOf(decimalSeparator) < 0) {
1187 return s;
1188 }
1189 int end = s.length();
1190 while (end > 0 && s.charAt(end - 1) == '0') {
1191 end--;
1192 }
1193 if (end > 0 && s.charAt(end - 1) == decimalSeparator) {
1194 end--;
1195 }
1196 return s.substring(0, end);
1197 }
1198
1199 private void appendPadded(String body, boolean leftJustify, boolean zeroPad, int width) {
1200
1201
1202 int bodyLength = body.codePointCount(0, body.length());
1203 if (width <= bodyLength) {
1204 out.append(body);
1205 return;
1206 }
1207 int padLength = width - bodyLength;
1208 if (leftJustify) {
1209 out.append(body);
1210 appendSpaces(padLength);
1211 } else if (zeroPad) {
1212 out.append(zeros(padLength)).append(body);
1213 } else {
1214 appendSpaces(padLength);
1215 out.append(body);
1216 }
1217 }
1218
1219 private void appendSpaces(int count) {
1220 out.append(repeat(' ', count));
1221 }
1222 }
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235 private static BigDecimal roundHalfEvenToScale(double abs, int scale) {
1236 BigDecimal shortest = shortestDecimal(abs);
1237 if (shortest != null && roundsLikeExact(abs, shortest, shortest.scale() - scale, -scale)) {
1238 return shortest.setScale(scale, RoundingMode.HALF_EVEN);
1239 }
1240
1241 return new BigDecimal(abs).setScale(scale, RoundingMode.HALF_EVEN);
1242 }
1243
1244
1245
1246
1247
1248
1249
1250 private static BigDecimal roundHalfEvenToSignificant(double abs, int digits) {
1251 if (digits > 0) {
1252 BigDecimal shortest = shortestDecimal(abs);
1253 if (shortest != null) {
1254
1255
1256 int unitExponent = shortest.precision() - shortest.scale() - digits;
1257 if (roundsLikeExact(abs, shortest, shortest.precision() - digits, unitExponent)) {
1258 return shortest.round(new MathContext(digits, RoundingMode.HALF_EVEN));
1259 }
1260 }
1261 }
1262
1263 return new BigDecimal(abs).round(new MathContext(digits, RoundingMode.HALF_EVEN));
1264 }
1265
1266
1267
1268
1269
1270
1271 private static BigDecimal shortestDecimal(double abs) {
1272 if (!(abs >= Double.MIN_NORMAL) || abs > Double.MAX_VALUE) {
1273 return null;
1274 }
1275 return new BigDecimal(Double.toString(abs));
1276 }
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300 private static boolean roundsLikeExact(double abs, BigDecimal shortest, int remainderDigits, int unitExponent) {
1301 if (unitExponent < -307 || unitExponent > 308) {
1302
1303 return false;
1304 }
1305 if (Math.ulp(abs) * 100.0 >= Math.pow(10.0, unitExponent)) {
1306 return false;
1307 }
1308 if (remainderDigits <= 0) {
1309
1310
1311 return true;
1312 }
1313 String digits = shortest.unscaledValue().toString();
1314 if (remainderDigits > digits.length()) {
1315
1316
1317 return true;
1318 }
1319
1320
1321
1322
1323 char first = digits.charAt(digits.length() - remainderDigits);
1324 return first != '4' && first != '5';
1325 }
1326
1327
1328 private static String exponentDigits(int exponent) {
1329 String digits = Integer.toString(exponent);
1330 return digits.length() < 2 ? "0" + digits : digits;
1331 }
1332
1333 private static boolean isUpperCaseConversion(char conversion) {
1334 return conversion == 'X' || conversion == 'E' || conversion == 'F' || conversion == 'G' || conversion == 'A';
1335 }
1336
1337 private static boolean isZeroMagnitude(String magnitude) {
1338 for (int i = 0; i < magnitude.length(); i++) {
1339 if (magnitude.charAt(i) != '0') {
1340 return false;
1341 }
1342 }
1343 return true;
1344 }
1345
1346 private static boolean isAsciiDigit(char c) {
1347 return c >= '0' && c <= '9';
1348 }
1349
1350
1351
1352
1353
1354
1355 private static int parseInt(String s, int from, int to) {
1356 try {
1357 return Integer.parseInt(s.substring(from, to));
1358 } catch (NumberFormatException e) {
1359 return Integer.MAX_VALUE;
1360 }
1361 }
1362
1363 private static String zeros(int count) {
1364 return repeat('0', count);
1365 }
1366
1367 private static String repeat(char c, int count) {
1368 if (count <= 0) {
1369 return "";
1370 }
1371 char[] chars = new char[count];
1372 Arrays.fill(chars, c);
1373 return new String(chars);
1374 }
1375 }