summaryrefslogtreecommitdiffstats
path: root/luni/src/main/java/java/util/Formatter.java
blob: 021da08a35b9f3c3018e63101ca16d9187eedf31 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
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
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
/* Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package java.util;

import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.Flushable;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.nio.charset.Charset;
import libcore.icu.LocaleData;
import libcore.icu.NativeDecimalFormat;
import libcore.io.IoUtils;

/**
 * Formats arguments according to a format string (like {@code printf} in C).
 * <p>
 * It's relatively rare to use a {@code Formatter} directly. A variety of classes offer convenience
 * methods for accessing formatter functionality.
 * Of these, {@link String#format} is generally the most useful.
 * {@link java.io.PrintStream} and {@link java.io.PrintWriter} both offer
 * {@code format} and {@code printf} methods.
 * <p>
 * <i>Format strings</i> consist of plain text interspersed with format specifiers, such
 * as {@code "name: %s weight: %03dkg\n"}. Being a Java string, the usual Java string literal
 * backslash escapes are of course available.
 * <p>
 * <i>Format specifiers</i> (such as {@code "%s"} or {@code "%03d"} in the example) start with a
 * {@code %} and describe how to format their corresponding argument. It includes an optional
 * argument index, optional flags, an optional width, an optional precision, and a mandatory
 * conversion type.
 * In the example, {@code "%s"} has no flags, no width, and no precision, while
 * {@code "%03d"} has the flag {@code 0}, the width 3, and no precision.
 * <p>
 * Not all combinations of argument index, flags, width, precision, and conversion type
 * are valid.
 * <p>
 * <i>Argument index</i>. Normally, each format specifier consumes the next argument to
 * {@code format}.
 * For convenient localization, it's possible to reorder arguments so that they appear in a
 * different order in the output than the order in which they were supplied.
 * For example, {@code "%4$s"} formats the fourth argument ({@code 4$}) as a string ({@code s}).
 * It's also possible to reuse an argument with {@code <}. For example,
 * {@code format("%o %&lt;d %&lt;x", 64)} results in {@code "100 64 40"}.
 * <p>
 * <i>Flags</i>. The available flags are:
 * <p>
 * <table BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
 * <tr BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=4> <B>Flags</B> </TD> </tr>
 * <tr>
 * <td width="5%">{@code ,}</td>
 * <td width="25%">Use grouping separators for large numbers. (Decimal only.)</td>
 * <td width="30%">{@code format("%,d", 1024);}</td>
 * <td width="30%">{@code 1,234}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code +}</td>
 * <td width="25%">Always show sign. (Decimal only.)</td>
 * <td width="30%">{@code format("%+d, %+4d", 5, 5);}</td>
 * <td width="30%"><pre>+5,   +5</pre></td>
 * </tr>
 * <tr>
 * <td width="5%">{@code  }</td>
 * <td width="25%">A space indicates that non-negative numbers
 * should have a leading space. (Decimal only.)</td>
 * <td width="30%">{@code format("x% d% 5d", 4, 4);}</td>
 * <td width="30%"><pre>x 4    4</pre></td>
 * </tr>
 * <tr>
 * <td width="5%">{@code (}</td>
 * <td width="25%">Put parentheses around negative numbers. (Decimal only.)</td>
 * <td width="30%">{@code format("%(d, %(d, %(6d", 12, -12, -12);}</td>
 * <td width="30%"><pre>12, (12),   (12)</pre></td>
 * </tr>
 * <tr>
 * <td width="5%">{@code -}</td>
 * <td width="25%">Left-justify. (Requires width.)</td>
 * <td width="30%">{@code format("%-6dx", 5);}<br/>{@code format("%-3C, %3C", 'd', 0x65);}</td>
 * <td width="30%"><pre>5      x</pre><br/><pre>D  ,   E</pre></td>
 * </tr>
 * <tr>
 * <td width="5%">{@code 0}</td>
 * <td width="25%">Pad the number with leading zeros. (Requires width.)</td>
 * <td width="30%">{@code format("%07d, %03d", 4, 5555);}</td>
 * <td width="30%">{@code 0000004, 5555}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code #}</td>
 * <td width="25%">Alternate form. (Octal and hex only.) </td>
 * <td width="30%">{@code format("%o %#o", 010, 010);}<br/>{@code format("%x %#x", 0x12, 0x12);}</td>
 * <td width="30%">{@code 10 010}<br/>{@code 12 0x12}</td>
 * </tr>
 * </table>
 * <p>
 * <i>Width</i>. The width is a decimal integer specifying the minimum number of characters to be
 * used to represent the argument. If the result would otherwise be shorter than the width, padding
 * will be added (the exact details of which depend on the flags). Note that you can't use width to
 * truncate a field, only to make it wider: see precision for control over the maximum width.
 * <p>
 * <i>Precision</i>. The precision is a {@code .} followed by a decimal integer, giving the minimum
 * number of digits for {@code d}, {@code o}, {@code x}, or {@code X}; the minimum number of digits
 * after the decimal point for {@code a}, {@code A}, {@code e}, {@code E}, {@code f}, or {@code F};
 * the maximum number of significant digits for {@code g} or {@code G}; or the maximum number of
 * characters for {@code s} or {@code S}.
 * <p>
 * <i>Conversion type</i>. One or two characters describing how to interpret the argument. Most
 * conversions are a single character, but date/time conversions all start with {@code t} and
 * have a single extra character describing the desired output.
 * <p>
 * Many conversion types have a corresponding uppercase variant that converts its result to
 * uppercase using the rules of the relevant locale (either the default or the locale set for
 * this formatter).
 * <p>
 * This table shows the available single-character (non-date/time) conversion types:
 * <table BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
 * <tr BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
 * <TD COLSPAN=4>
 * <B>String conversions</B>
 * <br>
 * All types are acceptable arguments. Values of type {@link Formattable} have their
 * {@code formatTo} method invoked; all other types use {@code toString}.
 * </TD>
 * </tr>
 * <tr>
 * <td width="5%">{@code s}</td>
 * <td width="25%">String.</td>
 * <td width="30%">{@code format("%s %s", "hello", "Hello");}</td>
 * <td width="30%">{@code hello Hello}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code S}</td>
 * <td width="25%">Uppercase string.</td>
 * <td width="30%">{@code format("%S %S", "hello", "Hello");}</td>
 * <td width="30%">{@code HELLO HELLO}</td>
 * </tr>
 * <tr BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
 * <TD COLSPAN=4>
 * <B>Character conversions</B>
 * <br>
 * Byte, Character, Short, and Integer (and primitives that box to those types) are all acceptable
 * as character arguments. Any other type is an error.
 * </TD>
 * </tr>
 * <tr>
 * <td width="5%">{@code c}</td>
 * <td width="25%">Character.</td>
 * <td width="30%">{@code format("%c %c", 'd', 'E');}</td>
 * <td width="30%">{@code d E}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code C}</td>
 * <td width="25%">Uppercase character.</td>
 * <td width="30%">{@code format("%C %C", 'd', 'E');}</td>
 * <td width="30%">{@code D E}</td>
 * </tr>
 * <tr BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
 * <TD COLSPAN=4>
 * <B>Integer conversions</B>
 * <br>
 * Byte, Short, Integer, Long, and BigInteger (and primitives that box to those types) are all
 * acceptable as integer arguments. Any other type is an error.
 * </TD>
 * </tr>
 * <tr>
 * <td width="5%">{@code d}</td>
 * <td width="25%">Decimal.</td>
 * <td width="30%">{@code format("%d", 26);}</td>
 * <td width="30%">{@code 26}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code o}</td>
 * <td width="25%">Octal.</td>
 * <td width="30%">{@code format("%o", 032);}</td>
 * <td width="30%">{@code 32}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code x}, {@code X}</td>
 * <td width="25%">Hexadecimal.</td>
 * <td width="30%">{@code format("%x %X", 0x1a, 0x1a);}</td>
 * <td width="30%">{@code 1a 1A}</td>
 * </tr>
 * <tr BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
 * <TD COLSPAN=4><B>Floating-point conversions</B>
 * <br>
 * Float, Double, and BigDecimal (and primitives that box to those types) are all acceptable as
 * floating-point arguments. Any other type is an error.
 * </TD>
 * </tr>
 * <tr>
 * <td width="5%">{@code f}</td>
 * <td width="25%">Decimal floating point.</td>
 * <td width="30%"><pre>
format("%f", 123.456f);
format("%.1f", 123.456f);
format("%1.5f", 123.456f);
format("%10f", 123.456f);
format("%6.0f", 123.456f);</td>
 * <td width="30%" valign="top"><pre>
123.456001
123.5
123.45600
123.456001
&nbsp;&nbsp;&nbsp;123</pre></td>
 * </tr>
 * <tr>
 * <td width="5%">{@code e}, {@code E}</td>
 * <td width="25%">Engineering/exponential floating point.</td>
 * <td width="30%"><pre>
format("%e", 123.456f);
format("%.1e", 123.456f);
format("%1.5E", 123.456f);
format("%10E", 123.456f);
format("%6.0E", 123.456f);</td>
 * <td width="30%" valign="top"><pre>
1.234560e+02
1.2e+02
1.23456E+02
1.234560E+02
&nbsp;1E+02</pre></td>
 * </tr>
 * <tr>
 * <td width="5%" valign="top">{@code g}, {@code G}</td>
 * <td width="25%" valign="top">Decimal or engineering, depending on the magnitude of the value.</td>
 * <td width="30%" valign="top">{@code format("%g %g", 0.123, 0.0000123);}</td>
 * <td width="30%" valign="top">{@code 0.123000 1.23000e-05}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code a}, {@code A}</td>
 * <td width="25%">Hexadecimal floating point.</td>
 * <td width="30%">{@code format("%a", 123.456f);}</td>
 * <td width="30%">{@code 0x1.edd2f2p6}</td>
 * </tr>
 * <tr BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
 * <TD COLSPAN=4>
 * <B>Boolean conversion</B>
 * <br>
 * Accepts Boolean values. {@code null} is considered false, and instances of all other
 * types are considered true.
 * </TD>
 * </tr>
 * <tr>
 * <td width="5%">{@code b}, {@code B}</td>
 * <td width="25%">Boolean.</td>
 * <td width="30%">{@code format("%b %b", true, false);}<br>{@code format("%B %B", true, false);}<br>{@code format("%b", null);}<br>{@code format("%b", "hello");}</td>
 * <td width="30%">{@code true false}<br>{@code TRUE FALSE}<br>{@code false}<br>{@code true}</td>
 * </tr>
 * <tr BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
 * <TD COLSPAN=4>
 * <B>Hash code conversion</B>
 * <br>
 * Invokes {@code hashCode} on its argument, which may be of any type.
 * </TD>
 * </tr>
 * <tr>
 * <td width="5%">{@code h}, {@code H}</td>
 * <td width="25%">Hexadecimal hash code.</td>
 * <td width="30%">{@code format("%h", this);}<br>{@code format("%H", this);}<br>{@code format("%h", null);}</td>
 * <td width="30%">{@code 190d11}<br>{@code 190D11}<br>{@code null}</td>
 * </tr>
 * <tr BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
 * <TD COLSPAN=4>
 * <B>Zero-argument conversions</B></TD>
 * </tr>
 * <tr>
 * <td width="5%">{@code %}</td>
 * <td width="25%">A literal % character.</td>
 * <td width="30%">{@code format("%d%%", 50);}</td>
 * <td width="30%">{@code 50%}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code n}</td>
 * <td width="25%">Newline. (The value of the "line.separator" system property}.)</td>
 * <td width="30%">{@code format("first%nsecond");}</td>
 * <td width="30%">{@code first\nsecond}</td>
 * </tr>
 * </table>
 * <p>
 * It's also possible to format dates and times with {@code Formatter}, though you should seriously
 * consider using {@link java.text.SimpleDateFormat} via the factory methods in
 * {@link java.text.DateFormat} instead.
 * The facilities offered by {@code Formatter} are low-level and place the burden of localization
 * on the developer. Using {@link java.text.DateFormat#getDateInstance},
 * {@link java.text.DateFormat#getTimeInstance}, and
 * {@link java.text.DateFormat#getDateTimeInstance} is preferable for dates and times that will be
 * presented to a human. Those methods will select the best format strings for the user's locale.
 * <p>
 * The best non-localized form is <a href="http://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a>,
 * which you can get with {@code "%tF"} (2010-01-22), {@code "%tF %tR"} (2010-01-22 13:39),
 * {@code "%tF %tT"} (2010-01-22 13:39:15), or {@code "%tF %tT%z"} (2010-01-22 13:39:15-0800).
 * <p>
 * As with the other conversions, date/time conversion has an uppercase format. Replacing
 * {@code %t} with {@code %T} will uppercase the field according to the rules of the formatter's
 * locale.
 * <p>
 * This table shows the date/time conversions:
 * <table BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
 * <tr BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
 * <TD COLSPAN=4><B>Date/time conversions</B>
 * <br>
 * Calendar, Date, and Long (representing milliseconds past the epoch) are all acceptable
 * as date/time arguments. Any other type is an error. The epoch is 1970-01-01 00:00:00 UTC.
 * </TD>
 * </tr>
 * <tr>
 * <td width="5%">{@code ta}</td>
 * <td width="25%">Localized weekday name (abbreviated).</td>
 * <td width="30%">{@code format("%ta", cal, cal);}</td>
 * <td width="30%">{@code Tue}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code tA}</td>
 * <td width="25%">Localized weekday name (full).</td>
 * <td width="30%">{@code format("%tA", cal, cal);}</td>
 * <td width="30%">{@code Tuesday}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code tb}</td>
 * <td width="25%">Localized month name (abbreviated).</td>
 * <td width="30%">{@code format("%tb", cal);}</td>
 * <td width="30%">{@code Apr}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code tB}</td>
 * <td width="25%">Localized month name (full).</td>
 * <td width="30%">{@code format("%tB", cal);}</td>
 * <td width="30%">{@code April}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code tc}</td>
 * <td width="25%">Locale-preferred date and time representation. (See {@link java.text.DateFormat} for more variations.)</td>
 * <td width="30%">{@code format("%tc", cal);}</td>
 * <td width="30%">{@code Tue Apr 01 16:19:17 CEST 2008}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code tC}</td>
 * <td width="25%">2-digit century.</td>
 * <td width="30%">{@code format("%tC", cal);}</td>
 * <td width="30%">{@code 20}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code td}</td>
 * <td width="25%">2-digit day of month (01-31).</td>
 * <td width="30%">{@code format("%td", cal);}</td>
 * <td width="30%">{@code 01}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code tD}</td>
 * <td width="25%">Ambiguous US date format (MM/DD/YY). Do not use.</td>
 * <td width="30%">{@code format("%tD", cal);}</td>
 * <td width="30%">{@code 04/01/08}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code te}</td>
 * <td width="25%">Day of month (1-31).</td>
 * <td width="30%">{@code format("%te", cal);}</td>
 * <td width="30%">{@code 1}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code tF}</td>
 * <td width="25%">Full date in ISO 8601 format (YYYY-MM-DD).</td>
 * <td width="30%">{@code format("%tF", cal);}</td>
 * <td width="30%">{@code 2008-04-01}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code th}</td>
 * <td width="25%">Synonym for {@code %tb}.</td>
 * <td width="30%"></td>
 * <td width="30%"></td>
 * </tr>
 * <tr>
 * <td width="5%">{@code tH}</td>
 * <td width="25%">24-hour hour of day (00-23).</td>
 * <td width="30%">{@code format("%tH", cal);}</td>
 * <td width="30%">{@code 16}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code tI}</td>
 * <td width="25%">12-hour hour of day (01-12).</td>
 * <td width="30%">{@code format("%tH", cal);}</td>
 * <td width="30%">{@code 04}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code tj}</td>
 * <td width="25%">3-digit day of year (001-366).</td>
 * <td width="30%">{@code format("%tj", cal);}</td>
 * <td width="30%">{@code 092}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code tk}</td>
 * <td width="25%">24-hour hour of day (0-23).</td>
 * <td width="30%">{@code format("%tH", cal);}</td>
 * <td width="30%">{@code 16}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code tl}</td>
 * <td width="25%">12-hour hour of day (1-12).</td>
 * <td width="30%">{@code format("%tH", cal);}</td>
 * <td width="30%">{@code 4}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code tL}</td>
 * <td width="25%">Milliseconds.</td>
 * <td width="30%">{@code format("%tL", cal);}</td>
 * <td width="30%">{@code 359}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code tm}</td>
 * <td width="25%">2-digit month of year (01-12).</td>
 * <td width="30%">{@code format("%tm", cal);}</td>
 * <td width="30%">{@code 04}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code tM}</td>
 * <td width="25%">2-digit minute.</td>
 * <td width="30%">{@code format("%tM", cal);}</td>
 * <td width="30%">{@code 08}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code tN}</td>
 * <td width="25%">Nanoseconds.</td>
 * <td width="30%">{@code format("%tN", cal);}</td>
 * <td width="30%">{@code 359000000}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code tp}</td>
 * <td width="25%">a.m. or p.m.</td>
 * <td width="30%">{@code format("%tp %Tp", cal, cal);}</td>
 * <td width="30%">{@code pm PM}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code tQ}</td>
 * <td width="25%">Milliseconds since the epoch.</td>
 * <td width="30%">{@code format("%tQ", cal);}</td>
 * <td width="30%">{@code 1207059412656}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code tr}</td>
 * <td width="25%">Full 12-hour time ({@code %tI:%tM:%tS %Tp}).</td>
 * <td width="30%">{@code format("%tr", cal);}</td>
 * <td width="30%">{@code 04:15:32 PM}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code tR}</td>
 * <td width="25%">Short 24-hour time ({@code %tH:%tM}).</td>
 * <td width="30%">{@code format("%tR", cal);}</td>
 * <td width="30%">{@code 16:15}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code ts}</td>
 * <td width="25%">Seconds since the epoch.</td>
 * <td width="30%">{@code format("%ts", cal);}</td>
 * <td width="30%">{@code 1207059412}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code tS}</td>
 * <td width="25%">2-digit seconds (00-60).</td>
 * <td width="30%">{@code format("%tS", cal);}</td>
 * <td width="30%">{@code 17}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code tT}</td>
 * <td width="25%">Full 24-hour time ({@code %tH:%tM:%tS}).</td>
 * <td width="30%">{@code format("%tT", cal);}</td>
 * <td width="30%">{@code 16:15:32}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code ty}</td>
 * <td width="25%">2-digit year (00-99).</td>
 * <td width="30%">{@code format("%ty", cal);}</td>
 * <td width="30%">{@code 08}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code tY}</td>
 * <td width="25%">4-digit year.</td>
 * <td width="30%">{@code format("%tY", cal);}</td>
 * <td width="30%">{@code 2008}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code tz}</td>
 * <td width="25%">Time zone GMT offset.</td>
 * <td width="30%">{@code format("%tz", cal);}</td>
 * <td width="30%">{@code +0100}</td>
 * </tr>
 * <tr>
 * <td width="5%">{@code tZ}</td>
 * <td width="25%">Localized time zone abbreviation.</td>
 * <td width="30%">{@code format("%tZ", cal);}</td>
 * <td width="30%">{@code CEST}</td>
 * </tr>
 * </table>
 * <p><i>Number localization</i>. Some conversions use localized decimal digits rather than the
 * usual ASCII digits. So formatting {@code 123} with {@code %d} will give 123 in English locales
 * but &#x0661;&#x0662;&#x0663; in appropriate Arabic locales, for example. This number localization
 * occurs for the decimal integer conversion {@code %d}, the floating point conversions {@code %e},
 * {@code %f}, and {@code %g}, and all date/time {@code %t} or {@code %T} conversions, but no other
 * conversions.
 * <p><i>Thread safety</i>. Formatter is not thread-safe.
 *
 * @since 1.5
 * @see java.text.DateFormat
 * @see Formattable
 * @see java.text.SimpleDateFormat
 */
public final class Formatter implements Closeable, Flushable {
    private static final char[] ZEROS = new char[] { '0', '0', '0', '0', '0', '0', '0', '0', '0' };

    /**
     * The enumeration giving the available styles for formatting very large
     * decimal numbers.
     */
    public enum BigDecimalLayoutForm {
        /**
         * Use scientific style for BigDecimals.
         */
        SCIENTIFIC,
        /**
         * Use normal decimal/float style for BigDecimals.
         */
        DECIMAL_FLOAT
    }

    // User-settable parameters.
    private Appendable out;
    private Locale locale;

    // Implementation details.
    private Object arg;
    private boolean closed = false;
    private FormatToken formatToken;
    private IOException lastIOException;
    private LocaleData localeData;

    private static class CachedDecimalFormat {
        public NativeDecimalFormat decimalFormat;
        public LocaleData currentLocaleData;
        public String currentPattern;

        public CachedDecimalFormat() {
        }

        public NativeDecimalFormat update(LocaleData localeData, String pattern) {
            if (decimalFormat == null) {
                currentPattern = pattern;
                currentLocaleData = localeData;
                decimalFormat = new NativeDecimalFormat(currentPattern, currentLocaleData);
            }
            if (!pattern.equals(currentPattern)) {
                decimalFormat.applyPattern(pattern);
                currentPattern = pattern;
            }
            if (localeData != currentLocaleData) {
                decimalFormat.setDecimalFormatSymbols(localeData);
                currentLocaleData = localeData;
            }
            return decimalFormat;
        }
    }

    private static final ThreadLocal<CachedDecimalFormat> cachedDecimalFormat = new ThreadLocal<CachedDecimalFormat>() {
        @Override protected CachedDecimalFormat initialValue() {
            return new CachedDecimalFormat();
        }
    };

    /**
     * Creates a native peer if we don't already have one, or reconfigures an existing one.
     * This means we get to reuse the peer in cases like "x=%.2f y=%.2f".
     */
    private NativeDecimalFormat getDecimalFormat(String pattern) {
        return cachedDecimalFormat.get().update(localeData, pattern);
    }

    /**
     * Constructs a {@code Formatter}.
     *
     * <p>The output is written to a {@code StringBuilder} which can be acquired by invoking
     * {@link #out()} and whose content can be obtained by calling {@code toString}.
     *
     * <p>The {@code Locale} used is the user's default locale.
     * See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>".
     */
    public Formatter() {
        this(new StringBuilder(), Locale.getDefault());
    }

    /**
     * Constructs a {@code Formatter} whose output will be written to the
     * specified {@code Appendable}.
     *
     * <p>The {@code Locale} used is the user's default locale.
     * See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>".
     *
     * @param a
     *            the output destination of the {@code Formatter}. If {@code a} is {@code null},
     *            then a {@code StringBuilder} will be used.
     */
    public Formatter(Appendable a) {
        this(a, Locale.getDefault());
    }

    /**
     * Constructs a {@code Formatter} with the specified {@code Locale}.
     *
     * <p>The output is written to a {@code StringBuilder} which can be acquired by invoking
     * {@link #out()} and whose content can be obtained by calling {@code toString}.
     *
     * @param l
     *            the {@code Locale} of the {@code Formatter}. If {@code l} is {@code null},
     *            then no localization will be used.
     */
    public Formatter(Locale l) {
        this(new StringBuilder(), l);
    }

    /**
     * Constructs a {@code Formatter} with the specified {@code Locale}
     * and whose output will be written to the
     * specified {@code Appendable}.
     *
     * @param a
     *            the output destination of the {@code Formatter}. If {@code a} is {@code null},
     *            then a {@code StringBuilder} will be used.
     * @param l
     *            the {@code Locale} of the {@code Formatter}. If {@code l} is {@code null},
     *            then no localization will be used.
     */
    public Formatter(Appendable a, Locale l) {
        if (a == null) {
            out = new StringBuilder();
        } else {
            out = a;
        }
        locale = l;
    }

    /**
     * Constructs a {@code Formatter} whose output is written to the specified file.
     *
     * <p>The charset of the {@code Formatter} is the default charset.
     *
     * <p>The {@code Locale} used is the user's default locale.
     * See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>".
     *
     * @param fileName
     *            the filename of the file that is used as the output
     *            destination for the {@code Formatter}. The file will be truncated to
     *            zero size if the file exists, or else a new file will be
     *            created. The output of the {@code Formatter} is buffered.
     * @throws FileNotFoundException
     *             if the filename does not denote a normal and writable file,
     *             or if a new file cannot be created, or if any error arises when
     *             opening or creating the file.
     */
    public Formatter(String fileName) throws FileNotFoundException {
        this(new File(fileName));

    }

    /**
     * Constructs a {@code Formatter} whose output is written to the specified file.
     *
     * <p>The {@code Locale} used is the user's default locale.
     * See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>".
     *
     * @param fileName
     *            the filename of the file that is used as the output
     *            destination for the {@code Formatter}. The file will be truncated to
     *            zero size if the file exists, or else a new file will be
     *            created. The output of the {@code Formatter} is buffered.
     * @param csn
     *            the name of the charset for the {@code Formatter}.
     * @throws FileNotFoundException
     *             if the filename does not denote a normal and writable file,
     *             or if a new file cannot be created, or if any error arises when
     *             opening or creating the file.
     * @throws UnsupportedEncodingException
     *             if the charset with the specified name is not supported.
     */
    public Formatter(String fileName, String csn) throws FileNotFoundException,
            UnsupportedEncodingException {
        this(new File(fileName), csn);
    }

    /**
     * Constructs a {@code Formatter} with the given {@code Locale} and charset,
     * and whose output is written to the specified file.
     *
     * @param fileName
     *            the filename of the file that is used as the output
     *            destination for the {@code Formatter}. The file will be truncated to
     *            zero size if the file exists, or else a new file will be
     *            created. The output of the {@code Formatter} is buffered.
     * @param csn
     *            the name of the charset for the {@code Formatter}.
     * @param l
     *            the {@code Locale} of the {@code Formatter}. If {@code l} is {@code null},
     *            then no localization will be used.
     * @throws FileNotFoundException
     *             if the filename does not denote a normal and writable file,
     *             or if a new file cannot be created, or if any error arises when
     *             opening or creating the file.
     * @throws UnsupportedEncodingException
     *             if the charset with the specified name is not supported.
     */
    public Formatter(String fileName, String csn, Locale l)
            throws FileNotFoundException, UnsupportedEncodingException {

        this(new File(fileName), csn, l);
    }

    /**
     * Constructs a {@code Formatter} whose output is written to the specified {@code File}.
     *
     * The charset of the {@code Formatter} is the default charset.
     *
     * <p>The {@code Locale} used is the user's default locale.
     * See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>".
     *
     * @param file
     *            the {@code File} that is used as the output destination for the
     *            {@code Formatter}. The {@code File} will be truncated to zero size if the {@code File}
     *            exists, or else a new {@code File} will be created. The output of the
     *            {@code Formatter} is buffered.
     * @throws FileNotFoundException
     *             if the {@code File} is not a normal and writable {@code File}, or if a
     *             new {@code File} cannot be created, or if any error rises when opening or
     *             creating the {@code File}.
     */
    public Formatter(File file) throws FileNotFoundException {
        this(new FileOutputStream(file));
    }

    /**
     * Constructs a {@code Formatter} with the given charset,
     * and whose output is written to the specified {@code File}.
     *
     * <p>The {@code Locale} used is the user's default locale.
     * See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>".
     *
     * @param file
     *            the {@code File} that is used as the output destination for the
     *            {@code Formatter}. The {@code File} will be truncated to zero size if the {@code File}
     *            exists, or else a new {@code File} will be created. The output of the
     *            {@code Formatter} is buffered.
     * @param csn
     *            the name of the charset for the {@code Formatter}.
     * @throws FileNotFoundException
     *             if the {@code File} is not a normal and writable {@code File}, or if a
     *             new {@code File} cannot be created, or if any error rises when opening or
     *             creating the {@code File}.
     * @throws UnsupportedEncodingException
     *             if the charset with the specified name is not supported.
     */
    public Formatter(File file, String csn) throws FileNotFoundException,
            UnsupportedEncodingException {
        this(file, csn, Locale.getDefault());
    }

    /**
     * Constructs a {@code Formatter} with the given {@code Locale} and charset,
     * and whose output is written to the specified {@code File}.
     *
     * @param file
     *            the {@code File} that is used as the output destination for the
     *            {@code Formatter}. The {@code File} will be truncated to zero size if the {@code File}
     *            exists, or else a new {@code File} will be created. The output of the
     *            {@code Formatter} is buffered.
     * @param csn
     *            the name of the charset for the {@code Formatter}.
     * @param l
     *            the {@code Locale} of the {@code Formatter}. If {@code l} is {@code null},
     *            then no localization will be used.
     * @throws FileNotFoundException
     *             if the {@code File} is not a normal and writable {@code File}, or if a
     *             new {@code File} cannot be created, or if any error rises when opening or
     *             creating the {@code File}.
     * @throws UnsupportedEncodingException
     *             if the charset with the specified name is not supported.
     */
    public Formatter(File file, String csn, Locale l)
            throws FileNotFoundException, UnsupportedEncodingException {
        FileOutputStream fout = null;
        try {
            fout = new FileOutputStream(file);
            out = new BufferedWriter(new OutputStreamWriter(fout, csn));
        } catch (RuntimeException e) {
            IoUtils.closeQuietly(fout);
            throw e;
        } catch (UnsupportedEncodingException e) {
            IoUtils.closeQuietly(fout);
            throw e;
        }

        locale = l;
    }

    /**
     * Constructs a {@code Formatter} whose output is written to the specified {@code OutputStream}.
     *
     * <p>The charset of the {@code Formatter} is the default charset.
     *
     * <p>The {@code Locale} used is the user's default locale.
     * See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>".
     *
     * @param os
     *            the stream to be used as the destination of the {@code Formatter}.
     */
    public Formatter(OutputStream os) {
        out = new BufferedWriter(new OutputStreamWriter(os, Charset.defaultCharset()));
        locale = Locale.getDefault();
    }

    /**
     * Constructs a {@code Formatter} with the given charset,
     * and whose output is written to the specified {@code OutputStream}.
     *
     * <p>The {@code Locale} used is the user's default locale.
     * See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>".
     *
     * @param os
     *            the stream to be used as the destination of the {@code Formatter}.
     * @param csn
     *            the name of the charset for the {@code Formatter}.
     * @throws UnsupportedEncodingException
     *             if the charset with the specified name is not supported.
     */
    public Formatter(OutputStream os, String csn) throws UnsupportedEncodingException {
        this(os, csn, Locale.getDefault());
    }

    /**
     * Constructs a {@code Formatter} with the given {@code Locale} and charset,
     * and whose output is written to the specified {@code OutputStream}.
     *
     * @param os
     *            the stream to be used as the destination of the {@code Formatter}.
     * @param csn
     *            the name of the charset for the {@code Formatter}.
     * @param l
     *            the {@code Locale} of the {@code Formatter}. If {@code l} is {@code null},
     *            then no localization will be used.
     * @throws UnsupportedEncodingException
     *             if the charset with the specified name is not supported.
     */
    public Formatter(OutputStream os, String csn, Locale l) throws UnsupportedEncodingException {
        out = new BufferedWriter(new OutputStreamWriter(os, csn));
        locale = l;
    }

    /**
     * Constructs a {@code Formatter} whose output is written to the specified {@code PrintStream}.
     *
     * <p>The charset of the {@code Formatter} is the default charset.
     *
     * <p>The {@code Locale} used is the user's default locale.
     * See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>".
     *
     * @param ps
     *            the {@code PrintStream} used as destination of the {@code Formatter}. If
     *            {@code ps} is {@code null}, then a {@code NullPointerException} will
     *            be raised.
     */
    public Formatter(PrintStream ps) {
        if (ps == null) {
            throw new NullPointerException("ps == null");
        }
        out = ps;
        locale = Locale.getDefault();
    }

    private void checkNotClosed() {
        if (closed) {
            throw new FormatterClosedException();
        }
    }

    /**
     * Returns the {@code Locale} of the {@code Formatter}.
     *
     * @return the {@code Locale} for the {@code Formatter} or {@code null} for no {@code Locale}.
     * @throws FormatterClosedException
     *             if the {@code Formatter} has been closed.
     */
    public Locale locale() {
        checkNotClosed();
        return locale;
    }

    /**
     * Returns the output destination of the {@code Formatter}.
     *
     * @return the output destination of the {@code Formatter}.
     * @throws FormatterClosedException
     *             if the {@code Formatter} has been closed.
     */
    public Appendable out() {
        checkNotClosed();
        return out;
    }

    /**
     * Returns the content by calling the {@code toString()} method of the output
     * destination.
     *
     * @return the content by calling the {@code toString()} method of the output
     *         destination.
     * @throws FormatterClosedException
     *             if the {@code Formatter} has been closed.
     */
    @Override
    public String toString() {
        checkNotClosed();
        return out.toString();
    }

    /**
     * Flushes the {@code Formatter}. If the output destination is {@link Flushable},
     * then the method {@code flush()} will be called on that destination.
     *
     * @throws FormatterClosedException
     *             if the {@code Formatter} has been closed.
     */
    public void flush() {
        checkNotClosed();
        if (out instanceof Flushable) {
            try {
                ((Flushable) out).flush();
            } catch (IOException e) {
                lastIOException = e;
            }
        }
    }

    /**
     * Closes the {@code Formatter}. If the output destination is {@link Closeable},
     * then the method {@code close()} will be called on that destination.
     *
     * If the {@code Formatter} has been closed, then calling the this method will have no
     * effect.
     *
     * Any method but the {@link #ioException()} that is called after the
     * {@code Formatter} has been closed will raise a {@code FormatterClosedException}.
     */
    public void close() {
        if (!closed) {
            closed = true;
            try {
                if (out instanceof Closeable) {
                    ((Closeable) out).close();
                }
            } catch (IOException e) {
                lastIOException = e;
            }
        }
    }

    /**
     * Returns the last {@code IOException} thrown by the {@code Formatter}'s output
     * destination. If the {@code append()} method of the destination does not throw
     * {@code IOException}s, the {@code ioException()} method will always return {@code null}.
     *
     * @return the last {@code IOException} thrown by the {@code Formatter}'s output
     *         destination.
     */
    public IOException ioException() {
        return lastIOException;
    }

    /**
     * Writes a formatted string to the output destination of the {@code Formatter}.
     *
     * @param format
     *            a format string.
     * @param args
     *            the arguments list used in the {@code format()} method. If there are
     *            more arguments than those specified by the format string, then
     *            the additional arguments are ignored.
     * @return this {@code Formatter}.
     * @throws IllegalFormatException
     *             if the format string is illegal or incompatible with the
     *             arguments, or if fewer arguments are sent than those required by
     *             the format string, or any other illegal situation.
     * @throws FormatterClosedException
     *             if the {@code Formatter} has been closed.
     */
    public Formatter format(String format, Object... args) {
        return format(this.locale, format, args);
    }

    /**
     * Writes a formatted string to the output destination of the {@code Formatter}.
     *
     * @param l
     *            the {@code Locale} used in the method. If {@code locale} is
     *            {@code null}, then no localization will be applied. This
     *            parameter does not change this Formatter's default {@code Locale}
     *            as specified during construction, and only applies for the
     *            duration of this call.
     * @param format
     *            a format string.
     * @param args
     *            the arguments list used in the {@code format()} method. If there are
     *            more arguments than those specified by the format string, then
     *            the additional arguments are ignored.
     * @return this {@code Formatter}.
     * @throws IllegalFormatException
     *             if the format string is illegal or incompatible with the
     *             arguments, or if fewer arguments are sent than those required by
     *             the format string, or any other illegal situation.
     * @throws FormatterClosedException
     *             if the {@code Formatter} has been closed.
     */
    public Formatter format(Locale l, String format, Object... args) {
        Locale originalLocale = locale;
        try {
            this.locale = (l == null ? Locale.US : l);
            this.localeData = LocaleData.get(locale);
            doFormat(format, args);
        } finally {
            this.locale = originalLocale;
        }
        return this;
    }

    private void doFormat(String format, Object... args) {
        checkNotClosed();

        FormatSpecifierParser fsp = new FormatSpecifierParser(format);
        int currentObjectIndex = 0;
        Object lastArgument = null;
        boolean hasLastArgumentSet = false;

        int length = format.length();
        int i = 0;
        while (i < length) {
            // Find the maximal plain-text sequence...
            int plainTextStart = i;
            int nextPercent = format.indexOf('%', i);
            int plainTextEnd = (nextPercent == -1) ? length : nextPercent;
            // ...and output it.
            if (plainTextEnd > plainTextStart) {
                outputCharSequence(format, plainTextStart, plainTextEnd);
            }
            i = plainTextEnd;
            // Do we have a format specifier?
            if (i < length) {
                FormatToken token = fsp.parseFormatToken(i + 1);

                Object argument = null;
                if (token.requireArgument()) {
                    int index = token.getArgIndex() == FormatToken.UNSET ? currentObjectIndex++ : token.getArgIndex();
                    argument = getArgument(args, index, fsp, lastArgument, hasLastArgumentSet);
                    lastArgument = argument;
                    hasLastArgumentSet = true;
                }

                CharSequence substitution = transform(token, argument);
                // The substitution is null if we called Formattable.formatTo.
                if (substitution != null) {
                    outputCharSequence(substitution, 0, substitution.length());
                }
                i = fsp.i;
            }
        }
    }

    // Fixes http://code.google.com/p/android/issues/detail?id=1767.
    private void outputCharSequence(CharSequence cs, int start, int end) {
        try {
            out.append(cs, start, end);
        } catch (IOException e) {
            lastIOException = e;
        }
    }

    private Object getArgument(Object[] args, int index, FormatSpecifierParser fsp,
            Object lastArgument, boolean hasLastArgumentSet) {
        if (index == FormatToken.LAST_ARGUMENT_INDEX && !hasLastArgumentSet) {
            throw new MissingFormatArgumentException("<");
        }

        if (args == null) {
            return null;
        }

        if (index >= args.length) {
            throw new MissingFormatArgumentException(fsp.getFormatSpecifierText());
        }

        if (index == FormatToken.LAST_ARGUMENT_INDEX) {
            return lastArgument;
        }

        return args[index];
    }

    /*
     * Complete details of a single format specifier parsed from a format string.
     */
    private static class FormatToken {
        static final int LAST_ARGUMENT_INDEX = -2;

        static final int UNSET = -1;

        static final int FLAGS_UNSET = 0;

        static final int DEFAULT_PRECISION = 6;

        static final int FLAG_ZERO = 1 << 4;

        private int argIndex = UNSET;

        // These have package access for performance. They used to be represented by an int bitmask
        // and accessed via methods, but Android's JIT doesn't yet do a good job of such code.
        // Direct field access, on the other hand, is fast.
        boolean flagComma;
        boolean flagMinus;
        boolean flagParenthesis;
        boolean flagPlus;
        boolean flagSharp;
        boolean flagSpace;
        boolean flagZero;

        private char conversionType = (char) UNSET;
        private char dateSuffix;

        private int precision = UNSET;
        private int width = UNSET;

        private StringBuilder strFlags;

        // Tests whether there were no flags, no width, and no precision specified.
        boolean isDefault() {
            return !flagComma && !flagMinus && !flagParenthesis && !flagPlus && !flagSharp &&
                    !flagSpace && !flagZero && width == UNSET && precision == UNSET;
        }

        boolean isPrecisionSet() {
            return precision != UNSET;
        }

        int getArgIndex() {
            return argIndex;
        }

        void setArgIndex(int index) {
            argIndex = index;
        }

        int getWidth() {
            return width;
        }

        void setWidth(int width) {
            this.width = width;
        }

        int getPrecision() {
            return precision;
        }

        void setPrecision(int precise) {
            this.precision = precise;
        }

        String getStrFlags() {
            return (strFlags != null) ? strFlags.toString() : "";
        }

        /*
         * Sets qualified char as one of the flags. If the char is qualified,
         * sets it as a flag and returns true. Or else returns false.
         */
        boolean setFlag(int ch) {
            boolean dupe = false;
            switch (ch) {
            case ',':
                dupe = flagComma;
                flagComma = true;
                break;
            case '-':
                dupe = flagMinus;
                flagMinus = true;
                break;
            case '(':
                dupe = flagParenthesis;
                flagParenthesis = true;
                break;
            case '+':
                dupe = flagPlus;
                flagPlus = true;
                break;
            case '#':
                dupe = flagSharp;
                flagSharp = true;
                break;
            case ' ':
                dupe = flagSpace;
                flagSpace = true;
                break;
            case '0':
                dupe = flagZero;
                flagZero = true;
                break;
            default:
                return false;
            }
            if (dupe) {
                // The RI documentation implies we're supposed to report all the flags, not just
                // the first duplicate, but the RI behaves the same as we do.
                throw new DuplicateFormatFlagsException(String.valueOf(ch));
            }
            if (strFlags == null) {
                strFlags = new StringBuilder(7); // There are seven possible flags.
            }
            strFlags.append((char) ch);
            return true;
        }

        char getConversionType() {
            return conversionType;
        }

        void setConversionType(char c) {
            conversionType = c;
        }

        char getDateSuffix() {
            return dateSuffix;
        }

        void setDateSuffix(char c) {
            dateSuffix = c;
        }

        boolean requireArgument() {
            return conversionType != '%' && conversionType != 'n';
        }

        void checkFlags(Object arg) {
            // Work out which flags are allowed.
            boolean allowComma = false;
            boolean allowMinus = true;
            boolean allowParenthesis = false;
            boolean allowPlus = false;
            boolean allowSharp = false;
            boolean allowSpace = false;
            boolean allowZero = false;
            // Precision and width?
            boolean allowPrecision = true;
            boolean allowWidth = true;
            // Argument?
            boolean allowArgument = true;
            switch (conversionType) {
            // Character and date/time.
            case 'c': case 'C': case 't': case 'T':
                // Only '-' is allowed.
                allowPrecision = false;
                break;

            // String.
            case 's': case 'S':
                if (arg instanceof Formattable) {
                    allowSharp = true;
                }
                break;

            // Floating point.
            case 'g': case 'G':
                allowComma = allowParenthesis = allowPlus = allowSpace = allowZero = true;
                break;
            case 'f':
                allowComma = allowParenthesis = allowPlus = allowSharp = allowSpace = allowZero = true;
                break;
            case 'e': case 'E':
                allowParenthesis = allowPlus = allowSharp = allowSpace = allowZero = true;
                break;
            case 'a': case 'A':
                allowPlus = allowSharp = allowSpace = allowZero = true;
                break;

            // Integral.
            case 'd':
                allowComma = allowParenthesis = allowPlus = allowSpace = allowZero = true;
                allowPrecision = false;
                break;
            case 'o': case 'x': case 'X':
                allowSharp = allowZero = true;
                if (arg == null || arg instanceof BigInteger) {
                    allowParenthesis = allowPlus = allowSpace = true;
                }
                allowPrecision = false;
                break;

            // Special.
            case 'n':
                // Nothing is allowed.
                allowMinus = false;
                allowArgument = allowPrecision = allowWidth = false;
                break;
            case '%':
                // The only flag allowed is '-', and no argument or precision is allowed.
                allowArgument = false;
                allowPrecision = false;
                break;

            // Booleans and hash codes.
            case 'b': case 'B': case 'h': case 'H':
                break;

            default:
                throw unknownFormatConversionException();
            }

            // Check for disallowed flags.
            String mismatch = null;
            if (!allowComma && flagComma) {
                mismatch = ",";
            } else if (!allowMinus && flagMinus) {
                mismatch = "-";
            } else if (!allowParenthesis && flagParenthesis) {
                mismatch = "(";
            } else if (!allowPlus && flagPlus) {
                mismatch = "+";
            } else if (!allowSharp && flagSharp) {
                mismatch = "#";
            } else if (!allowSpace && flagSpace) {
                mismatch = " ";
            } else if (!allowZero && flagZero) {
                mismatch = "0";
            }
            if (mismatch != null) {
                if (conversionType == 'n') {
                    // For no good reason, %n is a special case...
                    throw new IllegalFormatFlagsException(mismatch);
                } else {
                    throw new FormatFlagsConversionMismatchException(mismatch, conversionType);
                }
            }

            // Check for a missing width with flags that require a width.
            if ((flagMinus || flagZero) && width == UNSET) {
                throw new MissingFormatWidthException("-" + conversionType);
            }

            // Check that no-argument conversion types don't have an argument.
            // Note: the RI doesn't enforce this.
            if (!allowArgument && argIndex != UNSET) {
                throw new IllegalFormatFlagsException("%" + conversionType +
                        " doesn't take an argument");
            }

            // Check that we don't have a precision or width where they're not allowed.
            if (!allowPrecision && precision != UNSET) {
                throw new IllegalFormatPrecisionException(precision);
            }
            if (!allowWidth && width != UNSET) {
                throw new IllegalFormatWidthException(width);
            }

            // Some combinations make no sense...
            if (flagPlus && flagSpace) {
                throw new IllegalFormatFlagsException("the '+' and ' ' flags are incompatible");
            }
            if (flagMinus && flagZero) {
                throw new IllegalFormatFlagsException("the '-' and '0' flags are incompatible");
            }
        }

        public UnknownFormatConversionException unknownFormatConversionException() {
            if (conversionType == 't' || conversionType == 'T') {
                throw new UnknownFormatConversionException(String.format("%c%c",
                        conversionType, dateSuffix));
            }
            throw new UnknownFormatConversionException(String.valueOf(conversionType));
        }
    }

    /*
     * Gets the formatted string according to the format token and the
     * argument.
     */
    private CharSequence transform(FormatToken token, Object argument) {
        this.formatToken = token;
        this.arg = argument;

        // There are only two format specifiers that matter: "%d" and "%s".
        // Nothing else is common in the wild. We fast-path these two to
        // avoid the heavyweight machinery needed to cope with flags, width,
        // and precision.
        if (token.isDefault()) {
            switch (token.getConversionType()) {
            case 's':
                if (arg == null) {
                    return "null";
                } else if (!(arg instanceof Formattable)) {
                    return arg.toString();
                }
                break;
            case 'd':
                boolean needLocalizedDigits = (localeData.zeroDigit != '0');
                if (out instanceof StringBuilder && !needLocalizedDigits) {
                    if (arg instanceof Integer || arg instanceof Short || arg instanceof Byte) {
                        IntegralToString.appendInt((StringBuilder) out, ((Number) arg).intValue());
                        return null;
                    } else if (arg instanceof Long) {
                        IntegralToString.appendLong((StringBuilder) out, ((Long) arg).longValue());
                        return null;
                    }
                }
                if (arg instanceof Integer || arg instanceof Long || arg instanceof Short || arg instanceof Byte) {
                    String result = arg.toString();
                    return needLocalizedDigits ? localizeDigits(result) : result;
                }
            }
        }

        formatToken.checkFlags(arg);
        CharSequence result;
        switch (token.getConversionType()) {
        case 'B': case 'b':
            result = transformFromBoolean();
            break;
        case 'H': case 'h':
            result = transformFromHashCode();
            break;
        case 'S': case 's':
            result = transformFromString();
            break;
        case 'C': case 'c':
            result = transformFromCharacter();
            break;
        case 'd': case 'o': case 'x': case 'X':
            if (arg == null || arg instanceof BigInteger) {
                result = transformFromBigInteger();
            } else {
                result = transformFromInteger();
            }
            break;
        case 'A': case 'a': case 'E': case 'e': case 'f': case 'G': case 'g':
            result = transformFromFloat();
            break;
        case '%':
            result = transformFromPercent();
            break;
        case 'n':
            result = System.lineSeparator();
            break;
        case 't': case 'T':
            result = transformFromDateTime();
            break;
        default:
            throw token.unknownFormatConversionException();
        }

        if (Character.isUpperCase(token.getConversionType())) {
            if (result != null) {
                result = result.toString().toUpperCase(locale);
            }
        }
        return result;
    }

    private IllegalFormatConversionException badArgumentType() {
        throw new IllegalFormatConversionException(formatToken.getConversionType(), arg.getClass());
    }

    /**
     * Returns a CharSequence corresponding to {@code s} with all the ASCII digits replaced
     * by digits appropriate to this formatter's locale. Other characters remain unchanged.
     */
    private CharSequence localizeDigits(CharSequence s) {
        int length = s.length();
        int offsetToLocalizedDigits = localeData.zeroDigit - '0';
        StringBuilder result = new StringBuilder(length);
        for (int i = 0; i < length; ++i) {
            char ch = s.charAt(i);
            if (ch >= '0' && ch <= '9') {
                ch += offsetToLocalizedDigits;
            }
            result.append(ch);
        }
        return result;
    }

    /**
     * Inserts the grouping separator every 3 digits. DecimalFormat lets you configure grouping
     * size, but you can't access that from Formatter, and the default is every 3 digits.
     */
    private CharSequence insertGrouping(CharSequence s) {
        StringBuilder result = new StringBuilder(s.length() + s.length()/3);

        // A leading '-' doesn't want to be included in the grouping.
        int digitsLength = s.length();
        int i = 0;
        if (s.charAt(0) == '-') {
            --digitsLength;
            ++i;
            result.append('-');
        }

        // Append the digits that come before the first separator.
        int headLength = digitsLength % 3;
        if (headLength == 0) {
            headLength = 3;
        }
        result.append(s, i, i + headLength);
        i += headLength;

        // Append the remaining groups.
        for (; i < s.length(); i += 3) {
            result.append(localeData.groupingSeparator);
            result.append(s, i, i + 3);
        }
        return result;
    }

    private CharSequence transformFromBoolean() {
        CharSequence result;
        if (arg instanceof Boolean) {
            result = arg.toString();
        } else if (arg == null) {
            result = "false";
        } else {
            result = "true";
        }
        return padding(result, 0);
    }

    private CharSequence transformFromHashCode() {
        CharSequence result;
        if (arg == null) {
            result = "null";
        } else {
            result = Integer.toHexString(arg.hashCode());
        }
        return padding(result, 0);
    }

    private CharSequence transformFromString() {
        if (arg instanceof Formattable) {
            int flags = 0;
            if (formatToken.flagMinus) {
                flags |= FormattableFlags.LEFT_JUSTIFY;
            }
            if (formatToken.flagSharp) {
                flags |= FormattableFlags.ALTERNATE;
            }
            if (Character.isUpperCase(formatToken.getConversionType())) {
                flags |= FormattableFlags.UPPERCASE;
            }
            ((Formattable) arg).formatTo(this, flags, formatToken.getWidth(),
                    formatToken.getPrecision());
            // all actions have been taken out in the
            // Formattable.formatTo, thus there is nothing to do, just
            // returns null, which tells the Parser to add nothing to the
            // output.
            return null;
        }
        CharSequence result = arg != null ? arg.toString() : "null";
        return padding(result, 0);
    }

    private CharSequence transformFromCharacter() {
        if (arg == null) {
            return padding("null", 0);
        }
        if (arg instanceof Character) {
            return padding(String.valueOf(arg), 0);
        } else if (arg instanceof Byte || arg instanceof Short || arg instanceof Integer) {
            int codePoint = ((Number) arg).intValue();
            if (!Character.isValidCodePoint(codePoint)) {
                throw new IllegalFormatCodePointException(codePoint);
            }
            CharSequence result = (codePoint < Character.MIN_SUPPLEMENTARY_CODE_POINT)
                    ? String.valueOf((char) codePoint)
                    : String.valueOf(Character.toChars(codePoint));
            return padding(result, 0);
        } else {
            throw badArgumentType();
        }
    }

    private CharSequence transformFromPercent() {
        return padding("%", 0);
    }

    private CharSequence padding(CharSequence source, int startIndex) {
        int start = startIndex;
        int width = formatToken.getWidth();
        int precision = formatToken.getPrecision();

        int length = source.length();
        if (precision >= 0) {
            length = Math.min(length, precision);
            if (source instanceof StringBuilder) {
                ((StringBuilder) source).setLength(length);
            } else {
                source = source.subSequence(0, length);
            }
        }
        if (width > 0) {
            width = Math.max(source.length(), width);
        }
        if (length >= width) {
            return source;
        }

        char paddingChar = '\u0020'; // space as padding char.
        if (formatToken.flagZero) {
            if (formatToken.getConversionType() == 'd') {
                paddingChar = localeData.zeroDigit;
            } else {
                paddingChar = '0'; // No localized digits for bases other than decimal.
            }
        } else {
            // if padding char is space, always pad from the start.
            start = 0;
        }
        char[] paddingChars = new char[width - length];
        Arrays.fill(paddingChars, paddingChar);

        boolean paddingRight = formatToken.flagMinus;
        StringBuilder result = toStringBuilder(source);
        if (paddingRight) {
            result.append(paddingChars);
        } else {
            result.insert(start, paddingChars);
        }
        return result;
    }

    private StringBuilder toStringBuilder(CharSequence cs) {
        return cs instanceof StringBuilder ? (StringBuilder) cs : new StringBuilder(cs);
    }

    private StringBuilder wrapParentheses(StringBuilder result) {
        result.setCharAt(0, '('); // Replace the '-'.
        if (formatToken.flagZero) {
            formatToken.setWidth(formatToken.getWidth() - 1);
            result = (StringBuilder) padding(result, 1);
            result.append(')');
        } else {
            result.append(')');
            result = (StringBuilder) padding(result, 0);
        }
        return result;
    }

    private CharSequence transformFromInteger() {
        int startIndex = 0;
        StringBuilder result = new StringBuilder();
        char currentConversionType = formatToken.getConversionType();

        long value;
        if (arg instanceof Long) {
            value = ((Long) arg).longValue();
        } else if (arg instanceof Integer) {
            value = ((Integer) arg).longValue();
        } else if (arg instanceof Short) {
            value = ((Short) arg).longValue();
        } else if (arg instanceof Byte) {
            value = ((Byte) arg).longValue();
        } else {
            throw badArgumentType();
        }

        if (formatToken.flagSharp) {
            if (currentConversionType == 'o') {
                result.append("0");
                startIndex += 1;
            } else {
                result.append("0x");
                startIndex += 2;
            }
        }

        if (currentConversionType == 'd') {
            CharSequence digits = Long.toString(value);
            if (formatToken.flagComma) {
                digits = insertGrouping(digits);
            }
            if (localeData.zeroDigit != '0') {
                digits = localizeDigits(digits);
            }
            result.append(digits);

            if (value < 0) {
                if (formatToken.flagParenthesis) {
                    return wrapParentheses(result);
                } else if (formatToken.flagZero) {
                    startIndex++;
                }
            } else {
                if (formatToken.flagPlus) {
                    result.insert(0, '+');
                    startIndex += 1;
                } else if (formatToken.flagSpace) {
                    result.insert(0, ' ');
                    startIndex += 1;
                }
            }
        } else {
            // Undo sign-extension, since we'll be using Long.to(Octal|Hex)String.
            if (arg instanceof Byte) {
                value &= 0xffL;
            } else if (arg instanceof Short) {
                value &= 0xffffL;
            } else if (arg instanceof Integer) {
                value &= 0xffffffffL;
            }
            if (currentConversionType == 'o') {
                result.append(Long.toOctalString(value));
            } else {
                result.append(Long.toHexString(value));
            }
        }

        return padding(result, startIndex);
    }

    private CharSequence transformFromNull() {
        formatToken.flagZero = false;
        return padding("null", 0);
    }

    private CharSequence transformFromBigInteger() {
        int startIndex = 0;
        StringBuilder result = new StringBuilder();
        BigInteger bigInt = (BigInteger) arg;
        char currentConversionType = formatToken.getConversionType();

        if (bigInt == null) {
            return transformFromNull();
        }

        boolean isNegative = (bigInt.compareTo(BigInteger.ZERO) < 0);

        if (currentConversionType == 'd') {
            CharSequence digits = bigInt.toString(10);
            if (formatToken.flagComma) {
                digits = insertGrouping(digits);
            }
            result.append(digits);
        } else if (currentConversionType == 'o') {
            // convert BigInteger to a string presentation using radix 8
            result.append(bigInt.toString(8));
        } else {
            // convert BigInteger to a string presentation using radix 16
            result.append(bigInt.toString(16));
        }
        if (formatToken.flagSharp) {
            startIndex = isNegative ? 1 : 0;
            if (currentConversionType == 'o') {
                result.insert(startIndex, "0");
                startIndex += 1;
            } else if (currentConversionType == 'x' || currentConversionType == 'X') {
                result.insert(startIndex, "0x");
                startIndex += 2;
            }
        }

        if (!isNegative) {
            if (formatToken.flagPlus) {
                result.insert(0, '+');
                startIndex += 1;
            }
            if (formatToken.flagSpace) {
                result.insert(0, ' ');
                startIndex += 1;
            }
        }

        /* pad paddingChar to the output */
        if (isNegative && formatToken.flagParenthesis) {
            return wrapParentheses(result);
        }
        if (isNegative && formatToken.flagZero) {
            startIndex++;
        }
        return padding(result, startIndex);
    }

    private CharSequence transformFromDateTime() {
        if (arg == null) {
            return transformFromNull();
        }

        Calendar calendar;
        if (arg instanceof Calendar) {
            calendar = (Calendar) arg;
        } else {
            Date date = null;
            if (arg instanceof Long) {
                date = new Date(((Long) arg).longValue());
            } else if (arg instanceof Date) {
                date = (Date) arg;
            } else {
                throw badArgumentType();
            }
            calendar = Calendar.getInstance(locale);
            calendar.setTime(date);
        }

        StringBuilder result = new StringBuilder();
        if (!appendT(result, formatToken.getDateSuffix(), calendar)) {
            throw formatToken.unknownFormatConversionException();
        }
        return padding(result, 0);
    }

    private boolean appendT(StringBuilder result, char conversion, Calendar calendar) {
        switch (conversion) {
        case 'A':
            result.append(localeData.longWeekdayNames[calendar.get(Calendar.DAY_OF_WEEK)]);
            return true;
        case 'a':
            result.append(localeData.shortWeekdayNames[calendar.get(Calendar.DAY_OF_WEEK)]);
            return true;
        case 'B':
            result.append(localeData.longMonthNames[calendar.get(Calendar.MONTH)]);
            return true;
        case 'b': case 'h':
            result.append(localeData.shortMonthNames[calendar.get(Calendar.MONTH)]);
            return true;
        case 'C':
            appendLocalized(result, calendar.get(Calendar.YEAR) / 100, 2);
            return true;
        case 'D':
            appendT(result, 'm', calendar);
            result.append('/');
            appendT(result, 'd', calendar);
            result.append('/');
            appendT(result, 'y', calendar);
            return true;
        case 'F':
            appendT(result, 'Y', calendar);
            result.append('-');
            appendT(result, 'm', calendar);
            result.append('-');
            appendT(result, 'd', calendar);
            return true;
        case 'H':
            appendLocalized(result, calendar.get(Calendar.HOUR_OF_DAY), 2);
            return true;
        case 'I':
            appendLocalized(result, to12Hour(calendar.get(Calendar.HOUR)), 2);
            return true;
        case 'L':
            appendLocalized(result, calendar.get(Calendar.MILLISECOND), 3);
            return true;
        case 'M':
            appendLocalized(result, calendar.get(Calendar.MINUTE), 2);
            return true;
        case 'N':
            appendLocalized(result, calendar.get(Calendar.MILLISECOND) * 1000000L, 9);
            return true;
        case 'Q':
            appendLocalized(result, calendar.getTimeInMillis(), 0);
            return true;
        case 'R':
            appendT(result, 'H', calendar);
            result.append(':');
            appendT(result, 'M', calendar);
            return true;
        case 'S':
            appendLocalized(result, calendar.get(Calendar.SECOND), 2);
            return true;
        case 'T':
            appendT(result, 'H', calendar);
            result.append(':');
            appendT(result, 'M', calendar);
            result.append(':');
            appendT(result, 'S', calendar);
            return true;
        case 'Y':
            appendLocalized(result, calendar.get(Calendar.YEAR), 4);
            return true;
        case 'Z':
            TimeZone timeZone = calendar.getTimeZone();
            result.append(timeZone.getDisplayName(timeZone.inDaylightTime(calendar.getTime()),
                    TimeZone.SHORT, locale));
            return true;
        case 'c':
            appendT(result, 'a', calendar);
            result.append(' ');
            appendT(result, 'b', calendar);
            result.append(' ');
            appendT(result, 'd', calendar);
            result.append(' ');
            appendT(result, 'T', calendar);
            result.append(' ');
            appendT(result, 'Z', calendar);
            result.append(' ');
            appendT(result, 'Y', calendar);
            return true;
        case 'd':
            appendLocalized(result, calendar.get(Calendar.DAY_OF_MONTH), 2);
            return true;
        case 'e':
            appendLocalized(result, calendar.get(Calendar.DAY_OF_MONTH), 0);
            return true;
        case 'j':
            appendLocalized(result, calendar.get(Calendar.DAY_OF_YEAR), 3);
            return true;
        case 'k':
            appendLocalized(result, calendar.get(Calendar.HOUR_OF_DAY), 0);
            return true;
        case 'l':
            appendLocalized(result, to12Hour(calendar.get(Calendar.HOUR)), 0);
            return true;
        case 'm':
            // Calendar.JANUARY is 0; humans want January represented as 1.
            appendLocalized(result, calendar.get(Calendar.MONTH) + 1, 2);
            return true;
        case 'p':
            result.append(localeData.amPm[calendar.get(Calendar.AM_PM)].toLowerCase(locale));
            return true;
        case 'r':
            appendT(result, 'I', calendar);
            result.append(':');
            appendT(result, 'M', calendar);
            result.append(':');
            appendT(result, 'S', calendar);
            result.append(' ');
            result.append(localeData.amPm[calendar.get(Calendar.AM_PM)]);
            return true;
        case 's':
            appendLocalized(result, calendar.getTimeInMillis() / 1000, 0);
            return true;
        case 'y':
            appendLocalized(result, calendar.get(Calendar.YEAR) % 100, 2);
            return true;
        case 'z':
            long offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
            char sign = '+';
            if (offset < 0) {
                sign = '-';
                offset = -offset;
            }
            result.append(sign);
            appendLocalized(result, offset / 3600000, 2);
            appendLocalized(result, (offset % 3600000) / 60000, 2);
            return true;
        }
        return false;
    }

    private int to12Hour(int hour) {
        return hour == 0 ? 12 : hour;
    }

    private void appendLocalized(StringBuilder result, long value, int width) {
        int paddingIndex = result.length();
        char zeroDigit = localeData.zeroDigit;
        if (zeroDigit == '0') {
            result.append(value);
        } else {
            result.append(localizeDigits(Long.toString(value)));
        }
        int zeroCount = width - (result.length() - paddingIndex);
        if (zeroCount <= 0) {
            return;
        }
        if (zeroDigit == '0') {
            result.insert(paddingIndex, ZEROS, 0, zeroCount);
        } else {
            for (int i = 0; i < zeroCount; ++i) {
                result.insert(paddingIndex, zeroDigit);
            }
        }
    }

    private CharSequence transformFromSpecialNumber(double d) {
        String source = null;
        if (Double.isNaN(d)) {
            source = "NaN";
        } else if (d == Double.POSITIVE_INFINITY) {
            if (formatToken.flagPlus) {
                source = "+Infinity";
            } else if (formatToken.flagSpace) {
                source = " Infinity";
            } else {
                source = "Infinity";
            }
        } else if (d == Double.NEGATIVE_INFINITY) {
            if (formatToken.flagParenthesis) {
                source = "(Infinity)";
            } else {
                source = "-Infinity";
            }
        } else {
            return null;
        }

        formatToken.setPrecision(FormatToken.UNSET);
        formatToken.flagZero = false;
        return padding(source, 0);
    }

    private CharSequence transformFromFloat() {
        if (arg == null) {
            return transformFromNull();
        } else if (arg instanceof Float || arg instanceof Double) {
            Number number = (Number) arg;
            double d = number.doubleValue();
            if (d != d || d == Double.POSITIVE_INFINITY || d == Double.NEGATIVE_INFINITY) {
                return transformFromSpecialNumber(d);
            }
        } else if (arg instanceof BigDecimal) {
            // BigDecimal can't represent NaN or infinities, but its doubleValue method will return
            // infinities if the BigDecimal is too big for a double.
        } else {
            throw badArgumentType();
        }

        char conversionType = formatToken.getConversionType();
        if (conversionType != 'a' && conversionType != 'A' && !formatToken.isPrecisionSet()) {
            formatToken.setPrecision(FormatToken.DEFAULT_PRECISION);
        }

        StringBuilder result = new StringBuilder();
        switch (conversionType) {
        case 'a': case 'A':
            transformA(result);
            break;
        case 'e': case 'E':
            transformE(result);
            break;
        case 'f':
            transformF(result);
            break;
        case 'g':
        case 'G':
            transformG(result);
            break;
        default:
            throw formatToken.unknownFormatConversionException();
        }

        formatToken.setPrecision(FormatToken.UNSET);

        int startIndex = 0;
        if (result.charAt(0) == localeData.minusSign) {
            if (formatToken.flagParenthesis) {
                return wrapParentheses(result);
            }
        } else {
            if (formatToken.flagSpace) {
                result.insert(0, ' ');
                startIndex++;
            }
            if (formatToken.flagPlus) {
                result.insert(0, '+');
                startIndex++;
            }
        }

        char firstChar = result.charAt(0);
        if (formatToken.flagZero && (firstChar == '+' || firstChar == localeData.minusSign)) {
            startIndex = 1;
        }

        if (conversionType == 'a' || conversionType == 'A') {
            startIndex += 2;
        }
        return padding(result, startIndex);
    }

    private void transformE(StringBuilder result) {
        // All zeros in this method are *pattern* characters, so no localization.
        final int precision = formatToken.getPrecision();
        String pattern = "0E+00";
        if (precision > 0) {
            StringBuilder sb = new StringBuilder("0.");
            char[] zeros = new char[precision];
            Arrays.fill(zeros, '0');
            sb.append(zeros);
            sb.append("E+00");
            pattern = sb.toString();
        }

        NativeDecimalFormat nf = getDecimalFormat(pattern);
        char[] chars;
        if (arg instanceof BigDecimal) {
            chars = nf.formatBigDecimal((BigDecimal) arg, null);
        } else {
            chars = nf.formatDouble(((Number) arg).doubleValue(), null);
        }
        // Unlike %f, %e uses 'e' (regardless of what the DecimalFormatSymbols would have us use).
        for (int i = 0; i < chars.length; ++i) {
            if (chars[i] == 'E') {
                chars[i] = 'e';
            }
        }
        result.append(chars);
        // The # flag requires that we always output a decimal separator.
        if (formatToken.flagSharp && precision == 0) {
            int indexOfE = result.indexOf("e");
            result.insert(indexOfE, localeData.decimalSeparator);
        }
    }

    private void transformG(StringBuilder result) {
        int precision = formatToken.getPrecision();
        if (precision == 0) {
            precision = 1;
        }
        formatToken.setPrecision(precision);

        double d = ((Number) arg).doubleValue();
        if (d == 0.0) {
            precision--;
            formatToken.setPrecision(precision);
            transformF(result);
            return;
        }

        boolean requireScientificRepresentation = true;
        d = Math.abs(d);
        if (Double.isInfinite(d)) {
            precision = formatToken.getPrecision();
            precision--;
            formatToken.setPrecision(precision);
            transformE(result);
            return;
        }
        BigDecimal b = new BigDecimal(d, new MathContext(precision));
        d = b.doubleValue();
        long l = b.longValue();

        if (d >= 1 && d < Math.pow(10, precision)) {
            if (l < Math.pow(10, precision)) {
                requireScientificRepresentation = false;
                precision -= String.valueOf(l).length();
                precision = precision < 0 ? 0 : precision;
                l = Math.round(d * Math.pow(10, precision + 1));
                if (String.valueOf(l).length() <= formatToken.getPrecision()) {
                    precision++;
                }
                formatToken.setPrecision(precision);
            }
        } else {
            l = b.movePointRight(4).longValue();
            if (d >= Math.pow(10, -4) && d < 1) {
                requireScientificRepresentation = false;
                precision += 4 - String.valueOf(l).length();
                l = b.movePointRight(precision + 1).longValue();
                if (String.valueOf(l).length() <= formatToken.getPrecision()) {
                    precision++;
                }
                l = b.movePointRight(precision).longValue();
                if (l >= Math.pow(10, precision - 4)) {
                    formatToken.setPrecision(precision);
                }
            }
        }
        if (requireScientificRepresentation) {
            precision = formatToken.getPrecision();
            precision--;
            formatToken.setPrecision(precision);
            transformE(result);
        } else {
            transformF(result);
        }
    }

    private void transformF(StringBuilder result) {
        // All zeros in this method are *pattern* characters, so no localization.
        String pattern = "0.000000";
        final int precision = formatToken.getPrecision();
        if (formatToken.flagComma || precision != FormatToken.DEFAULT_PRECISION) {
            StringBuilder patternBuilder = new StringBuilder();
            if (formatToken.flagComma) {
                patternBuilder.append(',');
                int groupingSize = 3;
                char[] sharps = new char[groupingSize - 1];
                Arrays.fill(sharps, '#');
                patternBuilder.append(sharps);
            }
            patternBuilder.append('0');
            if (precision > 0) {
                patternBuilder.append('.');
                for (int i = 0; i < precision; ++i) {
                    patternBuilder.append('0');
                }
            }
            pattern = patternBuilder.toString();
        }

        NativeDecimalFormat nf = getDecimalFormat(pattern);
        if (arg instanceof BigDecimal) {
            result.append(nf.formatBigDecimal((BigDecimal) arg, null));
        } else {
            result.append(nf.formatDouble(((Number) arg).doubleValue(), null));
        }
        // The # flag requires that we always output a decimal separator.
        if (formatToken.flagSharp && precision == 0) {
            result.append(localeData.decimalSeparator);
        }
    }

    private void transformA(StringBuilder result) {
        if (arg instanceof Float) {
            result.append(Float.toHexString(((Float) arg).floatValue()));
        } else if (arg instanceof Double) {
            result.append(Double.toHexString(((Double) arg).doubleValue()));
        } else {
            throw badArgumentType();
        }

        if (!formatToken.isPrecisionSet()) {
            return;
        }

        int precision = formatToken.getPrecision();
        if (precision == 0) {
            precision = 1;
        }
        int indexOfFirstFractionalDigit = result.indexOf(".") + 1;
        int indexOfP = result.indexOf("p");
        int fractionalLength = indexOfP - indexOfFirstFractionalDigit;

        if (fractionalLength == precision) {
            return;
        }

        if (fractionalLength < precision) {
            char[] zeros = new char[precision - fractionalLength];
            Arrays.fill(zeros, '0'); // %a shouldn't be localized.
            result.insert(indexOfP, zeros);
            return;
        }
        result.delete(indexOfFirstFractionalDigit + precision, indexOfP);
    }

    private static class FormatSpecifierParser {
        private String format;
        private int length;

        private int startIndex;
        private int i;

        /**
         * Constructs a new parser for the given format string.
         */
        FormatSpecifierParser(String format) {
            this.format = format;
            this.length = format.length();
        }

        /**
         * Returns a FormatToken representing the format specifier starting at 'offset'.
         * @param offset the first character after the '%'
         */
        FormatToken parseFormatToken(int offset) {
            this.startIndex = offset;
            this.i = offset;
            return parseArgumentIndexAndFlags(new FormatToken());
        }

        /**
         * Returns a string corresponding to the last format specifier that was parsed.
         * Used to construct error messages.
         */
        String getFormatSpecifierText() {
            return format.substring(startIndex, i);
        }

        private int peek() {
            return (i < length) ? format.charAt(i) : -1;
        }

        private char advance() {
            if (i >= length) {
                throw unknownFormatConversionException();
            }
            return format.charAt(i++);
        }

        private UnknownFormatConversionException unknownFormatConversionException() {
            throw new UnknownFormatConversionException(getFormatSpecifierText());
        }

        private FormatToken parseArgumentIndexAndFlags(FormatToken token) {
            // Parse the argument index, if there is one.
            int position = i;
            int ch = peek();
            if (Character.isDigit(ch)) {
                int number = nextInt();
                if (peek() == '$') {
                    // The number was an argument index.
                    advance(); // Swallow the '$'.
                    if (number == FormatToken.UNSET) {
                        throw new MissingFormatArgumentException(getFormatSpecifierText());
                    }
                    // k$ stands for the argument whose index is k-1 except that
                    // 0$ and 1$ both stand for the first element.
                    token.setArgIndex(Math.max(0, number - 1));
                } else {
                    if (ch == '0') {
                        // The digit zero is a format flag, so reparse it as such.
                        i = position;
                    } else {
                        // The number was a width. This means there are no flags to parse.
                        return parseWidth(token, number);
                    }
                }
            } else if (ch == '<') {
                token.setArgIndex(FormatToken.LAST_ARGUMENT_INDEX);
                advance();
            }

            // Parse the flags.
            while (token.setFlag(peek())) {
                advance();
            }

            // What comes next?
            ch = peek();
            if (Character.isDigit(ch)) {
                return parseWidth(token, nextInt());
            } else if (ch == '.') {
                return parsePrecision(token);
            } else {
                return parseConversionType(token);
            }
        }

        // We pass the width in because in some cases we've already parsed it.
        // (Because of the ambiguity between argument indexes and widths.)
        private FormatToken parseWidth(FormatToken token, int width) {
            token.setWidth(width);
            int ch = peek();
            if (ch == '.') {
                return parsePrecision(token);
            } else {
                return parseConversionType(token);
            }
        }

        private FormatToken parsePrecision(FormatToken token) {
            advance(); // Swallow the '.'.
            int ch = peek();
            if (Character.isDigit(ch)) {
                token.setPrecision(nextInt());
                return parseConversionType(token);
            } else {
                // The precision is required but not given by the format string.
                throw unknownFormatConversionException();
            }
        }

        private FormatToken parseConversionType(FormatToken token) {
            char conversionType = advance(); // A conversion type is mandatory.
            token.setConversionType(conversionType);
            if (conversionType == 't' || conversionType == 'T') {
                char dateSuffix = advance(); // A date suffix is mandatory for 't' or 'T'.
                token.setDateSuffix(dateSuffix);
            }
            return token;
        }

        // Parses an integer (of arbitrary length, but typically just one digit).
        private int nextInt() {
            long value = 0;
            while (i < length && Character.isDigit(format.charAt(i))) {
                value = 10 * value + (format.charAt(i++) - '0');
                if (value > Integer.MAX_VALUE) {
                    return failNextInt();
                }
            }
            return (int) value;
        }

        // Swallow remaining digits to resync our attempted parse, but return failure.
        private int failNextInt() {
            while (Character.isDigit(peek())) {
                advance();
            }
            return FormatToken.UNSET;
        }
    }
}