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
//! 用于格式化和打印字符串的实用工具。

#![stable(feature = "rust1", since = "1.0.0")]

use crate::cell::{Cell, Ref, RefCell, RefMut, UnsafeCell};
use crate::char::EscapeDebugExtArgs;
use crate::marker::PhantomData;
use crate::mem;
use crate::num::fmt as numfmt;
use crate::ops::Deref;
use crate::result;
use crate::str;

mod builders;
#[cfg(not(no_fp_fmt_parse))]
mod float;
#[cfg(no_fp_fmt_parse)]
mod nofloat;
mod num;

#[stable(feature = "fmt_flags_align", since = "1.28.0")]
/// `Formatter::align` 返回的可能的对齐方式
#[derive(Debug)]
pub enum Alignment {
    #[stable(feature = "fmt_flags_align", since = "1.28.0")]
    /// 指示内容应左对齐。
    Left,
    #[stable(feature = "fmt_flags_align", since = "1.28.0")]
    /// 指示内容应右对齐。
    Right,
    #[stable(feature = "fmt_flags_align", since = "1.28.0")]
    /// 指示内容应居中对齐。
    Center,
}

#[stable(feature = "debug_builders", since = "1.2.0")]
pub use self::builders::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple};

#[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
#[doc(hidden)]
pub mod rt {
    pub mod v1;
}

/// 格式化程序方法返回的类型。
///
/// # Examples
///
/// ```
/// use std::fmt;
///
/// #[derive(Debug)]
/// struct Triangle {
///     a: f32,
///     b: f32,
///     c: f32
/// }
///
/// impl fmt::Display for Triangle {
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         write!(f, "({}, {}, {})", self.a, self.b, self.c)
///     }
/// }
///
/// let pythagorean_triple = Triangle { a: 3.0, b: 4.0, c: 5.0 };
///
/// assert_eq!(format!("{}", pythagorean_triple), "(3, 4, 5)");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub type Result = result::Result<(), Error>;

/// 将消息格式化为流后返回的错误类型。
///
/// 除了发生错误以外,此类型不支持错误的传输。
/// 必须安排任何其他信息以通过其他方式进行传输。
///
/// 要记住的重要一点是,不要将 `fmt::Error` 类型与 [`std::io::Error`] 或 [`std::error::Error`] 混淆,在作用域中也可以将它们与 [`std::io::Error`] 或 [`std::error::Error`] 混淆。
///
///
/// [`std::io::Error`]: ../../std/io/struct.Error.html
/// [`std::error::Error`]: ../../std/error/trait.Error.html
///
/// # Examples
///
/// ```rust
/// use std::fmt::{self, write};
///
/// let mut output = String::new();
/// if let Err(fmt::Error) = write(&mut output, format_args!("Hello {}!", "world")) {
///     panic!("An error occurred");
/// }
/// ```
///
///
#[stable(feature = "rust1", since = "1.0.0")]
#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Error;

/// 一个用于写入或格式化为 Unicode 接受的缓冲区或流的 trait。
///
/// 一个只接受 UTF-8 编码的数据,而不是 [flushable] 的 trait。
/// 如果您只想接受 Unicode 且不需要冲洗,则应实现此 trait; 否则,请执行此操作。
/// 否则,您应该实现 [`std::io::Write`]。
///
/// [`std::io::Write`]: ../../std/io/trait.Write.html
/// [flushable]: ../../std/io/trait.Write.html#tymethod.flush
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Write {
    /// 将字符串切片写入此 writer,返回写入是否成功。
    ///
    /// 仅当成功写入整个字符串切片后,此方法才能成功,并且只有在写入所有数据或发生错误后,该方法才会返回。
    ///
    ///
    /// # Errors
    ///
    /// 错误时,此函数将返回 [`Error`] 的实例。
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt::{Error, Write};
    ///
    /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
    ///     f.write_str(s)
    /// }
    ///
    /// let mut buf = String::new();
    /// writer(&mut buf, "hola").unwrap();
    /// assert_eq!(&buf, "hola");
    /// ```
    ///
    ///
    #[stable(feature = "rust1", since = "1.0.0")]
    fn write_str(&mut self, s: &str) -> Result;

    /// 将 [`char`] 写入此 writer,返回写入是否成功。
    ///
    /// 单个 [`char`] 可以被编码为一个以上的字节。
    /// 仅当成功写入了整个字节序列后,此方法才能成功,并且直到所有数据都已写入或发生错误后,该方法才会返回。
    ///
    ///
    /// # Errors
    ///
    /// 错误时,此函数将返回 [`Error`] 的实例。
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt::{Error, Write};
    ///
    /// fn writer<W: Write>(f: &mut W, c: char) -> Result<(), Error> {
    ///     f.write_char(c)
    /// }
    ///
    /// let mut buf = String::new();
    /// writer(&mut buf, 'a').unwrap();
    /// writer(&mut buf, 'b').unwrap();
    /// assert_eq!(&buf, "ab");
    /// ```
    ///
    #[stable(feature = "fmt_write_char", since = "1.1.0")]
    fn write_char(&mut self, c: char) -> Result {
        self.write_str(c.encode_utf8(&mut [0; 4]))
    }

    /// 结合使用 [`write!`] 宏和 trait 的实现者。
    ///
    /// 通常不应手动调用此方法,而应通过 [`write!`] 宏本身来调用。
    ///
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt::{Error, Write};
    ///
    /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
    ///     f.write_fmt(format_args!("{}", s))
    /// }
    ///
    /// let mut buf = String::new();
    /// writer(&mut buf, "world").unwrap();
    /// assert_eq!(&buf, "world");
    /// ```
    #[stable(feature = "rust1", since = "1.0.0")]
    fn write_fmt(mut self: &mut Self, args: Arguments<'_>) -> Result {
        write(&mut self, args)
    }
}

#[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
impl<W: Write + ?Sized> Write for &mut W {
    fn write_str(&mut self, s: &str) -> Result {
        (**self).write_str(s)
    }

    fn write_char(&mut self, c: char) -> Result {
        (**self).write_char(c)
    }

    fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
        (**self).write_fmt(args)
    }
}

/// 格式化配置。
///
/// `Formatter` 代表与格式相关的各种选项。
/// 用户不直接构建 `Formatter`s。将所有格式为 traits 的 `fmt` 方法 (例如 [`Debug`] 和 [`Display`]) 传递给 `fmt` 方法。
///
///
/// 要与 `Formatter` 进行交互,您将调用各种方法来更改与格式相关的各种选项。
/// 有关示例,请参见下面在 `Formatter` 上定义的方法的文档。
///
#[allow(missing_debug_implementations)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Formatter<'a> {
    flags: u32,
    fill: char,
    align: rt::v1::Alignment,
    width: Option<usize>,
    precision: Option<usize>,

    buf: &'a mut (dyn Write + 'a),
}

impl<'a> Formatter<'a> {
    /// 使用默认设置创建一个新的格式化程序。
    ///
    /// 在不需要完整的 `Arguments` 结构 (由 `format_args!` 创建) 的情况下,这可以用作微优化; 在简单的格式化场景中使用 `Arguments` 的使用成本稍高一些。
    ///
    ///
    /// 目前不打算在标准库之外使用。
    ///
    #[unstable(feature = "fmt_internals", reason = "internal to standard library", issue = "none")]
    #[doc(hidden)]
    pub fn new(buf: &'a mut (dyn Write + 'a)) -> Formatter<'a> {
        Formatter {
            flags: 0,
            fill: ' ',
            align: rt::v1::Alignment::Unknown,
            width: None,
            precision: None,
            buf,
        }
    }
}

// NB.
// 参数本质上是优化的部分应用的格式化函数,等效于 `exists T.(&T, fn(&T, &mut Formatter<'_>) -> Result`。

extern "C" {
    type Opaque;
}

/// 该结构体表示 Xprintf 系列函数采用的泛型 "argument"。它包含一个用于格式化给定值的函数。
/// 在编译时,请确保函数和值具有正确的类型,然后使用此结构体将参数规范化为一种类型。
///
///
#[derive(Copy, Clone)]
#[allow(missing_debug_implementations)]
#[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
#[doc(hidden)]
pub struct ArgumentV1<'a> {
    value: &'a Opaque,
    formatter: fn(&Opaque, &mut Formatter<'_>) -> Result,
}

/// 这个结构体代表了构建 `Arguments` 的不安全性。
/// 它的存在,而不是一个不安全的函数,是为了简化 `format_args!(..)` 的扩展,并缩小 `unsafe` 块的作用域。
///
#[allow(missing_debug_implementations)]
#[doc(hidden)]
#[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
pub struct UnsafeArg {
    _private: (),
}

impl UnsafeArg {
    /// 请参见 `UnsafeArg` 的文档,需要知道何时可以安全地创建和使用 `UnsafeArg`。
    ///
    #[doc(hidden)]
    #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
    #[inline(always)]
    pub unsafe fn new() -> Self {
        Self { _private: () }
    }
}

// 这样可以确保格式基础结构中与 indices/counts 关联的函数指针具有单个稳定值。
//
// 请注意,这样定义的函数将是不正确的,因为该函数始终会被标记为 unnamed_addr,并且当前的状态会降低到 LLVM IR,因此它们的地址对于 LLVM 并不重要,因此 as_usize 强制转换可能会被错误编译。
//
// 在实践中,我们绝不会在未使用的包含数据上调用 as_usize (作为 formatting 参数的静态生成的问题),因此,这仅仅是一项额外的检查。
//
// 我们主要是要确保 `USIZE_MARKER` 处的函数指针具有对应于 *only* 的地址,该地址也将 `&usize` 作为它的第一个参数。
// 这里的 read_volatile 确保我们可以安全地从传递的引用中准备出 usize,并且此地址不指向未使用的接受函数。
//
//
//
//
//
//
//
#[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
static USIZE_MARKER: fn(&usize, &mut Formatter<'_>) -> Result = |ptr, _| {
    // SAFETY: ptr 是引用
    let _v: usize = unsafe { crate::ptr::read_volatile(ptr) };
    loop {}
};

impl<'a> ArgumentV1<'a> {
    #[doc(hidden)]
    #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
    pub fn new<'b, T>(x: &'b T, f: fn(&T, &mut Formatter<'_>) -> Result) -> ArgumentV1<'b> {
        // SAFETY: `mem::transmute(x)` 是安全的,因为
        //     1. `&'b T` 保持它起源于 `'b` 的生命周期 (以便没有无限的生命周期)
        //     2.
        //     `&'b T` 和 `&'b Opaque` 具有相同的内存布局 (当 `T` 是 `Sized` 时,就像这里一样) `mem::transmute(f)` 是安全的,因为 `fn(&T, &mut Formatter<'_>) -> Result` 和 `fn(&Opaque, &mut Formatter<'_>) -> Result` 具有相同的 ABI (只要 `T` 是 `Sized`)
        //
        //
        //
        //
        unsafe { ArgumentV1 { formatter: mem::transmute(f), value: mem::transmute(x) } }
    }

    #[doc(hidden)]
    #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
    pub fn from_usize(x: &usize) -> ArgumentV1<'_> {
        ArgumentV1::new(x, USIZE_MARKER)
    }

    fn as_usize(&self) -> Option<usize> {
        if self.formatter as usize == USIZE_MARKER as usize {
            // SAFETY: 仅当值是 usize 时,才将 `formatter` 字段设置为 USIZE_MARKER,因此这是安全的
            //
            Some(unsafe { *(self.value as *const _ as *const usize) })
        } else {
            None
        }
    }
}

// v1 格式 (format_args) 中可用的标志
#[derive(Copy, Clone)]
enum FlagV1 {
    SignPlus,
    SignMinus,
    Alternate,
    SignAwareZeroPad,
    DebugLowerHex,
    DebugUpperHex,
}

impl<'a> Arguments<'a> {
    /// 当使用 format_args! () 宏时,此函数用于生成参数结构体。
    ///
    #[doc(hidden)]
    #[inline]
    #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
    #[rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none")]
    pub const fn new_v1(pieces: &'a [&'static str], args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
        if pieces.len() < args.len() || pieces.len() > args.len() + 1 {
            panic!("invalid args");
        }
        Arguments { pieces, fmt: None, args }
    }

    /// 此函数用于指定非标准格式设置参数。
    ///
    /// `UnsafeArg` 是必需的,因为必须保持以下不变量,此函数才安全:
    ///
    /// 1. `pieces` 必须至少与 `fmt` 一样长。
    /// 2. `fmt` 中的每个 [`rt::v1::Argument::position`] 值都必须是 `args` 的有效索引。
    /// 3. `fmt` 中的每个 [`Count::Param`] 都必须包含一个有效的 `args` 索引。
    ///
    ///
    #[doc(hidden)]
    #[inline]
    #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
    #[rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none")]
    pub const fn new_v1_formatted(
        pieces: &'a [&'static str],
        args: &'a [ArgumentV1<'a>],
        fmt: &'a [rt::v1::Argument],
        _unsafe_arg: UnsafeArg,
    ) -> Arguments<'a> {
        Arguments { pieces, fmt: Some(fmt), args }
    }

    /// 估计格式化文本的长度。
    ///
    /// 当使用 `format!` 时,这旨在用于设置 `String` 的初始容量。
    /// Note: 这既不是下限也不是上限。
    #[doc(hidden)]
    #[inline]
    #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
    pub fn estimated_capacity(&self) -> usize {
        let pieces_length: usize = self.pieces.iter().map(|x| x.len()).sum();

        if self.args.is_empty() {
            pieces_length
        } else if !self.pieces.is_empty() && self.pieces[0].is_empty() && pieces_length < 16 {
            // 如果格式字符串以参数开头,则不要预分配任何内容,除非片段长度很大。
            //
            //
            0
        } else {
            // 有一些参数,因此任何其他推送都会重新分配字符串。
            //
            // 为避免这种情况,我们将此处的容量设置为 "pre-doubling"。
            pieces_length.checked_mul(2).unwrap_or(0)
        }
    }
}

/// 该结构体表示格式字符串及其参数的安全预编译版本。
/// 由于无法安全地完成此操作,因此无法在运行时生成该文件,因此未提供任何构造函数,并且该字段为私有字段以防止修改。
///
///
/// [`format_args!`] 宏将安全地创建此结构体的实例。
/// 宏在编译时验证格式字符串,因此可以安全地执行 [`write()`] 和 [`format()`] 函数的使用。
///
/// 您可以在 `Debug` 和 `Display` 上下文中使用 [`format_args!`] 返回的 `Arguments<'a>`,如下所示。
/// 该示例还显示 `Debug` 和 `Display` 的格式相同: `format_args!` 中的插值格式字符串。
///
/// ```rust
/// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
/// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
/// assert_eq!("1 foo 2", display);
/// assert_eq!(display, debug);
/// ```
///
/// [`format()`]: ../../std/fmt/fn.format.html
///
///
///
///
#[stable(feature = "rust1", since = "1.0.0")]
#[derive(Copy, Clone)]
pub struct Arguments<'a> {
    // 格式化要打印的字符串。
    pieces: &'a [&'static str],

    // 占位符规范,如果所有规范均为默认规范,则为 `None` (与 "{}{}" 相同)。
    fmt: Option<&'a [rt::v1::Argument]>,

    // 用于插值的动态参数,与字符串切片交织。
    // (每个参数前面都有一个字符串。)
    args: &'a [ArgumentV1<'a>],
}

impl<'a> Arguments<'a> {
    /// 获取格式化的字符串 (如果没有要格式化的参数)。
    ///
    /// 在最琐碎的情况下,这可以用来避免分配。
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::fmt::Arguments;
    ///
    /// fn write_str(_: &str) { /* ... */ }
    ///
    /// fn write_fmt(args: &Arguments) {
    ///     if let Some(s) = args.as_str() {
    ///         write_str(s)
    ///     } else {
    ///         write_str(&args.to_string());
    ///     }
    /// }
    /// ```
    ///
    /// ```rust
    /// assert_eq!(format_args!("hello").as_str(), Some("hello"));
    /// assert_eq!(format_args!("").as_str(), Some(""));
    /// assert_eq!(format_args!("{}", 1).as_str(), None);
    /// ```
    #[stable(feature = "fmt_as_str", since = "1.52.0")]
    #[rustc_const_unstable(feature = "const_arguments_as_str", issue = "none")]
    #[must_use]
    #[inline]
    pub const fn as_str(&self) -> Option<&'static str> {
        match (self.pieces, self.args) {
            ([], []) => Some(""),
            ([s], []) => Some(s),
            _ => None,
        }
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl Debug for Arguments<'_> {
    fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
        Display::fmt(self, fmt)
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl Display for Arguments<'_> {
    fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
        write(fmt.buf, *self)
    }
}

/// `?` 格式。
///
/// `Debug` 应该在面向程序员的调试上下文中格式化输出。
///
/// 一般来说,您应该只将 `derive` 和 `Debug` 实现。
///
/// 当与备用格式说明符 `#?` 一起使用时,输出将被漂亮地打印。
///
/// 有关格式化程序的更多信息,请参见 [模块级文档][module]。
///
/// [module]: ../../std/fmt/index.html
///
/// 如果所有字段都实现 `Debug`,则此 trait 可以与 `#[derive]` 一起使用。
/// 当为结构体 `derived' 时,它将使用 `struct` 的名称,然后是 `{`,然后是每个字段名称和 `Debug` 值的逗号分隔列表,然后是 `}`。
/// 对于 `enum`,它将使用变体的名称,如果适用,将使用 `(`,然后是字段的 `Debug` 值,然后是 `)`。
///
/// # Stability
///
/// 派生的 `Debug` 格式不稳定,因此 future Rust 版本可能会更改。
/// 此外,标准库提供的类型 (`libstd`,`libcore`,`liballoc` 等) 的 `Debug` 实现不稳定,并且可能随 future Rust 版本而改变。
///
///
/// # Examples
///
/// 派生实现:
///
/// ```
/// #[derive(Debug)]
/// struct Point {
///     x: i32,
///     y: i32,
/// }
///
/// let origin = Point { x: 0, y: 0 };
///
/// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");
/// ```
///
/// 手动实现:
///
/// ```
/// use std::fmt;
///
/// struct Point {
///     x: i32,
///     y: i32,
/// }
///
/// impl fmt::Debug for Point {
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         f.debug_struct("Point")
///          .field("x", &self.x)
///          .field("y", &self.y)
///          .finish()
///     }
/// }
///
/// let origin = Point { x: 0, y: 0 };
///
/// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");
/// ```
///
/// [`Formatter`] 结构体上有许多辅助方法可以帮助您实现手动实现,例如 [`debug_struct`]。
///
/// 使用 `derive` 或 [`Formatter`] 上的调试构建器 API 的 `Debug` 实现支持使用备用标志 `{:#?}` 的漂亮打印。
///
/// [`debug_struct`]: Formatter::debug_struct
///
/// 使用 `#?` 进行漂亮的打印:
///
/// ```
/// #[derive(Debug)]
/// struct Point {
///     x: i32,
///     y: i32,
/// }
///
/// let origin = Point { x: 0, y: 0 };
///
/// assert_eq!(format!("The origin is: {:#?}", origin),
/// "The origin is: Point {
///     x: 0,
///     y: 0,
/// }");
/// ```
///
///
///
///
///

#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_on_unimplemented(
    on(
        crate_local,
        label = "`{Self}` cannot be formatted using `{{:?}}`",
        note = "add `#[derive(Debug)]` to `{Self}` or manually `impl {Debug} for {Self}`"
    ),
    message = "`{Self}` doesn't implement `{Debug}`",
    label = "`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`"
)]
#[doc(alias = "{:?}")]
#[rustc_diagnostic_item = "Debug"]
#[rustc_trivial_field_reads]
pub trait Debug {
    /// 使用给定的格式化程序格式化该值。
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// struct Position {
    ///     longitude: f32,
    ///     latitude: f32,
    /// }
    ///
    /// impl fmt::Debug for Position {
    ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    ///         f.debug_tuple("")
    ///          .field(&self.longitude)
    ///          .field(&self.latitude)
    ///          .finish()
    ///     }
    /// }
    ///
    /// let position = Position { longitude: 1.987, latitude: 2.983 };
    /// assert_eq!(format!("{:?}", position), "(1.987, 2.983)");
    ///
    /// assert_eq!(format!("{:#?}", position), "(
    ///     1.987,
    ///     2.983,
    /// )");
    /// ```
    #[stable(feature = "rust1", since = "1.0.0")]
    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
}

// 单独的模块,用于从 prelude 重导出 `Debug` 宏,而无需 `Debug` trait。
pub(crate) mod macros {
    /// 派生宏,生成 `Debug` trait 的 impl。
    #[rustc_builtin_macro]
    #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
    #[allow_internal_unstable(core_intrinsics)]
    pub macro Debug($item:item) {
        /* compiler built-in */
    }
}
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
#[doc(inline)]
pub use macros::Debug;

/// 空格式的格式 trait,`{}`。
///
/// `Display` 与 [`Debug`] 类似,但 `Display` 是面向用户的输出,因此无法导出。
///
///
/// 有关格式化程序的更多信息,请参见 [模块级文档][module]。
///
/// [module]: ../../std/fmt/index.html
///
/// # Examples
///
/// 在类型上实现 `Display`:
///
/// ```
/// use std::fmt;
///
/// struct Point {
///     x: i32,
///     y: i32,
/// }
///
/// impl fmt::Display for Point {
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         write!(f, "({}, {})", self.x, self.y)
///     }
/// }
///
/// let origin = Point { x: 0, y: 0 };
///
/// assert_eq!(format!("The origin is: {}", origin), "The origin is: (0, 0)");
/// ```
#[rustc_on_unimplemented(
    on(
        _Self = "std::path::Path",
        label = "`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
        note = "call `.display()` or `.to_string_lossy()` to safely print paths, \
                as they may contain non-Unicode data"
    ),
    message = "`{Self}` doesn't implement `{Display}`",
    label = "`{Self}` cannot be formatted with the default formatter",
    note = "in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead"
)]
#[doc(alias = "{}")]
#[rustc_diagnostic_item = "Display"]
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Display {
    /// 使用给定的格式化程序格式化该值。
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// struct Position {
    ///     longitude: f32,
    ///     latitude: f32,
    /// }
    ///
    /// impl fmt::Display for Position {
    ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    ///         write!(f, "({}, {})", self.longitude, self.latitude)
    ///     }
    /// }
    ///
    /// assert_eq!("(1.987, 2.983)",
    ///            format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
    /// ```
    #[stable(feature = "rust1", since = "1.0.0")]
    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
}

/// `o` 格式。
///
/// `Octal` trait 应该将其输出格式化为 base-8 中的数字。
///
/// 对于原始有符号整数 (`i8` 至 `i128` 和 `isize`),负值的格式设置为二进制补码表示形式。
///
///
/// 备用标志 `#` 在输出前面添加 `0o`。
///
/// 有关格式化程序的更多信息,请参见 [模块级文档][module]。
///
/// [module]: ../../std/fmt/index.html
///
/// # Examples
///
/// `i32` 的基本用法:
///
/// ```
/// let x = 42; // 42 是八进制的 '52'
///
/// assert_eq!(format!("{:o}", x), "52");
/// assert_eq!(format!("{:#o}", x), "0o52");
///
/// assert_eq!(format!("{:o}", -16), "37777777760");
/// ```
///
/// 在类型上实现 `Octal`:
///
/// ```
/// use std::fmt;
///
/// struct Length(i32);
///
/// impl fmt::Octal for Length {
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         let val = self.0;
///
///         fmt::Octal::fmt(&val, f) // 委托给 i32 的实现
///     }
/// }
///
/// let l = Length(9);
///
/// assert_eq!(format!("l as octal is: {:o}", l), "l as octal is: 11");
///
/// assert_eq!(format!("l as octal is: {:#06o}", l), "l as octal is: 0o0011");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Octal {
    /// 使用给定的格式化程序格式化该值。
    #[stable(feature = "rust1", since = "1.0.0")]
    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
}

/// `b` 格式。
///
/// `Binary` trait 应该将其输出格式化为二进制格式的数字。
///
/// 对于原始有符号整数 ([`i8`] 至 [`i128`] 和 [`isize`]),负值的格式设置为二进制补码表示形式。
///
///
/// 备用标志 `#` 在输出前面添加 `0b`。
///
/// 有关格式化程序的更多信息,请参见 [模块级文档][module]。
///
/// [module]: ../../std/fmt/index.html
///
/// # Examples
///
/// [`i32`] 的基本用法:
///
/// ```
/// let x = 42; // 42 是 '101010' 二进制
///
/// assert_eq!(format!("{:b}", x), "101010");
/// assert_eq!(format!("{:#b}", x), "0b101010");
///
/// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
/// ```
///
/// 在类型上实现 `Binary`:
///
/// ```
/// use std::fmt;
///
/// struct Length(i32);
///
/// impl fmt::Binary for Length {
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         let val = self.0;
///
///         fmt::Binary::fmt(&val, f) // 委托给 i32 的实现
///     }
/// }
///
/// let l = Length(107);
///
/// assert_eq!(format!("l as binary is: {:b}", l), "l as binary is: 1101011");
///
/// assert_eq!(
///     format!("l as binary is: {:#032b}", l),
///     "l as binary is: 0b000000000000000000000001101011"
/// );
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Binary {
    /// 使用给定的格式化程序格式化该值。
    #[stable(feature = "rust1", since = "1.0.0")]
    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
}

/// `x` 格式。
///
/// `LowerHex` trait 应该将其输出格式设置为十六进制数字,其中 `a` 至 `f` 为小写形式。
///
/// 对于原始有符号整数 (`i8` 至 `i128` 和 `isize`),负值的格式设置为二进制补码表示形式。
///
///
/// 备用标志 `#` 在输出前面添加 `0x`。
///
/// 有关格式化程序的更多信息,请参见 [模块级文档][module]。
///
/// [module]: ../../std/fmt/index.html
///
/// # Examples
///
/// `i32` 的基本用法:
///
/// ```
/// let x = 42; // 42 是十六进制的 '2a'
///
/// assert_eq!(format!("{:x}", x), "2a");
/// assert_eq!(format!("{:#x}", x), "0x2a");
///
/// assert_eq!(format!("{:x}", -16), "fffffff0");
/// ```
///
/// 在类型上实现 `LowerHex`:
///
/// ```
/// use std::fmt;
///
/// struct Length(i32);
///
/// impl fmt::LowerHex for Length {
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         let val = self.0;
///
///         fmt::LowerHex::fmt(&val, f) // 委托给 i32 的实现
///     }
/// }
///
/// let l = Length(9);
///
/// assert_eq!(format!("l as hex is: {:x}", l), "l as hex is: 9");
///
/// assert_eq!(format!("l as hex is: {:#010x}", l), "l as hex is: 0x00000009");
/// ```
///
#[stable(feature = "rust1", since = "1.0.0")]
pub trait LowerHex {
    /// 使用给定的格式化程序格式化该值。
    #[stable(feature = "rust1", since = "1.0.0")]
    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
}

/// `X` 格式。
///
/// `UpperHex` trait 应该将其输出格式设置为十六进制数字,其中 `A` 至 `F` 为大写形式。
///
/// 对于原始有符号整数 (`i8` 至 `i128` 和 `isize`),负值的格式设置为二进制补码表示形式。
///
///
/// 备用标志 `#` 在输出前面添加 `0x`。
///
/// 有关格式化程序的更多信息,请参见 [模块级文档][module]。
///
/// [module]: ../../std/fmt/index.html
///
/// # Examples
///
/// `i32` 的基本用法:
///
/// ```
/// let x = 42; // 42 是十六进制的 '2A'
///
/// assert_eq!(format!("{:X}", x), "2A");
/// assert_eq!(format!("{:#X}", x), "0x2A");
///
/// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
/// ```
///
/// 在类型上实现 `UpperHex`:
///
/// ```
/// use std::fmt;
///
/// struct Length(i32);
///
/// impl fmt::UpperHex for Length {
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         let val = self.0;
///
///         fmt::UpperHex::fmt(&val, f) // 委托给 i32 的实现
///     }
/// }
///
/// let l = Length(i32::MAX);
///
/// assert_eq!(format!("l as hex is: {:X}", l), "l as hex is: 7FFFFFFF");
///
/// assert_eq!(format!("l as hex is: {:#010X}", l), "l as hex is: 0x7FFFFFFF");
/// ```
///
#[stable(feature = "rust1", since = "1.0.0")]
pub trait UpperHex {
    /// 使用给定的格式化程序格式化该值。
    #[stable(feature = "rust1", since = "1.0.0")]
    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
}

/// `p` 格式。
///
/// `Pointer` trait 应该将其输出格式化为存储位置。
/// 通常以十六进制表示。
///
/// 有关格式化程序的更多信息,请参见 [模块级文档][module]。
///
/// [module]: ../../std/fmt/index.html
///
/// # Examples
///
/// `&i32` 的基本用法:
///
/// ```
/// let x = &42;
///
/// let address = format!("{:p}", x); // 这会产生类似 '0x7f06092ac6d0' 的东西
/// ```
///
/// 在类型上实现 `Pointer`:
///
/// ```
/// use std::fmt;
///
/// struct Length(i32);
///
/// impl fmt::Pointer for Length {
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         // 使用 `as` 转换为 `*const T`,该 `*const T` 实现了 Pointer,我们可以使用它
///
///         let ptr = self as *const Self;
///         fmt::Pointer::fmt(&ptr, f)
///     }
/// }
///
/// let l = Length(42);
///
/// println!("l is in memory here: {:p}", l);
///
/// let l_ptr = format!("{:018p}", l);
/// assert_eq!(l_ptr.len(), 18);
/// assert_eq!(&l_ptr[..2], "0x");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_diagnostic_item = "Pointer"]
pub trait Pointer {
    /// 使用给定的格式化程序格式化该值。
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_diagnostic_item = "pointer_trait_fmt"]
    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
}

/// `e` 格式。
///
/// `LowerExp` trait 应该使用小写的 `e` 以科学计数法格式化其输出。
///
/// 有关格式化程序的更多信息,请参见 [模块级文档][module]。
///
/// [module]: ../../std/fmt/index.html
///
/// # Examples
///
/// `f64` 的基本用法:
///
/// ```
/// let x = 42.0; // 42.0 是 '4.2e1' 的科学计数形式
///
/// assert_eq!(format!("{:e}", x), "4.2e1");
/// ```
///
/// 在类型上实现 `LowerExp`:
///
/// ```
/// use std::fmt;
///
/// struct Length(i32);
///
/// impl fmt::LowerExp for Length {
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         let val = f64::from(self.0);
///         fmt::LowerExp::fmt(&val, f) // 委托 f64 的实现
///     }
/// }
///
/// let l = Length(100);
///
/// assert_eq!(
///     format!("l in scientific notation is: {:e}", l),
///     "l in scientific notation is: 1e2"
/// );
///
/// assert_eq!(
///     format!("l in scientific notation is: {:05e}", l),
///     "l in scientific notation is: 001e2"
/// );
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub trait LowerExp {
    /// 使用给定的格式化程序格式化该值。
    #[stable(feature = "rust1", since = "1.0.0")]
    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
}

/// `E` 格式。
///
/// `UpperExp` trait 应该使用大写的 `E` 以科学计数法格式化其输出。
///
/// 有关格式化程序的更多信息,请参见 [模块级文档][module]。
///
/// [module]: ../../std/fmt/index.html
///
/// # Examples
///
/// `f64` 的基本用法:
///
/// ```
/// let x = 42.0; // 42.0 是 '4.2E1' 的科学计数形式
///
/// assert_eq!(format!("{:E}", x), "4.2E1");
/// ```
///
/// 在类型上实现 `UpperExp`:
///
/// ```
/// use std::fmt;
///
/// struct Length(i32);
///
/// impl fmt::UpperExp for Length {
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         let val = f64::from(self.0);
///         fmt::UpperExp::fmt(&val, f) // 委托 f64 的实现
///     }
/// }
///
/// let l = Length(100);
///
/// assert_eq!(
///     format!("l in scientific notation is: {:E}", l),
///     "l in scientific notation is: 1E2"
/// );
///
/// assert_eq!(
///     format!("l in scientific notation is: {:05E}", l),
///     "l in scientific notation is: 001E2"
/// );
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub trait UpperExp {
    /// 使用给定的格式化程序格式化该值。
    #[stable(feature = "rust1", since = "1.0.0")]
    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
}

/// `write` 函数接受一个输出流,以及一个可以与 `format_args!` 宏预编译的 `Arguments` 结构体。
///
///
/// 参数将根据指定的格式字符串格式化为提供的输出流。
///
/// # Examples
///
/// 基本用法:
///
/// ```
/// use std::fmt;
///
/// let mut output = String::new();
/// fmt::write(&mut output, format_args!("Hello {}!", "world"))
///     .expect("Error occurred while trying to write in String");
/// assert_eq!(output, "Hello world!");
/// ```
///
/// 请注意,使用 [`write!`] 可能更可取。Example:
///
/// ```
/// use std::fmt::Write;
///
/// let mut output = String::new();
/// write!(&mut output, "Hello {}!", "world")
///     .expect("Error occurred while trying to write in String");
/// assert_eq!(output, "Hello world!");
/// ```
///
/// [`write!`]: crate::write!
///
#[stable(feature = "rust1", since = "1.0.0")]
pub fn write(output: &mut dyn Write, args: Arguments<'_>) -> Result {
    let mut formatter = Formatter::new(output);
    let mut idx = 0;

    match args.fmt {
        None => {
            // 我们可以对所有参数使用默认格式设置参数。
            for (i, arg) in args.args.iter().enumerate() {
                // SAFETY: args.args 和 args.pieces 来自同一个参数,保证索引总是在限定范围内。
                //
                let piece = unsafe { args.pieces.get_unchecked(i) };
                if !piece.is_empty() {
                    formatter.buf.write_str(*piece)?;
                }
                (arg.formatter)(arg.value, &mut formatter)?;
                idx += 1;
            }
        }
        Some(fmt) => {
            // 每个规范都有一个对应的参数,该参数后有一个字符串。
            //
            for (i, arg) in fmt.iter().enumerate() {
                // SAFETY: fmt 和 args.pieces 来自同一个 参数,保证索引总是在限定范围内。
                //
                let piece = unsafe { args.pieces.get_unchecked(i) };
                if !piece.is_empty() {
                    formatter.buf.write_str(*piece)?;
                }
                // SAFETY: arg 和 args.args 来自相同的参数,从而确保索引始终在范围之内。
                //
                unsafe { run(&mut formatter, arg, args.args) }?;
                idx += 1;
            }
        }
    }

    // 只能剩下一个尾随的字符串切片。
    if let Some(piece) = args.pieces.get(idx) {
        formatter.buf.write_str(*piece)?;
    }

    Ok(())
}

unsafe fn run(fmt: &mut Formatter<'_>, arg: &rt::v1::Argument, args: &[ArgumentV1<'_>]) -> Result {
    fmt.fill = arg.format.fill;
    fmt.align = arg.format.align;
    fmt.flags = arg.format.flags;
    // SAFETY: arg 和 args 来自相同的参数,从而确保索引始终在范围之内。
    //
    unsafe {
        fmt.width = getcount(args, &arg.format.width);
        fmt.precision = getcount(args, &arg.format.precision);
    }

    // 提取正确的参数
    debug_assert!(arg.position < args.len());
    // SAFETY: arg 和 args 来自相同的参数,从而确保其索引始终在范围之内。
    //
    let value = unsafe { args.get_unchecked(arg.position) };

    // 然后实际做一些打印
    (value.formatter)(value.value, fmt)
}

unsafe fn getcount(args: &[ArgumentV1<'_>], cnt: &rt::v1::Count) -> Option<usize> {
    match *cnt {
        rt::v1::Count::Is(n) => Some(n),
        rt::v1::Count::Implied => None,
        rt::v1::Count::Param(i) => {
            debug_assert!(i < args.len());
            // SAFETY: cnt 和 args 来自相同的参数,这确保此索引始终在范围之内。
            //
            unsafe { args.get_unchecked(i).as_usize() }
        }
    }
}

/// 结束后填充。由 `Formatter::padding` 返回。
#[must_use = "don't forget to write the post padding"]
pub(crate) struct PostPadding {
    fill: char,
    padding: usize,
}

impl PostPadding {
    fn new(fill: char, padding: usize) -> PostPadding {
        PostPadding { fill, padding }
    }

    /// 写这篇文章补充。
    pub(crate) fn write(self, f: &mut Formatter<'_>) -> Result {
        for _ in 0..self.padding {
            f.buf.write_char(self.fill)?;
        }
        Ok(())
    }
}

impl<'a> Formatter<'a> {
    fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
    where
        'b: 'c,
        F: FnOnce(&'b mut (dyn Write + 'b)) -> &'c mut (dyn Write + 'c),
    {
        Formatter {
            // 我们要改变这个
            buf: wrap(self.buf),

            // 并保留这些
            flags: self.flags,
            fill: self.fill,
            align: self.align,
            width: self.width,
            precision: self.precision,
        }
    }

    // 用于填充和处理格式化参数的辅助方法,所有格式化 traits 都可以使用。
    //

    /// 对已经发出到 str 中的整数执行正确的填充。
    /// str *不应* 包含整数的符号,该符号将通过此方法添加。
    ///
    /// # Arguments
    ///
    /// * is_nonnegative - 原始整数是正数还是零。
    /// * prefix - 如果提供了 '#' 字符 (Alternate),则这是放在数字前面的前缀。
    ///
    /// * buf - 数字已格式化为的字节数组
    ///
    /// 此函数将正确说明提供的标志以及最小宽度。
    /// 它不会考虑精度。
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// struct Foo { nb: i32 }
    ///
    /// impl Foo {
    ///     fn new(nb: i32) -> Foo {
    ///         Foo {
    ///             nb,
    ///         }
    ///     }
    /// }
    ///
    /// impl fmt::Display for Foo {
    ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
    ///         // 我们需要从数字输出中删除 "-"。
    ///         let tmp = self.nb.abs().to_string();
    ///
    ///         formatter.pad_integral(self.nb >= 0, "Foo ", &tmp)
    ///     }
    /// }
    ///
    /// assert_eq!(&format!("{}", Foo::new(2)), "2");
    /// assert_eq!(&format!("{}", Foo::new(-1)), "-1");
    /// assert_eq!(&format!("{}", Foo::new(0)), "0");
    /// assert_eq!(&format!("{:#}", Foo::new(-1)), "-Foo 1");
    /// assert_eq!(&format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
    /// ```
    ///
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn pad_integral(&mut self, is_nonnegative: bool, prefix: &str, buf: &str) -> Result {
        let mut width = buf.len();

        let mut sign = None;
        if !is_nonnegative {
            sign = Some('-');
            width += 1;
        } else if self.sign_plus() {
            sign = Some('+');
            width += 1;
        }

        let prefix = if self.alternate() {
            width += prefix.chars().count();
            Some(prefix)
        } else {
            None
        };

        // 写入符号 (如果存在),然后写入前缀 (如果已请求)
        #[inline(never)]
        fn write_prefix(f: &mut Formatter<'_>, sign: Option<char>, prefix: Option<&str>) -> Result {
            if let Some(c) = sign {
                f.buf.write_char(c)?;
            }
            if let Some(prefix) = prefix { f.buf.write_str(prefix) } else { Ok(()) }
        }

        // 此时,`width` 字段更多是 `min-width` 参数。
        match self.width {
            // 如果没有最小长度要求,那么我们可以写字节。
            //
            None => {
                write_prefix(self, sign, prefix)?;
                self.buf.write_str(buf)
            }
            // 检查是否超过最小宽度,如果是,那么我们也可以只写字节。
            //
            Some(min) if width >= min => {
                write_prefix(self, sign, prefix)?;
                self.buf.write_str(buf)
            }
            // 如果填充字符为零,则符号和前缀位于填充之前
            //
            Some(min) if self.sign_aware_zero_pad() => {
                let old_fill = crate::mem::replace(&mut self.fill, '0');
                let old_align = crate::mem::replace(&mut self.align, rt::v1::Alignment::Right);
                write_prefix(self, sign, prefix)?;
                let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
                self.buf.write_str(buf)?;
                post_padding.write(self)?;
                self.fill = old_fill;
                self.align = old_align;
                Ok(())
            }
            // 否则,符号和前缀在填充之后
            Some(min) => {
                let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
                write_prefix(self, sign, prefix)?;
                self.buf.write_str(buf)?;
                post_padding.write(self)
            }
        }
    }

    /// 应用指定的相关格式设置标志后,此函数将获取一个字符串切片并将其发送到内部缓冲区。
    /// 泛型字符串可识别的标志为:
    ///
    /// * width - 发射的最小宽度
    /// * fill/align - 如果需要填充提供的字符串,要发出什么以及在哪里发出
    /// * precision - 发出的最大长度,如果字符串长于该长度,则字符串将被截断
    ///
    /// 值得注意的是,此函数将忽略 `flag` 参数。
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// struct Foo;
    ///
    /// impl fmt::Display for Foo {
    ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
    ///         formatter.pad("Foo")
    ///     }
    /// }
    ///
    /// assert_eq!(&format!("{:<4}", Foo), "Foo ");
    /// assert_eq!(&format!("{:0>4}", Foo), "0Foo");
    /// ```
    ///
    ///
    ///
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn pad(&mut self, s: &str) -> Result {
        // 确保前面有一条快速路
        if self.width.is_none() && self.precision.is_none() {
            return self.buf.write_str(s);
        }
        // 对于要格式化的字符串,`precision` 字段可以解释为 `max-width`。
        //
        let s = if let Some(max) = self.precision {
            // 如果我们的字符串比精度更长,那么我们必须将其截断。
            // 但是,其他标志 (例如 `fill`,`width` 和 `align`) 必须照常运行。
            //
            if let Some((i, _)) = s.char_indices().nth(max) {
                // 此处的 LLVM 不能证明 `..i` 不会 panic `&s[..i]`,但是我们知道它不能 panic。
                // 使用 `get` + `unwrap_or` 避免使用 `unsafe`,否则请不要在此处发出任何与 panic 相关的代码。
                //
                //
                s.get(..i).unwrap_or(s)
            } else {
                &s
            }
        } else {
            &s
        };
        // 此时,`width` 字段更多是 `min-width` 参数。
        match self.width {
            // 如果我们在最大长度以下,并且没有最小长度要求,那么我们就可以发出字符串
            //
            None => self.buf.write_str(s),
            Some(width) => {
                let chars_count = s.chars().count();
                // 如果我们在最大宽度之下,请检查我们是否在最小宽度之上,如果是,那么就和发出字符串一样容易。
                //
                if chars_count >= width {
                    self.buf.write_str(s)
                }
                // 如果我们同时处于最大和最小宽度之下,则使用指定的字符串 + 某些对齐方式来填充最小宽度。
                //
                else {
                    let align = rt::v1::Alignment::Left;
                    let post_padding = self.padding(width - chars_count, align)?;
                    self.buf.write_str(s)?;
                    post_padding.write(self)
                }
            }
        }
    }

    /// 编写前填充并返回未写的后填充。
    /// 调用者有责任确保在填充内容之后编写填充后的内容。
    ///
    pub(crate) fn padding(
        &mut self,
        padding: usize,
        default: rt::v1::Alignment,
    ) -> result::Result<PostPadding, Error> {
        let align = match self.align {
            rt::v1::Alignment::Unknown => default,
            _ => self.align,
        };

        let (pre_pad, post_pad) = match align {
            rt::v1::Alignment::Left => (0, padding),
            rt::v1::Alignment::Right | rt::v1::Alignment::Unknown => (padding, 0),
            rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
        };

        for _ in 0..pre_pad {
            self.buf.write_char(self.fill)?;
        }

        Ok(PostPadding::new(self.fill, post_pad))
    }

    /// 取出格式化的部分并应用填充。
    /// 假定调用者已经以所需的精度渲染了零件,因此可以忽略 `self.precision`。
    ///
    fn pad_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
        if let Some(mut width) = self.width {
            // 对于可识别符号的零填充,我们首先渲染符号,然后从一开始就表现为没有符号。
            //
            let mut formatted = formatted.clone();
            let old_fill = self.fill;
            let old_align = self.align;
            let mut align = old_align;
            if self.sign_aware_zero_pad() {
                // 符号总是最先
                let sign = formatted.sign;
                self.buf.write_str(sign)?;

                // 从格式化部分中删除符号
                formatted.sign = "";
                width = width.saturating_sub(sign.len());
                align = rt::v1::Alignment::Right;
                self.fill = '0';
                self.align = rt::v1::Alignment::Right;
            }

            // 其余部分则经过普通的填充过程。
            let len = formatted.len();
            let ret = if width <= len {
                // 没有填充
                self.write_formatted_parts(&formatted)
            } else {
                let post_padding = self.padding(width - len, align)?;
                self.write_formatted_parts(&formatted)?;
                post_padding.write(self)
            };
            self.fill = old_fill;
            self.align = old_align;
            ret
        } else {
            // 这是常见的情况,我们采取捷径
            self.write_formatted_parts(formatted)
        }
    }

    fn write_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
        fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
            // SAFETY: 这用于 `numfmt::Part::Num` 和 `numfmt::Part::Copy`。
            // 用于 `numfmt::Part::Num` 是安全的,因为每个字符 `c` 都在 `b'0'` 和 `b'9'` 之间,这意味着 `s` 是有效的 UTF-8。
            // 在实践中使用 `numfmt::Part::Copy(buf)` 也可能是安全的,因为 `buf` 应该是纯 ASCII,但有人可能会将 `buf` 的错误值传递给 `numfmt::to_shortest_str`,因为它是一个公共函数。
            //
            // FIXME: 确定这是否会导致 UB。
            //
            //
            //
            buf.write_str(unsafe { str::from_utf8_unchecked(s) })
        }

        if !formatted.sign.is_empty() {
            self.buf.write_str(formatted.sign)?;
        }
        for part in formatted.parts {
            match *part {
                numfmt::Part::Zero(mut nzeroes) => {
                    const ZEROES: &str = // 64 个零
                        "0000000000000000000000000000000000000000000000000000000000000000";
                    while nzeroes > ZEROES.len() {
                        self.buf.write_str(ZEROES)?;
                        nzeroes -= ZEROES.len();
                    }
                    if nzeroes > 0 {
                        self.buf.write_str(&ZEROES[..nzeroes])?;
                    }
                }
                numfmt::Part::Num(mut v) => {
                    let mut s = [0; 5];
                    let len = part.len();
                    for c in s[..len].iter_mut().rev() {
                        *c = b'0' + (v % 10) as u8;
                        v /= 10;
                    }
                    write_bytes(self.buf, &s[..len])?;
                }
                numfmt::Part::Copy(buf) => {
                    write_bytes(self.buf, buf)?;
                }
            }
        }
        Ok(())
    }

    /// 将一些数据写入此格式化程序中包含的底层缓冲区。
    ///
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// struct Foo;
    ///
    /// impl fmt::Display for Foo {
    ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
    ///         formatter.write_str("Foo")
    ///         // 这相当于:
    ///         // write!(formatter, "Foo")
    ///     }
    /// }
    ///
    /// assert_eq!(&format!("{}", Foo), "Foo");
    /// assert_eq!(&format!("{:0>8}", Foo), "Foo");
    /// ```
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn write_str(&mut self, data: &str) -> Result {
        self.buf.write_str(data)
    }

    /// 将一些格式化的信息写入此实例。
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// struct Foo(i32);
    ///
    /// impl fmt::Display for Foo {
    ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
    ///         formatter.write_fmt(format_args!("Foo {}", self.0))
    ///     }
    /// }
    ///
    /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1");
    /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2");
    /// ```
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
        write(self.buf, fmt)
    }

    /// 格式化标志
    #[must_use]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_deprecated(
        since = "1.24.0",
        reason = "use the `sign_plus`, `sign_minus`, `alternate`, \
                  or `sign_aware_zero_pad` methods instead"
    )]
    pub fn flags(&self) -> u32 {
        self.flags
    }

    /// 对齐时用作 'fill' 的字符。
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// struct Foo;
    ///
    /// impl fmt::Display for Foo {
    ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
    ///         let c = formatter.fill();
    ///         if let Some(width) = formatter.width() {
    ///             for _ in 0..width {
    ///                 write!(formatter, "{}", c)?;
    ///             }
    ///             Ok(())
    ///         } else {
    ///             write!(formatter, "{}", c)
    ///         }
    ///     }
    /// }
    ///
    /// // 我们使用 ">" 在右边设置对齐方式。
    /// assert_eq!(&format!("{:G>3}", Foo), "GGG");
    /// assert_eq!(&format!("{:t>6}", Foo), "tttttt");
    /// ```
    #[must_use]
    #[stable(feature = "fmt_flags", since = "1.5.0")]
    pub fn fill(&self) -> char {
        self.fill
    }

    /// 指示请求对齐方式的标志。
    ///
    /// # Examples
    ///
    /// ```
    /// extern crate core;
    ///
    /// use std::fmt::{self, Alignment};
    ///
    /// struct Foo;
    ///
    /// impl fmt::Display for Foo {
    ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
    ///         let s = if let Some(s) = formatter.align() {
    ///             match s {
    ///                 Alignment::Left    => "left",
    ///                 Alignment::Right   => "right",
    ///                 Alignment::Center  => "center",
    ///             }
    ///         } else {
    ///             "into the void"
    ///         };
    ///         write!(formatter, "{}", s)
    ///     }
    /// }
    ///
    /// assert_eq!(&format!("{:<}", Foo), "left");
    /// assert_eq!(&format!("{:>}", Foo), "right");
    /// assert_eq!(&format!("{:^}", Foo), "center");
    /// assert_eq!(&format!("{}", Foo), "into the void");
    /// ```
    #[must_use]
    #[stable(feature = "fmt_flags_align", since = "1.28.0")]
    pub fn align(&self) -> Option<Alignment> {
        match self.align {
            rt::v1::Alignment::Left => Some(Alignment::Left),
            rt::v1::Alignment::Right => Some(Alignment::Right),
            rt::v1::Alignment::Center => Some(Alignment::Center),
            rt::v1::Alignment::Unknown => None,
        }
    }

    /// (可选) 指定输出应为的整数宽度。
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// struct Foo(i32);
    ///
    /// impl fmt::Display for Foo {
    ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
    ///         if let Some(width) = formatter.width() {
    ///             // 如果我们收到一个宽度,我们就用它
    ///             write!(formatter, "{:width$}", &format!("Foo({})", self.0), width = width)
    ///         } else {
    ///             // 否则我们没什么特别的
    ///             write!(formatter, "Foo({})", self.0)
    ///         }
    ///     }
    /// }
    ///
    /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23)   ");
    /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
    /// ```
    #[must_use]
    #[stable(feature = "fmt_flags", since = "1.5.0")]
    pub fn width(&self) -> Option<usize> {
        self.width
    }

    /// 可选地为数字类型指定精度。
    /// 或者,为字符串类型的最大宽度。
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// struct Foo(f32);
    ///
    /// impl fmt::Display for Foo {
    ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
    ///         if let Some(precision) = formatter.precision() {
    ///             // 如果我们收到了精度,我们就会使用它。
    ///             write!(formatter, "Foo({1:.*})", precision, self.0)
    ///         } else {
    ///             // 否则,我们默认为 2。
    ///             write!(formatter, "Foo({:.2})", self.0)
    ///         }
    ///     }
    /// }
    ///
    /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
    /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
    /// ```
    #[must_use]
    #[stable(feature = "fmt_flags", since = "1.5.0")]
    pub fn precision(&self) -> Option<usize> {
        self.precision
    }

    /// 确定是否指定了 `+` 标志。
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// struct Foo(i32);
    ///
    /// impl fmt::Display for Foo {
    ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
    ///         if formatter.sign_plus() {
    ///             write!(formatter,
    ///                    "Foo({}{})",
    ///                    if self.0 < 0 { '-' } else { '+' },
    ///                    self.0)
    ///         } else {
    ///             write!(formatter, "Foo({})", self.0)
    ///         }
    ///     }
    /// }
    ///
    /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
    /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
    /// ```
    #[must_use]
    #[stable(feature = "fmt_flags", since = "1.5.0")]
    pub fn sign_plus(&self) -> bool {
        self.flags & (1 << FlagV1::SignPlus as u32) != 0
    }

    /// 确定是否指定了 `-` 标志。
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// struct Foo(i32);
    ///
    /// impl fmt::Display for Foo {
    ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
    ///         if formatter.sign_minus() {
    ///             // 您想要一个减号? 有一个!
    ///             write!(formatter, "-Foo({})", self.0)
    ///         } else {
    ///             write!(formatter, "Foo({})", self.0)
    ///         }
    ///     }
    /// }
    ///
    /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
    /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
    /// ```
    #[must_use]
    #[stable(feature = "fmt_flags", since = "1.5.0")]
    pub fn sign_minus(&self) -> bool {
        self.flags & (1 << FlagV1::SignMinus as u32) != 0
    }

    /// 确定是否指定了 `#` 标志。
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// struct Foo(i32);
    ///
    /// impl fmt::Display for Foo {
    ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
    ///         if formatter.alternate() {
    ///             write!(formatter, "Foo({})", self.0)
    ///         } else {
    ///             write!(formatter, "{}", self.0)
    ///         }
    ///     }
    /// }
    ///
    /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
    /// assert_eq!(&format!("{}", Foo(23)), "23");
    /// ```
    #[must_use]
    #[stable(feature = "fmt_flags", since = "1.5.0")]
    pub fn alternate(&self) -> bool {
        self.flags & (1 << FlagV1::Alternate as u32) != 0
    }

    /// 确定是否指定了 `0` 标志。
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// struct Foo(i32);
    ///
    /// impl fmt::Display for Foo {
    ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
    ///         assert!(formatter.sign_aware_zero_pad());
    ///         assert_eq!(formatter.width(), Some(4));
    ///         // 我们忽略格式化程序的选项。
    ///         write!(formatter, "{}", self.0)
    ///     }
    /// }
    ///
    /// assert_eq!(&format!("{:04}", Foo(23)), "23");
    /// ```
    #[must_use]
    #[stable(feature = "fmt_flags", since = "1.5.0")]
    pub fn sign_aware_zero_pad(&self) -> bool {
        self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
    }

    // FIXME: 确定我们要为这两个标志使用的公共 API。
    // https://github.com/rust-lang/rust/issues/48584
    fn debug_lower_hex(&self) -> bool {
        self.flags & (1 << FlagV1::DebugLowerHex as u32) != 0
    }

    fn debug_upper_hex(&self) -> bool {
        self.flags & (1 << FlagV1::DebugUpperHex as u32) != 0
    }

    /// 创建一个 [`DebugStruct`] 构建器,该构建器旨在帮助创建结构体的 [`fmt::Debug`] 实现。
    ///
    ///
    /// [`fmt::Debug`]: self::Debug
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::fmt;
    /// use std::net::Ipv4Addr;
    ///
    /// struct Foo {
    ///     bar: i32,
    ///     baz: String,
    ///     addr: Ipv4Addr,
    /// }
    ///
    /// impl fmt::Debug for Foo {
    ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
    ///         fmt.debug_struct("Foo")
    ///             .field("bar", &self.bar)
    ///             .field("baz", &self.baz)
    ///             .field("addr", &format_args!("{}", self.addr))
    ///             .finish()
    ///     }
    /// }
    ///
    /// assert_eq!(
    ///     "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
    ///     format!("{:?}", Foo {
    ///         bar: 10,
    ///         baz: "Hello World".to_string(),
    ///         addr: Ipv4Addr::new(127, 0, 0, 1),
    ///     })
    /// );
    /// ```
    #[stable(feature = "debug_builders", since = "1.2.0")]
    pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
        builders::debug_struct_new(self, name)
    }

    /// 创建一个 `DebugTuple` 构建器,该构建器旨在协助创建元组结构体的 `fmt::Debug` 实现。
    ///
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::fmt;
    /// use std::marker::PhantomData;
    ///
    /// struct Foo<T>(i32, String, PhantomData<T>);
    ///
    /// impl<T> fmt::Debug for Foo<T> {
    ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
    ///         fmt.debug_tuple("Foo")
    ///             .field(&self.0)
    ///             .field(&self.1)
    ///             .field(&format_args!("_"))
    ///             .finish()
    ///     }
    /// }
    ///
    /// assert_eq!(
    ///     "Foo(10, \"Hello\", _)",
    ///     format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
    /// );
    /// ```
    #[stable(feature = "debug_builders", since = "1.2.0")]
    pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
        builders::debug_tuple_new(self, name)
    }

    /// 创建一个 `DebugList` 构建器,该构建器旨在帮助为类似列表的结构创建 `fmt::Debug` 实现。
    ///
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::fmt;
    ///
    /// struct Foo(Vec<i32>);
    ///
    /// impl fmt::Debug for Foo {
    ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
    ///         fmt.debug_list().entries(self.0.iter()).finish()
    ///     }
    /// }
    ///
    /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
    /// ```
    #[stable(feature = "debug_builders", since = "1.2.0")]
    pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
        builders::debug_list_new(self)
    }

    /// 创建一个 `DebugSet` 构建器,该构建器旨在帮助为类似集合的结构创建 `fmt::Debug` 实现。
    ///
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::fmt;
    ///
    /// struct Foo(Vec<i32>);
    ///
    /// impl fmt::Debug for Foo {
    ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
    ///         fmt.debug_set().entries(self.0.iter()).finish()
    ///     }
    /// }
    ///
    /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
    /// ```
    ///
    /// [`format_args!`]: crate::format_args
    ///
    /// 在这个更复杂的示例中,我们使用 [`format_args!`] 和 `.debug_set()` 来构建匹配分支的列表:
    ///
    /// ```rust
    /// use std::fmt;
    ///
    /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
    /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
    ///
    /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
    /// where
    ///     L: 'a + fmt::Debug, R: 'a + fmt::Debug
    /// {
    ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
    ///         L::fmt(&(self.0).0, fmt)?;
    ///         fmt.write_str(" => ")?;
    ///         R::fmt(&(self.0).1, fmt)
    ///     }
    /// }
    ///
    /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
    /// where
    ///     K: 'a + fmt::Debug, V: 'a + fmt::Debug
    /// {
    ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
    ///         fmt.debug_set()
    ///         .entries(self.0.iter().map(Arm))
    ///         .entry(&Arm(&(format_args!("_"), &self.1)))
    ///         .finish()
    ///     }
    /// }
    /// ```
    ///
    #[stable(feature = "debug_builders", since = "1.2.0")]
    pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
        builders::debug_set_new(self)
    }

    /// 创建一个 `DebugMap` 构建器,该构建器旨在帮助为类似 map 的结构创建 `fmt::Debug` 实现。
    ///
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::fmt;
    ///
    /// struct Foo(Vec<(String, i32)>);
    ///
    /// impl fmt::Debug for Foo {
    ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
    ///         fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
    ///     }
    /// }
    ///
    /// assert_eq!(
    ///     format!("{:?}",  Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
    ///     r#"{"A": 10, "B": 11}"#
    ///  );
    /// ```
    #[stable(feature = "debug_builders", since = "1.2.0")]
    pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
        builders::debug_map_new(self)
    }
}

#[stable(since = "1.2.0", feature = "formatter_write")]
impl Write for Formatter<'_> {
    fn write_str(&mut self, s: &str) -> Result {
        self.buf.write_str(s)
    }

    fn write_char(&mut self, c: char) -> Result {
        self.buf.write_char(c)
    }

    fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
        write(self.buf, args)
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        Display::fmt("an error occurred when formatting an argument", f)
    }
}

// 核心格式 traits 的实现

macro_rules! fmt_refs {
    ($($tr:ident),*) => {
        $(
        #[stable(feature = "rust1", since = "1.0.0")]
        impl<T: ?Sized + $tr> $tr for &T {
            fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
        }
        #[stable(feature = "rust1", since = "1.0.0")]
        impl<T: ?Sized + $tr> $tr for &mut T {
            fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
        }
        )*
    }
}

fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }

#[unstable(feature = "never_type", issue = "35121")]
impl Debug for ! {
    fn fmt(&self, _: &mut Formatter<'_>) -> Result {
        *self
    }
}

#[unstable(feature = "never_type", issue = "35121")]
impl Display for ! {
    fn fmt(&self, _: &mut Formatter<'_>) -> Result {
        *self
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl Debug for bool {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        Display::fmt(self, f)
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl Display for bool {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        Display::fmt(if *self { "true" } else { "false" }, f)
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl Debug for str {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        f.write_char('"')?;
        let mut from = 0;
        for (i, c) in self.char_indices() {
            let esc = c.escape_debug_ext(EscapeDebugExtArgs {
                escape_grapheme_extended: true,
                escape_single_quote: false,
                escape_double_quote: true,
            });
            // 如果 char 需要转义,请清除到目前为止的积压并编写,否则跳过
            if esc.len() != 1 {
                f.write_str(&self[from..i])?;
                for c in esc {
                    f.write_char(c)?;
                }
                from = i + c.len_utf8();
            }
        }
        f.write_str(&self[from..])?;
        f.write_char('"')
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl Display for str {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        f.pad(self)
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl Debug for char {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        f.write_char('\'')?;
        for c in self.escape_debug_ext(EscapeDebugExtArgs {
            escape_grapheme_extended: true,
            escape_single_quote: true,
            escape_double_quote: false,
        }) {
            f.write_char(c)?
        }
        f.write_char('\'')
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl Display for char {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        if f.width.is_none() && f.precision.is_none() {
            f.write_char(*self)
        } else {
            f.pad(self.encode_utf8(&mut [0; 4]))
        }
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Pointer for *const T {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        let old_width = f.width;
        let old_flags = f.flags;

        // LowerHex 已将替代标志视为特殊标志,它表示是否以 0x 作为前缀。
        // 我们使用它来计算是否为零扩展,然后无条件地将其设置为获取前缀。
        //
        //
        if f.alternate() {
            f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);

            if f.width.is_none() {
                f.width = Some((usize::BITS / 4) as usize + 2);
            }
        }
        f.flags |= 1 << (FlagV1::Alternate as u32);

        let ret = LowerHex::fmt(&(*self as *const () as usize), f);

        f.width = old_width;
        f.flags = old_flags;

        ret
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Pointer for *mut T {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        Pointer::fmt(&(*self as *const T), f)
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Pointer for &T {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        Pointer::fmt(&(*self as *const T), f)
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Pointer for &mut T {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        Pointer::fmt(&(&**self as *const T), f)
    }
}

// Display/Debug 在各种核心类型上的实现

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Debug for *const T {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        Pointer::fmt(self, f)
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Debug for *mut T {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        Pointer::fmt(self, f)
    }
}

macro_rules! peel {
    ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
}

macro_rules! tuple {
    () => ();
    ( $($name:ident,)+ ) => (
        #[stable(feature = "rust1", since = "1.0.0")]
        impl<$($name:Debug),+> Debug for ($($name,)+) where last_type!($($name,)+): ?Sized {
            #[allow(non_snake_case, unused_assignments)]
            fn fmt(&self, f: &mut Formatter<'_>) -> Result {
                let mut builder = f.debug_tuple("");
                let ($(ref $name,)+) = *self;
                $(
                    builder.field(&$name);
                )+

                builder.finish()
            }
        }
        peel! { $($name,)+ }
    )
}

macro_rules! last_type {
    ($a:ident,) => { $a };
    ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
}

tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Debug> Debug for [T] {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        f.debug_list().entries(self.iter()).finish()
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl Debug for () {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        f.pad("()")
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Debug for PhantomData<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        f.debug_struct("PhantomData").finish()
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Copy + Debug> Debug for Cell<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        f.debug_struct("Cell").field("value", &self.get()).finish()
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + Debug> Debug for RefCell<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        match self.try_borrow() {
            Ok(borrow) => f.debug_struct("RefCell").field("value", &borrow).finish(),
            Err(_) => {
                // RefCell 是可变地借用的,因此我们在这里无法查看其值。
                // 改为显示一个占位符。
                struct BorrowedPlaceholder;

                impl Debug for BorrowedPlaceholder {
                    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
                        f.write_str("<borrowed>")
                    }
                }

                f.debug_struct("RefCell").field("value", &BorrowedPlaceholder).finish()
            }
        }
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        Debug::fmt(&**self, f)
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        Debug::fmt(&*(self.deref()), f)
    }
}

#[stable(feature = "core_impl_debug", since = "1.9.0")]
impl<T: ?Sized> Debug for UnsafeCell<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        f.debug_struct("UnsafeCell").finish_non_exhaustive()
    }
}

// 如果您希望测试在这里,请查看 core/tests/fmt.rs 文件,这比在此处创建所有 rt::Piece 结构要容易得多。
//
// alloc crate 中也有测试,用于那些需要分配的测试。