jiff 0.2.23

A date-time library that encourages you to jump into the pit of success. This library is heavily inspired by the Temporal project.
Documentation
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
use core::time::Duration;

use crate::{
    civil::{Date, DateTime, ISOWeekDate, Time},
    error::{fmt::temporal::Error as E, Error},
    fmt::{
        buffer::{ArrayBuffer, BorrowedBuffer, BorrowedWriter},
        temporal::{Pieces, PiecesOffset, TimeZoneAnnotationKind},
        Write,
    },
    span::{Span, UnitSet},
    tz::{Offset, TimeZone},
    SignedDuration, Timestamp, Unit, Zoned,
};

/// Defines the "maximum" possible length (in bytes) of an RFC 9557 zoned
/// datetime.
///
/// In practice, the actual maximal string possible is I believe
/// `-009999-03-14T17:30:00.999999999-04:23[America/Argentina/ComodRivadavia]`,
/// which is 72 bytes. Obviously, the length of the IANA tzdb identifier
/// matters and can be highly variable.
///
/// So why is this called "reasonable" and not "maximum"? Well, it's the
/// IANA tzdb identifiers. They can be arbitrarily long. There also aren't
/// any rules about how long they can be. So in theory, IANA could allocate
/// a new identifier longer than `America/Argentina/ComodRivadavia`. With
/// that said, they do generally try to keep them succinct.
///
/// Separately from what IANA does, Jiff itself doesn't impose any restrictions
/// on the length of identifiers. Callers can pass in arbitrarily long
/// identifiers via `TimeZone::tzif` or by simply futzing with the names of
/// files in `/usr/share/zoneinfo`. It's also possible to use an arbitrarily
/// long identifier via the "pieces" `TimeZoneAnnotationName` API. Since we
/// don't impose any restrictions, we really do want to at least try to handle
/// arbitrarily long identifiers here.
///
/// Thus, we define a "reasonable" upper bound. When the RFC 9557 string we
/// want to serialize is known to be under this bound, then we'll use a "fast"
/// path with a fixed size buffer on the stack (or perhaps even write directly
/// into the spare capacity of a caller providd `String`). But when it's above
/// this bound, then we fall back to a slower path that uses a buffering
/// mechanism to permit arbitrarily long IANA tzdb identifiers.
///
/// For the most part, doing this dance doesn't come with a runtime cost,
/// primarily because we choose to sacrifice code size a bit by duplicating
/// some functions. We could have our cake and eat it too if we enforce a
/// maximum length on IANA tzdb identifiers. Then we could set a true
/// `MAX_ZONED_LEN` and avoid the case where buffering is needed.
const REASONABLE_ZONED_LEN: usize = 72;

/// Defines the "maximum" possible length (in bytes) of an RFC 9557 zoned
/// datetime via the "pieces" API.
///
/// This generally should be identical to `REASONABLE_ZONED_LEN`, except its
/// expected maximum is one byte longer. Namely, the pieces API currently
/// lets the caller roundtrip the "criticality" of the timestamp. i.e.,
/// the `!` in the time zone annotation. So it's one extra byte longer
/// than zoned datetimes.
///
/// Note that all the same considerations from variable length IANA tzdb
/// identifiers apply to the pieces printing just as it does to zoned datetime
/// printing.
const REASONABLE_PIECES_LEN: usize = 73;

/// Defines the maximum possible length (in bytes) of an RFC 3339 timestamp
/// that is always in Zulu time.
///
/// The longest possible string is `-009999-03-14T21:53:08.999999999Z`.
const MAX_TIMESTAMP_ZULU_LEN: usize = 33;

/// Defines the maximum possible length (in bytes) of an RFC 3339 timestamp
/// with an offset (up to minute precision).
///
/// The longest possible string is `-009999-03-15T23:53:07.999999999+25:59`.
const MAX_TIMESTAMP_OFFSET_LEN: usize = 38;

/// Defines the maximum possible length (in bytes) of an ISO 8601 datetime.
///
/// The longest possible string is `-009999-03-14T17:30:00.999999999`.
const MAX_DATETIME_LEN: usize = 32;

/// Defines the maximum possible length (in bytes) of an ISO 8601 date.
///
/// The longest possible string is `-009999-03-14`.
const MAX_DATE_LEN: usize = 13;

/// Defines the maximum possible length (in bytes) of an ISO 8601 time.
///
/// The longest possible string is `17:30:00.999999999`.
const MAX_TIME_LEN: usize = 18;

/// Defines the maximum possible length (in bytes) of an offset.
///
/// The longest possible string is `-25:59:59`.
const MAX_OFFSET_LEN: usize = 9;

/// Defines the maximum possible length (in bytes) of an ISO 8601 week date.
///
/// The longest possible string is `-009999-W11-3`.
const MAX_ISO_WEEK_DATE_LEN: usize = 13;

/// Defines the maximum possible length (in bytes) of a `Span` printed in the
/// Temporal ISO 8601 format.
///
/// The way I computed this length was by using the default printer (since
/// there's only one knob and it doesn't impact the length of the string)
/// and using a negative `Span` with each unit set to
/// its minimum value.
const MAX_SPAN_LEN: usize = 78;

/// Defines the maximum possible length (in bytes) of a duration printed in the
/// Temporal ISO 8601 format.
///
/// This applies to both signed and unsigned durations. Unsigned durations have
/// one more digit, but signed durations can have a negative sign.
const MAX_DURATION_LEN: usize = 35;

#[derive(Clone, Debug)]
pub(super) struct DateTimePrinter {
    lowercase: bool,
    separator: u8,
    precision: Option<u8>,
}

impl DateTimePrinter {
    pub(super) const fn new() -> DateTimePrinter {
        DateTimePrinter { lowercase: false, separator: b'T', precision: None }
    }

    pub(super) const fn lowercase(self, yes: bool) -> DateTimePrinter {
        DateTimePrinter { lowercase: yes, ..self }
    }

    pub(super) const fn separator(self, ascii_char: u8) -> DateTimePrinter {
        assert!(ascii_char.is_ascii(), "RFC3339 separator must be ASCII");
        DateTimePrinter { separator: ascii_char, ..self }
    }

    pub(super) const fn precision(
        self,
        precision: Option<u8>,
    ) -> DateTimePrinter {
        DateTimePrinter { precision, ..self }
    }

    pub(super) fn print_zoned(
        &self,
        zdt: &Zoned,
        wtr: &mut dyn Write,
    ) -> Result<(), Error> {
        /// The base size of an RFC 9557 zoned datetime string.
        ///
        /// 19 comes from the datetime component, e.g., `2025-01-01T00:00:00`
        /// 6 comes from the offset, e.g., `+05:30`
        /// 2 comes from the `[` and `]` for the time zone annotation
        ///
        /// Basically, we always need space for *at least* the above stuff.
        /// The actual time zone annotation name, negative year and fractional
        /// second component are all optional and can vary quite a bit in
        /// length.
        ///
        /// We do this calculation to get a tighter bound on the spare capacity
        /// needed when the caller provides a `&mut String` or a `&mut Vec<u8>`
        /// to write into. That is, we want to try hard not to over-allocate.
        ///
        /// Note that memory safety does not depend on us getting this
        /// calculation right. If we get it wrong, the printer will panic if
        /// it tries to print a string that exceeds the calculated amount.
        const BASE: usize = 19 + 6 + 2;

        // An IANA tzdb identifier is variable length data, so add its length
        // to the `BASE` for runtime allocation size. When there is no IANA
        // identifier, we could write a fixed offset (that's always 6 bytes) or
        // `Etc/Unknown` (11 bytes) for when the offset from UTC is not known.
        // In the non-IANA case, we just use an upper bound of 11, so we will
        // over-allocate a little in the fixed offset case.
        let mut runtime_allocation = BASE
            + zdt.time_zone().iana_name().map(|name| name.len()).unwrap_or(11);
        // A datetime before year 0 means we add a `-00` prefix. e.g.,
        // `-001234-01-01`.
        if zdt.year() < 0 {
            runtime_allocation += 3;
        }
        // If we're printing fractional seconds, then we need more room for
        // that. This potentially overallocates because we don't do the extra
        // work required to find a tighter bound.
        if zdt.subsec_nanosecond() != 0 || self.precision.is_some() {
            runtime_allocation += 10;
        }

        // The runtime allocation could be greater than what we assume is a
        // "reasonable" upper bound on the length of an RFC 9557 string. This
        // can only happen when an IANA tzdb identifier is very long. When
        // we're under the limit, we use a fast path.
        if runtime_allocation <= REASONABLE_ZONED_LEN {
            return BorrowedBuffer::with_writer::<REASONABLE_ZONED_LEN>(
                wtr,
                runtime_allocation,
                |bbuf| Ok(self.print_zoned_buf(zdt, bbuf)),
            );
        }

        // ... otherwise, we use a path with a buffered writer that is slower
        // but can deal with arbitrarily long IANA tzdb identifiers.
        let mut buf = ArrayBuffer::<REASONABLE_ZONED_LEN>::default();
        let mut bbuf = buf.as_borrowed();
        let mut wtr = BorrowedWriter::new(&mut bbuf, wtr);
        self.print_zoned_wtr(zdt, &mut wtr)?;
        wtr.finish()
    }

    fn print_zoned_buf(&self, zdt: &Zoned, bbuf: &mut BorrowedBuffer<'_>) {
        self.print_datetime_buf(&zdt.datetime(), bbuf);
        let tz = zdt.time_zone();
        if tz.is_unknown() {
            bbuf.write_str("Z[Etc/Unknown]");
        } else {
            self.print_offset_rounded_buf(&zdt.offset(), bbuf);
            self.print_time_zone_annotation_buf(&tz, &zdt.offset(), bbuf);
        }
    }

    fn print_zoned_wtr(
        &self,
        zdt: &Zoned,
        wtr: &mut BorrowedWriter<'_, '_, '_>,
    ) -> Result<(), Error> {
        self.print_datetime_wtr(&zdt.datetime(), wtr)?;
        let tz = zdt.time_zone();
        if tz.is_unknown() {
            wtr.write_str("Z[Etc/Unknown]")?;
        } else {
            self.print_offset_rounded_wtr(&zdt.offset(), wtr)?;
            self.print_time_zone_annotation_wtr(&tz, &zdt.offset(), wtr)?;
        }
        Ok(())
    }

    pub(super) fn print_timestamp(
        &self,
        timestamp: &Timestamp,
        wtr: &mut dyn Write,
    ) -> Result<(), Error> {
        let mut runtime_allocation = MAX_TIMESTAMP_ZULU_LEN;
        // Don't reserve room for fractional seconds if we don't use them.
        if timestamp.subsec_nanosecond() == 0 && self.precision.is_none() {
            runtime_allocation -= 10;
        }
        BorrowedBuffer::with_writer::<MAX_TIMESTAMP_ZULU_LEN>(
            wtr,
            runtime_allocation,
            |bbuf| Ok(self.print_timestamp_buf(timestamp, bbuf)),
        )
    }

    fn print_timestamp_buf(
        &self,
        timestamp: &Timestamp,
        bbuf: &mut BorrowedBuffer<'_>,
    ) {
        let dt = Offset::UTC.to_datetime(*timestamp);
        self.print_datetime_buf(&dt, bbuf);
        self.print_zulu_buf(bbuf);
    }

    pub(super) fn print_timestamp_with_offset(
        &self,
        timestamp: &Timestamp,
        offset: Offset,
        wtr: &mut dyn Write,
    ) -> Result<(), Error> {
        let mut runtime_allocation = MAX_TIMESTAMP_OFFSET_LEN;
        // Don't reserve room for fractional seconds if we don't use them.
        if timestamp.subsec_nanosecond() == 0 && self.precision.is_none() {
            runtime_allocation -= 10;
        }
        BorrowedBuffer::with_writer::<MAX_TIMESTAMP_OFFSET_LEN>(
            wtr,
            runtime_allocation,
            |bbuf| {
                Ok(self
                    .print_timestamp_with_offset_buf(timestamp, offset, bbuf))
            },
        )
    }

    fn print_timestamp_with_offset_buf(
        &self,
        timestamp: &Timestamp,
        offset: Offset,
        bbuf: &mut BorrowedBuffer<'_>,
    ) {
        let dt = offset.to_datetime(*timestamp);
        self.print_datetime_buf(&dt, bbuf);
        self.print_offset_rounded_buf(&offset, bbuf);
    }

    pub(super) fn print_datetime(
        &self,
        dt: &DateTime,
        wtr: &mut dyn Write,
    ) -> Result<(), Error> {
        let mut runtime_allocation = MAX_DATETIME_LEN;
        // Don't reserve room for fractional seconds if we don't use them.
        if dt.subsec_nanosecond() == 0 && self.precision.is_none() {
            runtime_allocation -= 10;
        }
        BorrowedBuffer::with_writer::<MAX_DATETIME_LEN>(
            wtr,
            runtime_allocation,
            |bbuf| Ok(self.print_datetime_buf(dt, bbuf)),
        )
    }

    fn print_datetime_buf(
        &self,
        dt: &DateTime,
        bbuf: &mut BorrowedBuffer<'_>,
    ) {
        self.print_date_buf(&dt.date(), bbuf);
        bbuf.write_ascii_char(if self.lowercase {
            self.separator.to_ascii_lowercase()
        } else {
            self.separator
        });
        self.print_time_buf(&dt.time(), bbuf);
    }

    fn print_datetime_wtr(
        &self,
        dt: &DateTime,
        wtr: &mut BorrowedWriter<'_, '_, '_>,
    ) -> Result<(), Error> {
        self.print_date_wtr(&dt.date(), wtr)?;
        wtr.write_ascii_char(if self.lowercase {
            self.separator.to_ascii_lowercase()
        } else {
            self.separator
        })?;
        self.print_time_wtr(&dt.time(), wtr)?;
        Ok(())
    }

    pub(super) fn print_date(
        &self,
        date: &Date,
        wtr: &mut dyn Write,
    ) -> Result<(), Error> {
        BorrowedBuffer::with_writer::<MAX_DATE_LEN>(
            wtr,
            MAX_DATE_LEN,
            |bbuf| Ok(self.print_date_buf(date, bbuf)),
        )
    }

    fn print_date_buf(&self, date: &Date, bbuf: &mut BorrowedBuffer<'_>) {
        let year = date.year();
        if year < 0 {
            bbuf.write_str("-00");
        }
        bbuf.write_int_pad4(year.unsigned_abs());
        bbuf.write_ascii_char(b'-');
        bbuf.write_int_pad2(date.month().unsigned_abs());
        bbuf.write_ascii_char(b'-');
        bbuf.write_int_pad2(date.day().unsigned_abs());
    }

    fn print_date_wtr(
        &self,
        date: &Date,
        wtr: &mut BorrowedWriter<'_, '_, '_>,
    ) -> Result<(), Error> {
        let year = date.year();
        if year < 0 {
            wtr.write_str("-00")?;
        }
        wtr.write_int_pad4(year.unsigned_abs())?;
        wtr.write_ascii_char(b'-')?;
        wtr.write_int_pad2(date.month().unsigned_abs())?;
        wtr.write_ascii_char(b'-')?;
        wtr.write_int_pad2(date.day().unsigned_abs())?;
        Ok(())
    }

    pub(super) fn print_time(
        &self,
        time: &Time,
        wtr: &mut dyn Write,
    ) -> Result<(), Error> {
        let mut runtime_allocation = MAX_TIME_LEN;
        // Don't reserve room for fractional seconds if we don't use them.
        if time.subsec_nanosecond() == 0 && self.precision.is_none() {
            runtime_allocation -= 10;
        }
        BorrowedBuffer::with_writer::<MAX_TIME_LEN>(
            wtr,
            runtime_allocation,
            |bbuf| Ok(self.print_time_buf(time, bbuf)),
        )
    }

    fn print_time_buf(&self, time: &Time, bbuf: &mut BorrowedBuffer<'_>) {
        bbuf.write_int_pad2(time.hour().unsigned_abs());
        bbuf.write_ascii_char(b':');
        bbuf.write_int_pad2(time.minute().unsigned_abs());
        bbuf.write_ascii_char(b':');
        bbuf.write_int_pad2(time.second().unsigned_abs());
        let fractional_nanosecond = time.subsec_nanosecond();
        if self.precision.map_or(fractional_nanosecond != 0, |p| p > 0) {
            bbuf.write_ascii_char(b'.');
            bbuf.write_fraction(
                self.precision,
                fractional_nanosecond.unsigned_abs(),
            );
        }
    }

    fn print_time_wtr(
        &self,
        time: &Time,
        wtr: &mut BorrowedWriter<'_, '_, '_>,
    ) -> Result<(), Error> {
        wtr.write_int_pad2(time.hour().unsigned_abs())?;
        wtr.write_ascii_char(b':')?;
        wtr.write_int_pad2(time.minute().unsigned_abs())?;
        wtr.write_ascii_char(b':')?;
        wtr.write_int_pad2(time.second().unsigned_abs())?;
        let fractional_nanosecond = time.subsec_nanosecond();
        if self.precision.map_or(fractional_nanosecond != 0, |p| p > 0) {
            wtr.write_ascii_char(b'.')?;
            wtr.write_fraction(
                self.precision,
                fractional_nanosecond.unsigned_abs(),
            )?;
        }
        Ok(())
    }

    pub(super) fn print_time_zone<W: Write>(
        &self,
        tz: &TimeZone,
        mut wtr: W,
    ) -> Result<(), Error> {
        // N.B. We use a `&mut dyn Write` here instead of an uninitialized
        // buffer (as in the other routines for this printer) because this
        // can emit a POSIX time zone string. We don't really have strong
        // guarantees about how long this string can be (although all sensible
        // values are pretty short). Since this API is not expected to be used
        // much, we don't spend the time to try and optimize this.
        //
        // If and when we get a borrowed buffer writer abstraction (for truly
        // variable length output), then we might consider using that here.
        self.print_time_zone_wtr(tz, &mut wtr)
    }

    fn print_time_zone_wtr(
        &self,
        tz: &TimeZone,
        wtr: &mut dyn Write,
    ) -> Result<(), Error> {
        if let Some(iana_name) = tz.iana_name() {
            return wtr.write_str(iana_name);
        }
        if tz.is_unknown() {
            return wtr.write_str("Etc/Unknown");
        }
        if let Ok(offset) = tz.to_fixed_offset() {
            // Kind of unfortunate, but it's probably better than
            // making `print_offset_full_precision` accept a `dyn Write`.
            let mut buf = ArrayBuffer::<MAX_OFFSET_LEN>::default();
            let mut bbuf = buf.as_borrowed();
            self.print_offset_full_precision(&offset, &mut bbuf);
            return wtr.write_str(bbuf.filled());
        }
        if let Some(posix_tz) = tz.posix_tz() {
            use core::fmt::Write as _;

            // This is rather circuitous, but I'm not sure how else to do it
            // without allocating an intermediate string. Or writing another
            // printing API for `PosixTimeZone`. (Which might actually not be
            // a bad idea. Perhaps using uninit buffers. But... who gives a
            // fuck about printing POSIX time zone strings?)
            return write!(crate::fmt::StdFmtWrite(wtr), "{posix_tz}")
                .map_err(|_| {
                    Error::from(crate::error::fmt::Error::StdFmtWriteAdapter)
                });
        }
        // Ideally this never actually happens, but it can, and there
        // are likely system configurations out there in which it does.
        // I can imagine "lightweight" installations that just have a
        // `/etc/localtime` as a TZif file that doesn't point to any IANA time
        // zone. In which case, serializing a time zone probably doesn't make
        // much sense.
        //
        // Anyway, if you're seeing this error and think there should be a
        // different behavior, please file an issue.
        Err(Error::from(E::PrintTimeZoneFailure))
    }

    pub(super) fn print_pieces<W: Write>(
        &self,
        pieces: &Pieces,
        mut wtr: W,
    ) -> Result<(), Error> {
        // N.B. We don't bother with writing into the spare capacity of a
        // `&mut String` here because with `Pieces` it's a little more
        // complicated to find a more precise upper bound on the length.
        // Plus, I don't think this API is commonly used, so it's not clear
        // that it's worth optimizing. But I'm open to a PR with benchmarks
        // if there's a good use case. ---AG
        let mut buf = ArrayBuffer::<REASONABLE_PIECES_LEN>::default();
        let mut bbuf = buf.as_borrowed();
        let mut wtr = BorrowedWriter::new(&mut bbuf, &mut wtr);
        self.print_pieces_wtr(pieces, &mut wtr)?;
        wtr.finish()
    }

    fn print_pieces_wtr(
        &self,
        pieces: &Pieces,
        wtr: &mut BorrowedWriter<'_, '_, '_>,
    ) -> Result<(), Error> {
        if let Some(time) = pieces.time() {
            let dt = DateTime::from_parts(pieces.date(), time);
            self.print_datetime_wtr(&dt, wtr)?;
            if let Some(poffset) = pieces.offset() {
                self.print_pieces_offset(&poffset, wtr)?;
            }
        } else if let Some(poffset) = pieces.offset() {
            // In this case, we have an offset but no time component. Since
            // `2025-01-02-05:00` isn't valid, we forcefully write out the
            // default time (which is what would be assumed anyway).
            let dt = DateTime::from_parts(pieces.date(), Time::midnight());
            self.print_datetime_wtr(&dt, wtr)?;
            self.print_pieces_offset(&poffset, wtr)?;
        } else {
            // We have no time and no offset, so we can just write the date.
            // It's okay to write this followed by an annotation, e.g.,
            // `2025-01-02[America/New_York]` or even `2025-01-02[-05:00]`.
            self.print_date_wtr(&pieces.date(), wtr)?;
        }
        // For the time zone annotation, a `Pieces` gives us the annotation
        // name or offset directly, where as with `Zoned`, we have a
        // `TimeZone`. So we hand-roll our own formatter directly from the
        // annotation.
        if let Some(ann) = pieces.time_zone_annotation() {
            wtr.write_ascii_char(b'[')?;
            if ann.is_critical() {
                wtr.write_ascii_char(b'!')?;
            }
            match *ann.kind() {
                TimeZoneAnnotationKind::Named(ref name) => {
                    wtr.write_str(name.as_str())?;
                }
                TimeZoneAnnotationKind::Offset(offset) => {
                    self.print_offset_rounded_wtr(&offset, wtr)?;
                }
            }
            wtr.write_ascii_char(b']')?;
        }
        Ok(())
    }

    pub(super) fn print_iso_week_date(
        &self,
        iso_week_date: &ISOWeekDate,
        wtr: &mut dyn Write,
    ) -> Result<(), Error> {
        BorrowedBuffer::with_writer::<MAX_ISO_WEEK_DATE_LEN>(
            wtr,
            MAX_ISO_WEEK_DATE_LEN,
            |bbuf| Ok(self.print_iso_week_date_buf(iso_week_date, bbuf)),
        )
    }

    fn print_iso_week_date_buf(
        &self,
        iso_week_date: &ISOWeekDate,
        bbuf: &mut BorrowedBuffer<'_>,
    ) {
        let year = iso_week_date.year();
        if year < 0 {
            bbuf.write_str("-00");
        }
        bbuf.write_int_pad4(year.unsigned_abs());
        bbuf.write_ascii_char(b'-');
        bbuf.write_ascii_char(if self.lowercase { b'w' } else { b'W' });
        bbuf.write_int_pad2(iso_week_date.week().unsigned_abs());
        bbuf.write_ascii_char(b'-');
        bbuf.write_int1(
            iso_week_date.weekday().to_monday_one_offset().unsigned_abs(),
        );
    }

    fn print_pieces_offset(
        &self,
        poffset: &PiecesOffset,
        wtr: &mut BorrowedWriter<'_, '_, '_>,
    ) -> Result<(), Error> {
        match *poffset {
            PiecesOffset::Zulu => self.print_zulu_wtr(wtr),
            PiecesOffset::Numeric(ref noffset) => {
                if noffset.offset().is_zero() && noffset.is_negative() {
                    wtr.write_str("-00:00")
                } else {
                    self.print_offset_rounded_wtr(&noffset.offset(), wtr)
                }
            }
        }
    }

    /// Formats the given offset into the writer given.
    ///
    /// If the given offset has non-zero seconds, then they are rounded to
    /// the nearest minute.
    fn print_offset_rounded_buf(
        &self,
        offset: &Offset,
        bbuf: &mut BorrowedBuffer<'_>,
    ) {
        bbuf.write_ascii_char(if offset.is_negative() { b'-' } else { b'+' });
        let (offset_hours, offset_minutes) = offset.round_to_nearest_minute();
        bbuf.write_int_pad2(offset_hours);
        bbuf.write_ascii_char(b':');
        bbuf.write_int_pad2(offset_minutes);
    }

    /// Formats the given offset into the writer given.
    ///
    /// If the given offset has non-zero seconds, then they are rounded to
    /// the nearest minute.
    fn print_offset_rounded_wtr(
        &self,
        offset: &Offset,
        wtr: &mut BorrowedWriter<'_, '_, '_>,
    ) -> Result<(), Error> {
        wtr.write_ascii_char(if offset.is_negative() { b'-' } else { b'+' })?;
        let (offset_hours, offset_minutes) = offset.round_to_nearest_minute();
        wtr.write_int_pad2(offset_hours)?;
        wtr.write_ascii_char(b':')?;
        wtr.write_int_pad2(offset_minutes)?;
        Ok(())
    }

    /// Formats the given offset into the writer given.
    ///
    /// If the given offset has non-zero seconds, then they are emitted as a
    /// third `:`-delimited component of the offset. If seconds are zero, then
    /// only the hours and minute components are emitted.
    fn print_offset_full_precision(
        &self,
        offset: &Offset,
        bbuf: &mut BorrowedBuffer<'_>,
    ) {
        bbuf.write_ascii_char(if offset.is_negative() { b'-' } else { b'+' });
        let hours = offset.part_hours().unsigned_abs();
        let minutes = offset.part_minutes().unsigned_abs();
        let seconds = offset.part_seconds().unsigned_abs();
        bbuf.write_int_pad2(hours);
        bbuf.write_ascii_char(b':');
        bbuf.write_int_pad2(minutes);
        if seconds > 0 {
            bbuf.write_ascii_char(b':');
            bbuf.write_int_pad2(seconds);
        }
    }

    /// Prints the "zulu" indicator.
    ///
    /// This should only be used when the offset is not known. For example,
    /// when printing a `Timestamp`.
    fn print_zulu_buf(&self, bbuf: &mut BorrowedBuffer<'_>) {
        bbuf.write_ascii_char(if self.lowercase { b'z' } else { b'Z' });
    }

    /// Prints the "zulu" indicator.
    ///
    /// This should only be used when the offset is not known. For example,
    /// when printing a `Timestamp`.
    fn print_zulu_wtr(
        &self,
        wtr: &mut BorrowedWriter<'_, '_, '_>,
    ) -> Result<(), Error> {
        wtr.write_ascii_char(if self.lowercase { b'z' } else { b'Z' })
    }

    /// Formats the given time zone name into the writer given as an RFC 9557
    /// time zone annotation.
    ///
    /// When the given time zone is not an IANA time zone name, then the offset
    /// is printed instead. (This means the offset will be printed twice, which
    /// is indeed an intended behavior of RFC 9557 for cases where a time zone
    /// name is not used or unavailable.)
    fn print_time_zone_annotation_buf(
        &self,
        time_zone: &TimeZone,
        offset: &Offset,
        bbuf: &mut BorrowedBuffer<'_>,
    ) {
        bbuf.write_ascii_char(b'[');
        if let Some(iana_name) = time_zone.iana_name() {
            bbuf.write_str(iana_name);
        } else {
            self.print_offset_rounded_buf(offset, bbuf);
        }
        bbuf.write_ascii_char(b']');
    }

    /// Formats the given time zone name into the writer given as an RFC 9557
    /// time zone annotation.
    ///
    /// When the given time zone is not an IANA time zone name, then the offset
    /// is printed instead. (This means the offset will be printed twice, which
    /// is indeed an intended behavior of RFC 9557 for cases where a time zone
    /// name is not used or unavailable.)
    fn print_time_zone_annotation_wtr(
        &self,
        time_zone: &TimeZone,
        offset: &Offset,
        wtr: &mut BorrowedWriter<'_, '_, '_>,
    ) -> Result<(), Error> {
        wtr.write_ascii_char(b'[')?;
        if let Some(iana_name) = time_zone.iana_name() {
            wtr.write_str(iana_name)?;
        } else {
            self.print_offset_rounded_wtr(offset, wtr)?;
        }
        wtr.write_ascii_char(b']')?;
        Ok(())
    }
}

impl Default for DateTimePrinter {
    fn default() -> DateTimePrinter {
        DateTimePrinter::new()
    }
}

/// A printer for Temporal spans.
///
/// Note that in Temporal, a "span" is called a "duration."
#[derive(Debug)]
pub(super) struct SpanPrinter {
    /// The designators to use.
    designators: &'static Designators,
}

impl SpanPrinter {
    /// Create a new Temporal span printer with the default configuration.
    pub(super) const fn new() -> SpanPrinter {
        SpanPrinter { designators: DESIGNATORS_UPPERCASE }
    }

    /// Use lowercase for unit designator labels.
    ///
    /// By default, unit designator labels are written in uppercase.
    pub(super) const fn lowercase(self, yes: bool) -> SpanPrinter {
        SpanPrinter {
            designators: if yes {
                DESIGNATORS_LOWERCASE
            } else {
                DESIGNATORS_UPPERCASE
            },
        }
    }

    /// Print the given span to the writer given.
    ///
    /// This only returns an error when the given writer returns an error.
    pub(super) fn print_span<W: Write>(
        &self,
        span: &Span,
        mut wtr: W,
    ) -> Result<(), Error> {
        let mut buf = ArrayBuffer::<MAX_SPAN_LEN>::default();
        let mut bbuf = buf.as_borrowed();
        self.print_span_impl(span, &mut bbuf);
        wtr.write_str(bbuf.filled())
    }

    fn print_span_impl(&self, span: &Span, bbuf: &mut BorrowedBuffer<'_>) {
        static SUBSECOND: UnitSet = UnitSet::from_slice(&[
            Unit::Millisecond,
            Unit::Microsecond,
            Unit::Nanosecond,
        ]);

        if span.is_negative() {
            bbuf.write_ascii_char(b'-');
        }
        bbuf.write_ascii_char(b'P');

        let units = span.units();
        if units.contains(Unit::Year) {
            bbuf.write_int(span.get_years_unsigned());
            bbuf.write_ascii_char(self.label(Unit::Year));
        }
        if units.contains(Unit::Month) {
            bbuf.write_int(span.get_months_unsigned());
            bbuf.write_ascii_char(self.label(Unit::Month));
        }
        if units.contains(Unit::Week) {
            bbuf.write_int(span.get_weeks_unsigned());
            bbuf.write_ascii_char(self.label(Unit::Week));
        }
        if units.contains(Unit::Day) {
            bbuf.write_int(span.get_days_unsigned());
            bbuf.write_ascii_char(self.label(Unit::Day));
        }

        if units.only_time().is_empty() {
            if units.only_calendar().is_empty() {
                bbuf.write_ascii_char(b'T');
                bbuf.write_ascii_char(b'0');
                bbuf.write_ascii_char(self.label(Unit::Second));
            }
            return;
        }

        bbuf.write_ascii_char(b'T');

        if units.contains(Unit::Hour) {
            bbuf.write_int(span.get_hours_unsigned());
            bbuf.write_ascii_char(self.label(Unit::Hour));
        }
        if units.contains(Unit::Minute) {
            bbuf.write_int(span.get_minutes_unsigned());
            bbuf.write_ascii_char(self.label(Unit::Minute));
        }

        // ISO 8601 (and Temporal) don't support writing out milliseconds,
        // microseconds or nanoseconds as separate components like for all
        // the other units. Instead, they must be incorporated as fractional
        // seconds. But we only want to do that work if we need to.
        let has_subsecond = !units.intersection(SUBSECOND).is_empty();
        if units.contains(Unit::Second) && !has_subsecond {
            bbuf.write_int(span.get_seconds_unsigned());
            bbuf.write_ascii_char(self.label(Unit::Second));
        } else if has_subsecond {
            // We want to combine our seconds, milliseconds, microseconds and
            // nanoseconds into one single value in terms of nanoseconds. Then
            // we can "balance" that out so that we have a number of seconds
            // and a number of nanoseconds not greater than 1 second. (Which is
            // our fraction.)
            let (seconds, millis, micros, nanos) = (
                Duration::from_secs(span.get_seconds_unsigned()),
                Duration::from_millis(span.get_milliseconds_unsigned()),
                Duration::from_micros(span.get_microseconds_unsigned()),
                Duration::from_nanos(span.get_nanoseconds_unsigned()),
            );
            // OK because the maximums for a span's seconds, millis, micros
            // and nanos combined all fit into a 96-bit integer. (This is
            // guaranteed by `Span::to_duration_invariant`.)
            let total = seconds + millis + micros + nanos;
            let (secs, subsecs) = (total.as_secs(), total.subsec_nanos());
            bbuf.write_int(secs);
            if subsecs != 0 {
                bbuf.write_ascii_char(b'.');
                bbuf.write_fraction(None, subsecs);
            }
            bbuf.write_ascii_char(self.label(Unit::Second));
        }
    }

    /// Print the given signed duration to the writer given.
    ///
    /// This only returns an error when the given writer returns an error.
    pub(super) fn print_signed_duration<W: Write>(
        &self,
        dur: &SignedDuration,
        mut wtr: W,
    ) -> Result<(), Error> {
        let mut buf = ArrayBuffer::<MAX_DURATION_LEN>::default();
        let mut bbuf = buf.as_borrowed();
        if dur.is_negative() {
            bbuf.write_ascii_char(b'-');
        }
        self.print_unsigned_duration_impl(&dur.unsigned_abs(), &mut bbuf);
        wtr.write_str(bbuf.filled())
    }

    /// Print the given unsigned duration to the writer given.
    ///
    /// This only returns an error when the given writer returns an error.
    pub(super) fn print_unsigned_duration<W: Write>(
        &self,
        dur: &Duration,
        mut wtr: W,
    ) -> Result<(), Error> {
        let mut buf = ArrayBuffer::<MAX_DURATION_LEN>::default();
        let mut bbuf = buf.as_borrowed();
        self.print_unsigned_duration_impl(dur, &mut bbuf);
        wtr.write_str(bbuf.filled())
    }

    fn print_unsigned_duration_impl(
        &self,
        dur: &Duration,
        bbuf: &mut BorrowedBuffer<'_>,
    ) {
        bbuf.write_ascii_char(b'P');
        bbuf.write_ascii_char(b'T');

        let (mut secs, nanos) = (dur.as_secs(), dur.subsec_nanos());
        let non_zero_greater_than_second = secs >= 60;
        if non_zero_greater_than_second {
            let hours = secs / (60 * 60);
            secs %= 60 * 60;
            let minutes = secs / 60;
            secs = secs % 60;
            if hours != 0 {
                bbuf.write_int(hours);
                bbuf.write_ascii_char(self.label(Unit::Hour));
            }
            if minutes != 0 {
                bbuf.write_int(minutes);
                bbuf.write_ascii_char(self.label(Unit::Minute));
            }
        }
        if !non_zero_greater_than_second || secs != 0 || nanos != 0 {
            bbuf.write_int(secs);
            if nanos != 0 {
                bbuf.write_ascii_char(b'.');
                bbuf.write_fraction(None, nanos);
            }
            bbuf.write_ascii_char(self.label(Unit::Second));
        }
    }

    /// Converts the ASCII uppercase unit designator label to lowercase if this
    /// printer is configured to use lowercase. Otherwise the label is returned
    /// unchanged.
    fn label(&self, unit: Unit) -> u8 {
        self.designators.designator(unit)
    }
}

#[derive(Clone, Debug)]
struct Designators {
    // Indexed by `Unit as usize`
    map: [u8; 10],
}

const DESIGNATORS_UPPERCASE: &'static Designators = &Designators {
    // N.B. ISO 8601 duration format doesn't have unit
    // designators for sub-second units.
    map: [0, 0, 0, b'S', b'M', b'H', b'D', b'W', b'M', b'Y'],
};

const DESIGNATORS_LOWERCASE: &'static Designators = &Designators {
    // N.B. ISO 8601 duration format doesn't have unit
    // designators for sub-second units.
    map: [0, 0, 0, b's', b'm', b'h', b'd', b'w', b'm', b'y'],
};

impl Designators {
    /// Returns the designator for the given unit.
    fn designator(&self, unit: Unit) -> u8 {
        self.map[unit as usize]
    }
}

#[cfg(feature = "alloc")]
#[cfg(test)]
mod tests {
    use alloc::string::{String, ToString};

    use crate::{
        civil::{date, time, Weekday},
        fmt::StdFmtWrite,
        span::ToSpan,
        util::b,
    };

    use super::*;

    #[test]
    fn print_zoned() {
        if crate::tz::db().is_definitively_empty() {
            return;
        }

        let p = || DateTimePrinter::new();
        let via_io = |dtp: DateTimePrinter, zdt| {
            let mut buf = String::new();
            dtp.print_zoned(&zdt, &mut StdFmtWrite(&mut buf)).unwrap();
            buf
        };
        let to_string = |dtp: DateTimePrinter, zdt| {
            let mut buf = String::new();
            dtp.print_zoned(&zdt, &mut buf).unwrap();
            let got_via_io = via_io(dtp, zdt);
            assert_eq!(
                buf, got_via_io,
                "expected writes to `&mut String` to match `&mut StdFmtWrite`"
            );
            buf
        };

        let dt = date(2024, 3, 10).at(5, 34, 45, 0);
        let zdt = dt.in_tz("America/New_York").unwrap();
        let got = to_string(p(), zdt);
        assert_eq!(got, "2024-03-10T05:34:45-04:00[America/New_York]");

        let dt = date(2024, 3, 10).at(5, 34, 45, 0);
        let zdt = dt.in_tz("America/New_York").unwrap();
        let zdt = zdt.with_time_zone(TimeZone::UTC);
        let got = to_string(p(), zdt);
        assert_eq!(got, "2024-03-10T09:34:45+00:00[UTC]");

        let dt = date(2024, 3, 10).at(5, 34, 45, 0);
        let zdt = dt.to_zoned(TimeZone::fixed(Offset::MIN)).unwrap();
        let got = to_string(p(), zdt);
        assert_eq!(got, "2024-03-10T05:34:45-25:59[-25:59]");

        let dt = date(2024, 3, 10).at(5, 34, 45, 0);
        let zdt = dt.to_zoned(TimeZone::fixed(Offset::MAX)).unwrap();
        let got = to_string(p(), zdt);
        assert_eq!(got, "2024-03-10T05:34:45+25:59[+25:59]");

        let dt = date(2024, 3, 10).at(5, 34, 45, 123_456_789);
        let zdt = dt.in_tz("America/New_York").unwrap();
        let got = to_string(p(), zdt);
        assert_eq!(
            got,
            "2024-03-10T05:34:45.123456789-04:00[America/New_York]"
        );

        let dt = date(2024, 3, 10).at(5, 34, 45, 0);
        let zdt = dt.in_tz("America/New_York").unwrap();
        let got = to_string(p().precision(Some(9)), zdt);
        assert_eq!(
            got,
            "2024-03-10T05:34:45.000000000-04:00[America/New_York]"
        );

        let dt = date(-9999, 3, 1).at(23, 59, 59, 999_999_999);
        let zdt = dt.in_tz("America/Argentina/ComodRivadavia").unwrap();
        let got = to_string(p().precision(Some(9)), zdt);
        assert_eq!(
            got,
            "-009999-03-01T23:59:59.999999999-04:23[America/Argentina/ComodRivadavia]",
        );

        // Inject a very long IANA tzdb identifier to ensure it's handled
        // properly.
        let tz = TimeZone::tzif(
            "Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz/Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz/Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz",
            crate::tz::testdata::TzifTestFile::get("America/New_York").data,
        ).unwrap();
        let dt = date(-9999, 3, 1).at(23, 59, 59, 999_999_999);
        let zdt = dt.to_zoned(tz).unwrap();
        let got = to_string(p().precision(Some(9)), zdt);
        assert_eq!(
            got,
            "-009999-03-01T23:59:59.999999999-04:56[Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz/Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz/Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz]",
        );
    }

    #[test]
    fn print_timestamp_zulu() {
        let p = || DateTimePrinter::new();
        let via_io = |dtp: DateTimePrinter, ts| {
            let mut buf = String::new();
            dtp.print_timestamp(&ts, &mut StdFmtWrite(&mut buf)).unwrap();
            buf
        };
        let to_string = |dtp: DateTimePrinter, ts| {
            let mut buf = String::new();
            dtp.print_timestamp(&ts, &mut buf).unwrap();
            let got_via_io = via_io(dtp, ts);
            assert_eq!(
                buf, got_via_io,
                "expected writes to `&mut String` to match `&mut StdFmtWrite`"
            );
            buf
        };

        let tz = TimeZone::fixed(-Offset::constant(4));

        let dt = date(2024, 3, 10).at(5, 34, 45, 0);
        let zoned: Zoned = dt.to_zoned(tz.clone()).unwrap();
        let got = to_string(p(), zoned.timestamp());
        assert_eq!(got, "2024-03-10T09:34:45Z");

        let dt = date(-2024, 3, 10).at(5, 34, 45, 0);
        let zoned: Zoned = dt.to_zoned(tz.clone()).unwrap();
        let got = to_string(p(), zoned.timestamp());
        assert_eq!(got, "-002024-03-10T09:34:45Z");

        let dt = date(2024, 3, 10).at(5, 34, 45, 123_456_789);
        let zoned: Zoned = dt.to_zoned(tz.clone()).unwrap();
        let got = to_string(p(), zoned.timestamp());
        assert_eq!(got, "2024-03-10T09:34:45.123456789Z");

        let dt = date(2024, 3, 10).at(5, 34, 45, 0);
        let zoned: Zoned = dt.to_zoned(tz.clone()).unwrap();
        let got = to_string(p().precision(Some(9)), zoned.timestamp());
        assert_eq!(got, "2024-03-10T09:34:45.000000000Z");
    }

    #[test]
    fn print_timestamp_with_offset() {
        let p = || DateTimePrinter::new();
        let via_io = |dtp: DateTimePrinter, ts, offset| {
            let mut buf = String::new();
            dtp.print_timestamp_with_offset(
                &ts,
                offset,
                &mut StdFmtWrite(&mut buf),
            )
            .unwrap();
            buf
        };
        let to_string = |dtp: DateTimePrinter, ts, offset| {
            let mut buf = String::new();
            dtp.print_timestamp_with_offset(&ts, offset, &mut buf).unwrap();
            let got_via_io = via_io(dtp, ts, offset);
            assert_eq!(
                buf, got_via_io,
                "expected writes to `&mut String` to match `&mut StdFmtWrite`"
            );
            buf
        };

        let tz = TimeZone::fixed(-Offset::constant(4));

        let dt = date(2024, 3, 10).at(5, 34, 45, 0);
        let zoned: Zoned = dt.to_zoned(tz.clone()).unwrap();
        let got = to_string(p(), zoned.timestamp(), zoned.offset());
        assert_eq!(got, "2024-03-10T05:34:45-04:00");

        let dt = date(-2024, 3, 10).at(5, 34, 45, 0);
        let zoned: Zoned = dt.to_zoned(tz.clone()).unwrap();
        let got = to_string(p(), zoned.timestamp(), zoned.offset());
        assert_eq!(got, "-002024-03-10T05:34:45-04:00");

        let dt = date(2024, 3, 10).at(5, 34, 45, 123_456_789);
        let zoned: Zoned = dt.to_zoned(tz.clone()).unwrap();
        let got = to_string(p(), zoned.timestamp(), zoned.offset());
        assert_eq!(got, "2024-03-10T05:34:45.123456789-04:00");

        let dt = date(2024, 3, 10).at(5, 34, 45, 0);
        let zoned: Zoned = dt.to_zoned(tz.clone()).unwrap();
        let got = to_string(
            p().precision(Some(9)),
            zoned.timestamp(),
            zoned.offset(),
        );
        assert_eq!(got, "2024-03-10T05:34:45.000000000-04:00");

        let dt = DateTime::MIN;
        let zoned: Zoned = dt.to_zoned(TimeZone::fixed(Offset::MIN)).unwrap();
        let got = to_string(
            p().precision(Some(9)),
            zoned.timestamp(),
            zoned.offset(),
        );
        assert_eq!(got, "-009999-01-01T00:00:00.000000000-25:59");
    }

    #[test]
    fn print_datetime() {
        let p = || DateTimePrinter::new();
        let via_io = |dtp: DateTimePrinter, dt| {
            let mut buf = String::new();
            dtp.print_datetime(&dt, &mut StdFmtWrite(&mut buf)).unwrap();
            buf
        };
        let to_string = |dtp: DateTimePrinter, dt| {
            let mut buf = String::new();
            dtp.print_datetime(&dt, &mut buf).unwrap();
            let got_via_io = via_io(dtp, dt);
            assert_eq!(
                buf, got_via_io,
                "expected writes to `&mut String` to match `&mut StdFmtWrite`"
            );
            buf
        };

        let dt = date(2024, 3, 10).at(5, 34, 45, 0);
        let got = to_string(p(), dt);
        assert_eq!(got, "2024-03-10T05:34:45");

        let dt = date(-2024, 3, 10).at(5, 34, 45, 0);
        let got = to_string(p(), dt);
        assert_eq!(got, "-002024-03-10T05:34:45");

        let dt = date(2024, 3, 10).at(5, 34, 45, 123_456_789);
        let got = to_string(p(), dt);
        assert_eq!(got, "2024-03-10T05:34:45.123456789");

        let dt = date(2024, 3, 10).at(5, 34, 45, 0);
        let got = to_string(p().precision(Some(9)), dt);
        assert_eq!(got, "2024-03-10T05:34:45.000000000");

        let dt = DateTime::MIN;
        let got = to_string(p().precision(Some(9)), dt);
        assert_eq!(got, "-009999-01-01T00:00:00.000000000");
    }

    #[test]
    fn print_date() {
        let p = || DateTimePrinter::new();
        let via_io = |dtp: DateTimePrinter, date| {
            let mut buf = String::new();
            dtp.print_date(&date, &mut StdFmtWrite(&mut buf)).unwrap();
            buf
        };
        let to_string = |dtp: DateTimePrinter, date| {
            let mut buf = String::new();
            dtp.print_date(&date, &mut buf).unwrap();
            let got_via_io = via_io(dtp, date);
            assert_eq!(
                buf, got_via_io,
                "expected writes to `&mut String` to match `&mut StdFmtWrite`"
            );
            buf
        };

        let d = date(2024, 3, 10);
        let got = to_string(p(), d);
        assert_eq!(got, "2024-03-10");

        let d = date(-2024, 3, 10);
        let got = to_string(p(), d);
        assert_eq!(got, "-002024-03-10");

        let d = date(2024, 3, 10);
        let got = to_string(p(), d);
        assert_eq!(got, "2024-03-10");

        let d = Date::MIN;
        let got = to_string(p().precision(Some(9)), d);
        assert_eq!(got, "-009999-01-01");
    }

    #[test]
    fn print_time() {
        let p = || DateTimePrinter::new();
        let via_io = |dtp: DateTimePrinter, time| {
            let mut buf = String::new();
            dtp.print_time(&time, &mut StdFmtWrite(&mut buf)).unwrap();
            buf
        };
        let to_string = |dtp: DateTimePrinter, time| {
            let mut buf = String::new();
            dtp.print_time(&time, &mut buf).unwrap();
            let got_via_io = via_io(dtp, time);
            assert_eq!(
                buf, got_via_io,
                "expected writes to `&mut String` to match `&mut StdFmtWrite`"
            );
            buf
        };

        let t = time(5, 34, 45, 0);
        let got = to_string(p(), t);
        assert_eq!(got, "05:34:45");

        let t = time(5, 34, 45, 0);
        let got = to_string(p(), t);
        assert_eq!(got, "05:34:45");

        let t = time(5, 34, 45, 123_456_789);
        let got = to_string(p(), t);
        assert_eq!(got, "05:34:45.123456789");

        let t = time(5, 34, 45, 0);
        let got = to_string(p().precision(Some(9)), t);
        assert_eq!(got, "05:34:45.000000000");

        let t = Time::MIN;
        let got = to_string(p().precision(Some(9)), t);
        assert_eq!(got, "00:00:00.000000000");

        let t = Time::MAX;
        let got = to_string(p().precision(Some(9)), t);
        assert_eq!(got, "23:59:59.999999999");
    }

    #[test]
    fn print_iso_week_date() {
        let p = || DateTimePrinter::new();
        let via_io = |dtp: DateTimePrinter, date| {
            let mut buf = String::new();
            dtp.print_iso_week_date(&date, &mut StdFmtWrite(&mut buf))
                .unwrap();
            buf
        };
        let to_string = |dtp: DateTimePrinter, date| {
            let mut buf = String::new();
            dtp.print_iso_week_date(&date, &mut buf).unwrap();
            let got_via_io = via_io(dtp, date);
            assert_eq!(
                buf, got_via_io,
                "expected writes to `&mut String` to match `&mut StdFmtWrite`"
            );
            buf
        };

        let d = ISOWeekDate::new(2024, 52, Weekday::Monday).unwrap();
        let got = to_string(p(), d);
        assert_eq!(got, "2024-W52-1");

        let d = ISOWeekDate::new(2004, 1, Weekday::Sunday).unwrap();
        let got = to_string(p(), d);
        assert_eq!(got, "2004-W01-7");

        let d = ISOWeekDate::MIN;
        let got = to_string(p(), d);
        assert_eq!(got, "-009999-W01-1");

        let d = ISOWeekDate::MAX;
        let got = to_string(p(), d);
        assert_eq!(got, "9999-W52-5");
    }

    #[test]
    fn print_pieces() {
        let p = || DateTimePrinter::new();
        let via_io = |dtp: DateTimePrinter, pieces| {
            let mut buf = String::new();
            dtp.print_pieces(&pieces, &mut StdFmtWrite(&mut buf)).unwrap();
            buf
        };
        let to_string = |dtp: DateTimePrinter, pieces| {
            let mut buf = String::new();
            dtp.print_pieces(&pieces, &mut buf).unwrap();
            let got_via_io = via_io(dtp, pieces);
            assert_eq!(
                buf, got_via_io,
                "expected writes to `&mut String` to match `&mut StdFmtWrite`"
            );
            buf
        };

        let pieces = Pieces::from(date(2024, 3, 10).at(5, 34, 45, 0))
            .with_offset(Offset::constant(-4))
            .with_time_zone_name("America/New_York");
        let got = to_string(p(), pieces);
        assert_eq!(got, "2024-03-10T05:34:45-04:00[America/New_York]");

        let pieces = Pieces::from(date(2024, 3, 10).at(5, 34, 45, 0))
            .with_offset(Offset::UTC)
            .with_time_zone_name("UTC");
        let got = to_string(p(), pieces);
        assert_eq!(got, "2024-03-10T05:34:45+00:00[UTC]");

        let pieces = Pieces::from(date(2024, 3, 10).at(5, 34, 45, 0))
            .with_offset(Offset::MIN)
            .with_time_zone_offset(Offset::MIN);
        let got = to_string(p(), pieces);
        assert_eq!(got, "2024-03-10T05:34:45-25:59[-25:59]");

        let pieces = Pieces::from(date(2024, 3, 10).at(5, 34, 45, 0))
            .with_offset(Offset::MAX)
            .with_time_zone_offset(Offset::MAX);
        let got = to_string(p(), pieces);
        assert_eq!(got, "2024-03-10T05:34:45+25:59[+25:59]");

        let pieces =
            Pieces::from(date(2024, 3, 10).at(5, 34, 45, 123_456_789))
                .with_offset(Offset::constant(-4))
                .with_time_zone_name("America/New_York");
        let got = to_string(p(), pieces);
        assert_eq!(
            got,
            "2024-03-10T05:34:45.123456789-04:00[America/New_York]"
        );

        let pieces = Pieces::from(date(2024, 3, 10).at(5, 34, 45, 0))
            .with_offset(Offset::constant(-4))
            .with_time_zone_name("America/New_York");
        let got = to_string(p().precision(Some(9)), pieces);
        assert_eq!(
            got,
            "2024-03-10T05:34:45.000000000-04:00[America/New_York]"
        );

        let pieces =
            Pieces::from(date(-9999, 3, 1).at(23, 59, 59, 999_999_999))
                .with_offset(Offset::constant(-4))
                .with_time_zone_name("America/Argentina/ComodRivadavia");
        let got = to_string(p().precision(Some(9)), pieces);
        assert_eq!(
            got,
            "-009999-03-01T23:59:59.999999999-04:00[America/Argentina/ComodRivadavia]",
        );

        let pieces =
            Pieces::parse(
                "-009999-03-01T23:59:59.999999999-04:00[!America/Argentina/ComodRivadavia]",
            ).unwrap();
        let got = to_string(p().precision(Some(9)), pieces);
        assert_eq!(
            got,
            "-009999-03-01T23:59:59.999999999-04:00[!America/Argentina/ComodRivadavia]",
        );

        // Inject a very long IANA tzdb identifier to ensure it's handled
        let name = "Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz/Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz/Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz";
        let pieces =
            Pieces::from(date(-9999, 3, 1).at(23, 59, 59, 999_999_999))
                .with_offset(Offset::constant(-4))
                .with_time_zone_name(name);
        let got = to_string(p().precision(Some(9)), pieces);
        assert_eq!(
            got,
            "-009999-03-01T23:59:59.999999999-04:00[Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz/Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz/Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz]",
        );
    }

    #[test]
    fn print_time_zone() {
        let p = || DateTimePrinter::new();
        let via_io = |dtp: DateTimePrinter, tz| {
            let mut buf = String::new();
            dtp.print_time_zone(&tz, &mut StdFmtWrite(&mut buf)).unwrap();
            buf
        };
        let to_string = |dtp: DateTimePrinter, tz| {
            let mut buf = String::new();
            dtp.print_time_zone(&tz, &mut buf).unwrap();
            let got_via_io = via_io(dtp, tz);
            assert_eq!(
                buf, got_via_io,
                "expected writes to `&mut String` to match `&mut StdFmtWrite`"
            );
            buf
        };

        let tztest =
            crate::tz::testdata::TzifTestFile::get("America/New_York");
        let tz = TimeZone::tzif(tztest.name, tztest.data).unwrap();
        let got = to_string(p(), tz);
        assert_eq!(got, "America/New_York");

        // Inject a very long IANA tzdb identifier to ensure it's handled
        // properly.
        let tz = TimeZone::tzif(
            "Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz/Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz/Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz",
            tztest.data,
        ).unwrap();
        let got = to_string(p(), tz);
        assert_eq!(
            got,
            "Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz/Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz/Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz",
        );

        let tz = TimeZone::UTC;
        let got = to_string(p(), tz);
        assert_eq!(got, "UTC");

        let tz = TimeZone::unknown();
        let got = to_string(p(), tz);
        assert_eq!(got, "Etc/Unknown");

        let tz = TimeZone::fixed(Offset::MIN);
        let got = to_string(p(), tz);
        assert_eq!(got, "-25:59:59");

        let tz = TimeZone::fixed(Offset::MAX);
        let got = to_string(p(), tz);
        assert_eq!(got, "+25:59:59");

        let tz = TimeZone::posix("EST5EDT,M3.2.0,M11.1.0").unwrap();
        let got = to_string(p(), tz);
        assert_eq!(got, "EST5EDT,M3.2.0,M11.1.0");

        let tz = TimeZone::posix(
            "ABCDEFGHIJKLMNOPQRSTUVWXY5ABCDEFGHIJKLMNOPQRSTUVWXYT,M3.2.0,M11.1.0",
        ).unwrap();
        let got = to_string(p(), tz);
        assert_eq!(
            got,
            "ABCDEFGHIJKLMNOPQRSTUVWXY5ABCDEFGHIJKLMNOPQRSTUVWXYT,M3.2.0,M11.1.0",
        );

        // This isn't a public API, but this lets us test the error
        // case: a valid time zone but without a succinct name.
        #[cfg(feature = "tz-system")]
        {
            let tz = TimeZone::tzif_system(tztest.data).unwrap();
            let mut buf = String::new();
            let err = p().print_time_zone(&tz, &mut buf).unwrap_err();
            assert_eq!(
                err.to_string(),
                "time zones without IANA identifiers that aren't \
                 either fixed offsets or a POSIX time zone can't be \
                 serialized (this typically occurs when this is a \
                 system time zone derived from `/etc/localtime` on \
                 Unix systems that isn't symlinked to an entry in \
                 `/usr/share/zoneinfo`)",
            );
        }
    }

    #[cfg(not(miri))]
    #[test]
    fn print_span_basic() {
        let p = |span: Span| -> String {
            let mut buf = String::new();
            SpanPrinter::new().print_span(&span, &mut buf).unwrap();
            buf
        };

        insta::assert_snapshot!(p(Span::new()), @"PT0S");
        insta::assert_snapshot!(p(1.second()), @"PT1S");
        insta::assert_snapshot!(p(-1.second()), @"-PT1S");
        insta::assert_snapshot!(p(
            1.second().milliseconds(1).microseconds(1).nanoseconds(1),
        ), @"PT1.001001001S");
        insta::assert_snapshot!(p(
            0.second().milliseconds(999).microseconds(999).nanoseconds(999),
        ), @"PT0.999999999S");
        insta::assert_snapshot!(p(
            1.year().months(1).weeks(1).days(1)
            .hours(1).minutes(1).seconds(1)
            .milliseconds(1).microseconds(1).nanoseconds(1),
        ), @"P1Y1M1W1DT1H1M1.001001001S");
        insta::assert_snapshot!(p(
            -1.year().months(1).weeks(1).days(1)
            .hours(1).minutes(1).seconds(1)
            .milliseconds(1).microseconds(1).nanoseconds(1),
        ), @"-P1Y1M1W1DT1H1M1.001001001S");
    }

    #[cfg(not(miri))]
    #[test]
    fn print_span_subsecond_positive() {
        let p = |span: Span| -> String {
            let mut buf = String::new();
            SpanPrinter::new().print_span(&span, &mut buf).unwrap();
            buf
        };

        // These are all sub-second trickery tests.
        insta::assert_snapshot!(p(
            0.second().milliseconds(1000).microseconds(1000).nanoseconds(1000),
        ), @"PT1.001001S");
        insta::assert_snapshot!(p(
            1.second().milliseconds(1000).microseconds(1000).nanoseconds(1000),
        ), @"PT2.001001S");
        insta::assert_snapshot!(p(
            0.second()
            .milliseconds(b::SpanMilliseconds::MAX),
        ), @"PT631107417600S");
        insta::assert_snapshot!(p(
            0.second()
            .microseconds(b::SpanMicroseconds::MAX),
        ), @"PT631107417600S");
        insta::assert_snapshot!(p(
            0.second()
            .nanoseconds(b::SpanNanoseconds::MAX),
        ), @"PT9223372036.854775807S");

        insta::assert_snapshot!(p(
            0.second()
            .milliseconds(b::SpanMilliseconds::MAX)
            .microseconds(999_999),
        ), @"PT631107417600.999999S");
        // This is 1 microsecond more than the maximum number of seconds
        // representable in a span.
        insta::assert_snapshot!(p(
            0.second()
            .milliseconds(b::SpanMilliseconds::MAX)
            .microseconds(1_000_000),
        ), @"PT631107417601S");
        insta::assert_snapshot!(p(
            0.second()
            .milliseconds(b::SpanMilliseconds::MAX)
            .microseconds(1_000_001),
        ), @"PT631107417601.000001S");
        // This is 1 nanosecond more than the maximum number of seconds
        // representable in a span.
        insta::assert_snapshot!(p(
            0.second()
            .milliseconds(b::SpanMilliseconds::MAX)
            .nanoseconds(1_000_000_000),
        ), @"PT631107417601S");
        insta::assert_snapshot!(p(
            0.second()
            .milliseconds(b::SpanMilliseconds::MAX)
            .nanoseconds(1_000_000_001),
        ), @"PT631107417601.000000001S");

        // The max millis, micros and nanos, combined.
        insta::assert_snapshot!(p(
            0.second()
            .milliseconds(b::SpanMilliseconds::MAX)
            .microseconds(b::SpanMicroseconds::MAX)
            .nanoseconds(b::SpanNanoseconds::MAX),
        ), @"PT1271438207236.854775807S");
        // The max seconds, millis, micros and nanos, combined.
        insta::assert_snapshot!(p(
            Span::new()
            .seconds(b::SpanSeconds::MAX)
            .milliseconds(b::SpanMilliseconds::MAX)
            .microseconds(b::SpanMicroseconds::MAX)
            .nanoseconds(b::SpanNanoseconds::MAX),
        ), @"PT1902545624836.854775807S");
    }

    #[cfg(not(miri))]
    #[test]
    fn print_span_subsecond_negative() {
        let p = |span: Span| -> String {
            let mut buf = String::new();
            SpanPrinter::new().print_span(&span, &mut buf).unwrap();
            buf
        };

        // These are all sub-second trickery tests.
        insta::assert_snapshot!(p(
            -0.second().milliseconds(1000).microseconds(1000).nanoseconds(1000),
        ), @"-PT1.001001S");
        insta::assert_snapshot!(p(
            -1.second().milliseconds(1000).microseconds(1000).nanoseconds(1000),
        ), @"-PT2.001001S");
        insta::assert_snapshot!(p(
            0.second()
            .milliseconds(b::SpanMilliseconds::MIN),
        ), @"-PT631107417600S");
        insta::assert_snapshot!(p(
            0.second()
            .microseconds(b::SpanMicroseconds::MIN),
        ), @"-PT631107417600S");
        insta::assert_snapshot!(p(
            0.second()
            .nanoseconds(b::SpanNanoseconds::MIN),
        ), @"-PT9223372036.854775807S");

        insta::assert_snapshot!(p(
            0.second()
            .milliseconds(b::SpanMilliseconds::MIN)
            .microseconds(999_999),
        ), @"-PT631107417600.999999S");
        // This is 1 microsecond more than the maximum number of seconds
        // representable in a span.
        insta::assert_snapshot!(p(
            0.second()
            .milliseconds(b::SpanMilliseconds::MIN)
            .microseconds(1_000_000),
        ), @"-PT631107417601S");
        insta::assert_snapshot!(p(
            0.second()
            .milliseconds(b::SpanMilliseconds::MIN)
            .microseconds(1_000_001),
        ), @"-PT631107417601.000001S");
        // This is 1 nanosecond more than the maximum number of seconds
        // representable in a span.
        insta::assert_snapshot!(p(
            0.second()
            .milliseconds(b::SpanMilliseconds::MIN)
            .nanoseconds(1_000_000_000),
        ), @"-PT631107417601S");
        insta::assert_snapshot!(p(
            0.second()
            .milliseconds(b::SpanMilliseconds::MIN)
            .nanoseconds(1_000_000_001),
        ), @"-PT631107417601.000000001S");

        // The max millis, micros and nanos, combined.
        insta::assert_snapshot!(p(
            0.second()
            .milliseconds(b::SpanMilliseconds::MIN)
            .microseconds(b::SpanMicroseconds::MIN)
            .nanoseconds(b::SpanNanoseconds::MIN),
        ), @"-PT1271438207236.854775807S");
        // The max seconds, millis, micros and nanos, combined.
        insta::assert_snapshot!(p(
            Span::new()
            .seconds(b::SpanSeconds::MIN)
            .milliseconds(b::SpanMilliseconds::MIN)
            .microseconds(b::SpanMicroseconds::MIN)
            .nanoseconds(b::SpanNanoseconds::MIN),
        ), @"-PT1902545624836.854775807S");
    }

    #[cfg(not(miri))]
    #[test]
    fn print_signed_duration() {
        let p = |secs, nanos| -> String {
            let dur = SignedDuration::new(secs, nanos);
            let mut buf = String::new();
            SpanPrinter::new().print_signed_duration(&dur, &mut buf).unwrap();
            buf
        };

        insta::assert_snapshot!(p(0, 0), @"PT0S");
        insta::assert_snapshot!(p(0, 1), @"PT0.000000001S");
        insta::assert_snapshot!(p(1, 0), @"PT1S");
        insta::assert_snapshot!(p(59, 0), @"PT59S");
        insta::assert_snapshot!(p(60, 0), @"PT1M");
        insta::assert_snapshot!(p(60, 1), @"PT1M0.000000001S");
        insta::assert_snapshot!(p(61, 1), @"PT1M1.000000001S");
        insta::assert_snapshot!(p(3_600, 0), @"PT1H");
        insta::assert_snapshot!(p(3_600, 1), @"PT1H0.000000001S");
        insta::assert_snapshot!(p(3_660, 0), @"PT1H1M");
        insta::assert_snapshot!(p(3_660, 1), @"PT1H1M0.000000001S");
        insta::assert_snapshot!(p(3_661, 0), @"PT1H1M1S");
        insta::assert_snapshot!(p(3_661, 1), @"PT1H1M1.000000001S");

        insta::assert_snapshot!(p(0, -1), @"-PT0.000000001S");
        insta::assert_snapshot!(p(-1, 0), @"-PT1S");
        insta::assert_snapshot!(p(-59, 0), @"-PT59S");
        insta::assert_snapshot!(p(-60, 0), @"-PT1M");
        insta::assert_snapshot!(p(-60, -1), @"-PT1M0.000000001S");
        insta::assert_snapshot!(p(-61, -1), @"-PT1M1.000000001S");
        insta::assert_snapshot!(p(-3_600, 0), @"-PT1H");
        insta::assert_snapshot!(p(-3_600, -1), @"-PT1H0.000000001S");
        insta::assert_snapshot!(p(-3_660, 0), @"-PT1H1M");
        insta::assert_snapshot!(p(-3_660, -1), @"-PT1H1M0.000000001S");
        insta::assert_snapshot!(p(-3_661, 0), @"-PT1H1M1S");
        insta::assert_snapshot!(p(-3_661, -1), @"-PT1H1M1.000000001S");

        insta::assert_snapshot!(
            p(i64::MIN, -999_999_999),
            @"-PT2562047788015215H30M8.999999999S",
        );
        insta::assert_snapshot!(
            p(i64::MAX, 999_999_999),
            @"PT2562047788015215H30M7.999999999S",
        );
    }

    #[cfg(not(miri))]
    #[test]
    fn print_unsigned_duration() {
        let p = |secs, nanos| -> String {
            let dur = Duration::new(secs, nanos);
            let mut buf = String::new();
            SpanPrinter::new()
                .print_unsigned_duration(&dur, &mut buf)
                .unwrap();
            buf
        };

        insta::assert_snapshot!(p(0, 0), @"PT0S");
        insta::assert_snapshot!(p(0, 1), @"PT0.000000001S");
        insta::assert_snapshot!(p(1, 0), @"PT1S");
        insta::assert_snapshot!(p(59, 0), @"PT59S");
        insta::assert_snapshot!(p(60, 0), @"PT1M");
        insta::assert_snapshot!(p(60, 1), @"PT1M0.000000001S");
        insta::assert_snapshot!(p(61, 1), @"PT1M1.000000001S");
        insta::assert_snapshot!(p(3_600, 0), @"PT1H");
        insta::assert_snapshot!(p(3_600, 1), @"PT1H0.000000001S");
        insta::assert_snapshot!(p(3_660, 0), @"PT1H1M");
        insta::assert_snapshot!(p(3_660, 1), @"PT1H1M0.000000001S");
        insta::assert_snapshot!(p(3_661, 0), @"PT1H1M1S");
        insta::assert_snapshot!(p(3_661, 1), @"PT1H1M1.000000001S");

        insta::assert_snapshot!(
            p(u64::MAX, 999_999_999),
            @"PT5124095576030431H15.999999999S",
        );
    }
}