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
use core::mem::MaybeUninit;

use crate::{fmt::Write, Error};

const MAX_CAPACITY: usize = u16::MAX as usize;
// From `u64::MAX.to_string().len()`.
const MAX_INTEGER_LEN: u8 = 20;
const MAX_PRECISION: usize = 9;

/// The minimum buffer length required for *any* of `BorrowedBuffer`'s
/// integer formatting APIs to work.
///
/// This relies on the fact that the maximum padding is clamped to `20`.
const BROAD_MINIMUM_BUFFER_LEN: usize = 20;

/// All integers in the range `0..=99`, zero padded.
const RADIX_100_ZERO: [u8; 200] = *b"00010203040506070809\
       10111213141516171819\
       20212223242526272829\
       30313233343536373839\
       40414243444546474849\
       50515253545556575859\
       60616263646566676869\
       70717273747576777879\
       80818283848586878889\
       90919293949596979899";

/// All integers in the range `0..=99`, space padded.
const RADIX_100_SPACE: [u8; 200] = *b" 0 1 2 3 4 5 6 7 8 9\
       10111213141516171819\
       20212223242526272829\
       30313233343536373839\
       40414243444546474849\
       50515253545556575859\
       60616263646566676869\
       70717273747576777879\
       80818283848586878889\
       90919293949596979899";

/// An uninitialized slice of bytes of fixed size.
///
/// This is typically used with `BorrowedBuffer`.
#[derive(Clone, Copy)]
pub(crate) struct ArrayBuffer<const N: usize> {
    data: [MaybeUninit<u8>; N],
}

impl<const N: usize> ArrayBuffer<N> {
    /// Return a writable buffer into this storage.
    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn as_borrowed<'data>(&mut self) -> BorrowedBuffer<'_> {
        BorrowedBuffer::from(&mut self.data)
    }

    /// Assume this entire buffer is initialized and return it as an array.
    ///
    /// # Safety
    ///
    /// Callers must ensure the entire buffer is initialized.
    unsafe fn assume_init(self) -> [u8; N] {
        // SAFETY: Callers are responsible for ensuring that `self.data`
        // is initialized. Otherwise, `MaybeUninit<u8>` and `u8` have the
        // same representation.
        unsafe {
            *(&self.data as *const [MaybeUninit<u8>; N] as *const [u8; N])
        }
    }
}

/// Construct an uninitialized buffer of data of size `N`.
impl<const N: usize> Default for ArrayBuffer<N> {
    #[cfg_attr(feature = "perf-inline", inline(always))]
    fn default() -> ArrayBuffer<N> {
        ArrayBuffer { data: [MaybeUninit::uninit(); N] }
    }
}

/// A borrowed buffer for writing into an uninitialized slice of bytes.
///
/// This can be used with, e.g., an `ArrayBuffer` as backing storage. This
/// type will managed actually writing to the backing storage, keeping track
/// of how much data has been written and exposing a safe API.
///
/// This type is principally used in Jiff's printer implementations. In
/// particular, this helps printers generate tighter and more efficient code.
/// Once printing is done, the data in the buffer is then copied to the caller
/// provided implementation of `jiff::fmt::Write`. This double write is
/// unfortunate, but it turned out that threading a `jiff::fmt::Write` down
/// through the printers and using it directly leads to slower code overall
/// *and* more code bloat. This is because a `BorrowedBuffer` is an incredibly
/// lightweight abstraction that never has to deal with I/O or growing an
/// allocation.
///
/// # Design
///
/// * Requires valid UTF-8 so that we can provide higher level safe APIs for
/// interfacing with `String`.
/// * Specifically panics when a write would exceed available capacity. This
/// introduces a branch, but effectively decouples "get the maximum size
/// correct" from "is memory safe."
#[derive(Debug)]
pub(crate) struct BorrowedBuffer<'data> {
    data: &'data mut [MaybeUninit<u8>],
    filled: u16,
}

impl<'data> BorrowedBuffer<'data> {
    /// A high level API for writing to a `jiff::fmt::Write` via a buffer of
    /// uninitialized bytes.
    ///
    /// When the `alloc` crate feature is enabled and `W` provides a
    /// `&mut Vec<u8>`, then the buffer is extracted directly from the
    /// spare capacity of the `Vec<u8>`.
    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn with_writer<const N: usize>(
        wtr: &mut dyn Write,
        _runtime_allocation: usize,
        mut with: impl FnMut(&mut BorrowedBuffer<'_>) -> Result<(), Error>,
    ) -> Result<(), Error> {
        // Specialize for the common case of `W = String` or `W = Vec<u8>`.
        // In effect, we write directly into the excess capacity of `W`
        // instead of first writing into a stack array and then copying that
        // into `W`.
        //
        // This can provide up to a 40% improvement in runtime in some
        // microbenchmarks.
        //
        // SAFETY: We only ever write valid UTF-8. Namely, `BorrowedBuffer`
        // enforces this invariant.
        #[cfg(feature = "alloc")]
        if let Some(buf) = unsafe { wtr.as_mut_vec() } {
            buf.reserve(_runtime_allocation);
            return BorrowedBuffer::with_vec_spare_capacity(buf, with);
        }
        let mut buf = ArrayBuffer::<N>::default();
        let mut bbuf = buf.as_borrowed();
        with(&mut bbuf)?;
        wtr.write_str(bbuf.filled())?;
        Ok(())
    }

    /// Provides a borrowed buffer into the first 255 bytes of the spare
    /// capacity in the given `Vec<u8>` and updates the length on `Vec<u8>`
    /// after the closure completes to account for any new data written.
    ///
    /// In effect, this safely encapsulates writing into the uninitialized
    /// portion of a `Vec<u8>`.
    ///
    /// If the provided closure panics, then there is no guarantee that the
    /// `buf`'s length will be updated to reflect what has been written.
    /// However, it is guaranteed that the length setting will not lead to
    /// undefined behavior.
    #[cfg(feature = "alloc")]
    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn with_vec_spare_capacity<T>(
        buf: &'data mut alloc::vec::Vec<u8>,
        mut with: impl FnMut(&mut BorrowedBuffer<'_>) -> T,
    ) -> T {
        let mut bbuf = BorrowedBuffer::from_vec_spare_capacity(buf);
        let returned = with(&mut bbuf);
        let new_len = bbuf.len();
        // SAFETY: `BorrowedBuffer::len()` always reflects the number of
        // bytes that have been written to. Thus, the data up to the given new
        // length is guaranteed to be initialized.
        unsafe {
            buf.set_len(new_len);
        }
        returned
    }

    /// Build a borrowed buffer for writing into the spare capacity of a
    /// `Vec<u8>` allocation.
    ///
    /// This is limited only to the first `255` bytes of the spare capacity.
    #[cfg(feature = "alloc")]
    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn from_vec_spare_capacity(
        vec: &'data mut alloc::vec::Vec<u8>,
    ) -> BorrowedBuffer<'data> {
        let data = vec.spare_capacity_mut();
        let len = data.len().min(MAX_CAPACITY);
        BorrowedBuffer::from(&mut data[..len])
    }

    /// Write the provided string to the available space in this buffer.
    ///
    /// # Panics
    ///
    /// When the available space is shorter than the length of the provided
    /// string. That is, when `capacity() - filled().len() < string.len()`.
    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn write_str(&mut self, string: &str) {
        // SAFETY: A `&str`, `&[u8]` and `&[MaybeUninit<u8>]` all have the
        // same representation in memory.
        let data: &[MaybeUninit<u8>] = unsafe {
            core::slice::from_raw_parts(
                string.as_ptr().cast::<MaybeUninit<u8>>(),
                string.len(),
            )
        };
        self.available()
            .get_mut(..string.len())
            .expect("string data exceeds available buffer space")
            .copy_from_slice(data);
        // Cast here will never truncate because `BorrowedBuffer` is limited
        // to `u16::MAX` in total capacity. Above will panic if `string.len()`
        // exceeds available capacity, which can never be above total capacity.
        // Thus, if we're here, `string.len() <= u16::MAX` is guaranteed to
        // hold.
        self.filled += string.len() as u16;
    }

    /// Writes the given Unicode scalar value (as UTF-8) to this writer.
    ///
    /// # Panics
    ///
    /// When the available space is shorter than the UTF-8 encoding of the
    /// given Unicode scalar value (up to and including 4 bytes).
    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn write_char(&mut self, ch: char) {
        self.write_str(ch.encode_utf8(&mut [0; 4]));
    }

    /// Writes the given ASCII byte to this writer.
    ///
    /// # Panics
    ///
    /// When the available space is shorter than 1 or if `byte` is not ASCII.
    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn write_ascii_char(&mut self, byte: u8) {
        assert!(byte.is_ascii());
        self.available()
            .get_mut(0)
            .expect("insufficient buffer space to write one byte")
            .write(byte);
        self.filled += 1;
    }

    /// Writes the given `u8` integer to this buffer. No padding is performed.
    ///
    /// # Panics
    ///
    /// When the available space is insufficient to encode the number of
    /// digits in the decimal representation of `n`.
    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn write_int(&mut self, n: impl Into<u64>) {
        let mut n = n.into();
        let digits = digits(n);
        let mut remaining_digits = usize::from(digits);
        let available = self
            .available()
            .get_mut(..remaining_digits)
            .expect("u8 integer digits exceeds available buffer space");
        while remaining_digits > 0 {
            remaining_digits -= 1;
            // SAFETY: The assert above guarantees that `remaining_digits` is
            // always in bounds.
            unsafe {
                available
                    .get_unchecked_mut(remaining_digits)
                    .write(b'0' + ((n % 10) as u8));
            }
            n /= 10;
        }
        self.filled += u16::from(digits);
    }

    /// Writes the given `u8` integer to this buffer using the given padding.
    ///
    /// The maximum allowed padding is `20`. Any values bigger than that are
    /// silently clamped to `20`.
    ///
    /// This always pads with zeroes.
    ///
    /// # Panics
    ///
    /// When the available space is insufficient to encode the number of
    /// digits in the decimal representation of `n`.
    ///
    /// This also panics when `pad_byte` is not ASCII.
    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn write_int_pad0(&mut self, n: impl Into<u64>, pad_len: u8) {
        let mut n = n.into();
        let pad_len = pad_len.min(MAX_INTEGER_LEN);
        let digits = pad_len.max(digits(n));
        let mut remaining_digits = usize::from(digits);
        let available = self
            .available()
            .get_mut(..remaining_digits)
            .expect("u8 integer digits exceeds available buffer space");
        while remaining_digits > 0 {
            remaining_digits -= 1;
            // SAFETY: The assert above guarantees that `remaining_digits` is
            // always in bounds.
            unsafe {
                available
                    .get_unchecked_mut(remaining_digits)
                    .write(b'0' + ((n % 10) as u8));
            }
            n /= 10;
        }
        self.filled += u16::from(digits);
    }

    /// Writes the given `u8` integer to this buffer using the given padding.
    ///
    /// The maximum allowed padding is `20`. Any values bigger than that are
    /// silently clamped to `20`.
    ///
    /// # Panics
    ///
    /// When the available space is insufficient to encode the number of
    /// digits in the decimal representation of `n`.
    ///
    /// This also panics when `pad_byte` is not ASCII.
    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn write_int_pad(
        &mut self,
        n: impl Into<u64>,
        pad_byte: u8,
        pad_len: u8,
    ) {
        assert!(pad_byte.is_ascii(), "padding byte must be ASCII");

        let mut n = n.into();
        let pad_len = pad_len.min(MAX_INTEGER_LEN);
        let digits = pad_len.max(digits(n));
        let mut remaining_digits = usize::from(digits);
        let available = self
            .available()
            .get_mut(..remaining_digits)
            .expect("u8 integer digits exceeds available buffer space");
        while remaining_digits > 0 {
            remaining_digits -= 1;
            // SAFETY: The assert above guarantees that `remaining_digits` is
            // always in bounds.
            unsafe {
                available
                    .get_unchecked_mut(remaining_digits)
                    .write(b'0' + ((n % 10) as u8));
            }
            n /= 10;
            if n == 0 {
                break;
            }
        }
        while remaining_digits > 0 {
            remaining_digits -= 1;
            // SAFETY: The assert above guarantees that `remaining_digits` is
            // always in bounds.
            unsafe {
                available.get_unchecked_mut(remaining_digits).write(pad_byte);
            }
        }
        self.filled += u16::from(digits);
    }

    /// Writes the given integer as a 1-digit integer.
    ///
    /// # Panics
    ///
    /// When the available space is shorter than 1 or if `n > 9`.
    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn write_int1(&mut self, n: impl Into<u64>) {
        let n = n.into();
        // This is required for correctness. When `n > 9`, then the
        // `n as u8` below could result in writing an invalid UTF-8
        // byte. We don't mind incorrect results, but writing invalid
        // UTF-8 can lead to undefined behavior, and we want this API
        // to be sound.
        assert!(n <= 9);
        self.write_ascii_char(b'0' + (n as u8));
    }

    /// Writes the given integer as a 2-digit zero padded integer to this
    /// buffer.
    ///
    /// # Panics
    ///
    /// When the available space is shorter than 2 or if `n > 99`.
    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn write_int_pad2(&mut self, n: impl Into<u64>) {
        let n = n.into();
        // This is required for correctness. When `n > 99`, then the
        // last `n as u8` below could result in writing an invalid UTF-8
        // byte. We don't mind incorrect results, but writing invalid
        // UTF-8 can lead to undefined behavior, and we want this API
        // to be sound.
        //
        // We omit the final `% 10` because it makes micro-benchmark results
        // worse. This panicking check has a more modest impact.
        assert!(n <= 99);

        let dst = self
            .available()
            .get_mut(..2)
            .expect("padded 2 digit integer exceeds available buffer space");
        let radix_offset = ((n % 100) * 2) as usize;
        // SAFETY: Valid because of the assertion above. And also,
        // `RADIX_100_ZERO` always has exactly 200 elements and
        // `radix_offset` is never greater than 198. (In that case,
        // we do access element at index 199 below as well.)
        unsafe {
            dst.get_unchecked_mut(0)
                .write(*RADIX_100_ZERO.get_unchecked(radix_offset));
            dst.get_unchecked_mut(1)
                .write(*RADIX_100_ZERO.get_unchecked(radix_offset + 1));
        }
        self.filled += 2;
    }

    /// Writes the given integer as a 2-digit space padded integer to this
    /// buffer.
    ///
    /// # Panics
    ///
    /// When the available space is shorter than 2 or if `n > 99`.
    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn write_int_pad2_space(&mut self, n: impl Into<u64>) {
        let n = n.into();
        // This is required for correctness. When `n > 99`, then the
        // last `n as u8` below could result in writing an invalid UTF-8
        // byte. We don't mind incorrect results, but writing invalid
        // UTF-8 can lead to undefined behavior, and we want this API
        // to be sound.
        //
        // We omit the final `% 10` because it makes micro-benchmark results
        // worse. This panicking check has a more modest impact.
        assert!(n <= 99);

        let dst = self
            .available()
            .get_mut(..2)
            .expect("padded 2 digit integer exceeds available buffer space");
        let radix_offset = ((n % 100) * 2) as usize;
        // SAFETY: Valid because of the assertion above. And also,
        // `RADIX_100_ZERO` always has exactly 200 elements and
        // `radix_offset` is never greater than 198. (In that case,
        // we do access element at index 199 below as well.)
        unsafe {
            dst.get_unchecked_mut(0)
                .write(*RADIX_100_SPACE.get_unchecked(radix_offset));
            dst.get_unchecked_mut(1)
                .write(*RADIX_100_SPACE.get_unchecked(radix_offset + 1));
        }
        self.filled += 2;
    }

    /// Writes the given integer as a 4-digit zero padded integer to this
    /// buffer.
    ///
    /// # Panics
    ///
    /// When the available space is shorter than 4 or if `n > 9999`.
    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn write_int_pad4(&mut self, n: impl Into<u64>) {
        let mut n = n.into();
        // This is required for correctness. When `n > 9999`, then the
        // last `n as u8` below could result in writing an invalid UTF-8
        // byte. We don't mind incorrect results, but writing invalid
        // UTF-8 can lead to undefined behavior, and we want this API
        // to be sound.
        //
        // We omit the final `% 10` because it makes micro-benchmark results
        // worse. This panicking check has a more modest impact.
        assert!(n <= 9999);

        let dst = self
            .available()
            .get_mut(..4)
            .expect("padded 4 digit integer exceeds available buffer space");

        let radix_offset = ((n % 100) * 2) as usize;
        // SAFETY: Valid because of the assertion above. And also,
        // `RADIX_100_ZERO` always has exactly 200 elements and
        // `radix_offset` is never greater than 198. (In that case,
        // we do access element at index 199 below as well.)
        unsafe {
            dst.get_unchecked_mut(2)
                .write(*RADIX_100_ZERO.get_unchecked(radix_offset));
            dst.get_unchecked_mut(3)
                .write(*RADIX_100_ZERO.get_unchecked(radix_offset + 1));
        }

        n /= 100;
        let radix_offset = ((n % 100) * 2) as usize;
        // SAFETY: Valid because of the assertion above. And also,
        // `RADIX_100_ZERO` always has exactly 200 elements and
        // `radix_offset` is never greater than 198. (In that case,
        // we do access element at index 199 below as well.)
        unsafe {
            dst.get_unchecked_mut(0)
                .write(*RADIX_100_ZERO.get_unchecked(radix_offset));
            dst.get_unchecked_mut(1)
                .write(*RADIX_100_ZERO.get_unchecked(radix_offset + 1));
        }

        self.filled += 4;
    }

    /// Writes `n` as a fractional component to the given `precision`.
    ///
    /// When `precision` is absent, then it is automatically detected based
    /// on the value of `n`.
    ///
    /// When `precision` is bigger than `9`, then it is clamped to `9`.
    ///
    /// # Panics
    ///
    /// When the available space is shorter than the number of digits required
    /// to write `n` as a fractional value.
    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn write_fraction(
        &mut self,
        precision: Option<u8>,
        mut n: u32,
    ) {
        assert!(n <= 999_999_999);
        let mut buf = ArrayBuffer::<MAX_PRECISION>::default();
        for i in (0..MAX_PRECISION).rev() {
            unsafe {
                buf.data.get_unchecked_mut(i).write(b'0' + ((n % 10) as u8));
            }
            n /= 10;
        }

        let end = precision
            .map(|p| p.min(MAX_PRECISION as u8))
            .unwrap_or_else(|| {
                // SAFETY: The loop above is guaranteed to initialize `buf` in
                // its entirety.
                let buf = unsafe { buf.assume_init() };
                let mut end = MAX_PRECISION as u8;
                while end > 0 && buf[usize::from(end) - 1] == b'0' {
                    end -= 1;
                }
                end
            });

        let buf = &buf.data[..usize::from(end)];
        self.available()
            .get_mut(..buf.len())
            .expect("fraction exceeds available buffer space")
            .copy_from_slice(buf);
        self.filled += u16::from(end);
    }

    /// Clears this buffer so that there are no filled bytes.
    ///
    /// Note that no actual clearing of data is done, but this does lose
    /// track of data that has been initialized and data that hasn't been
    /// initialized.
    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn clear(&mut self) {
        self.filled = 0;
    }

    /// Returns the filled portion of this buffer.
    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn filled(&self) -> &str {
        // SAFETY: It is guaranteed that `..self.len()` is always a valid
        // range into `self.data` since `self.filled` is only increased upon
        // a valid write.
        let filled = unsafe { self.data.get_unchecked(..self.len()) };
        // SAFETY: Everything up to `self.filled` is guaranteed to be
        // initialized. Also, since `MaybeUninit<u8>` and `u8` have the same
        // representation, we can cast from `&[MaybeUninit<u8>]` to `&[u8]`.
        // Finally, the `BorrowedBuffer` API specifically guarantees that
        // all writes to `self.data` are valid UTF-8.
        unsafe {
            core::str::from_utf8_unchecked(core::slice::from_raw_parts(
                filled.as_ptr().cast::<u8>(),
                self.len(),
            ))
        }
    }

    /// Returns the available space in this buffer.
    #[cfg_attr(feature = "perf-inline", inline(always))]
    fn available(&mut self) -> &mut [MaybeUninit<u8>] {
        // SAFETY: `self.len()` is guaranteed to be a valid offset for the
        // start of a slice into `self.data`.
        unsafe { self.data.get_unchecked_mut(self.len()..) }
    }

    /// Return the length of the "filled" in bytes.
    ///
    /// This is always equivalent to the length of the slice returned by
    /// `BorrowedBuffer::filled`.
    #[cfg_attr(feature = "perf-inline", inline(always))]
    fn len(&self) -> usize {
        usize::from(self.filled)
    }

    /// Return the total unused capacity available to this buffer.
    #[cfg_attr(feature = "perf-inline", inline(always))]
    fn available_capacity(&self) -> usize {
        self.capacity() - self.len()
    }

    /// Return the total capacity available to this buffer.
    #[cfg_attr(feature = "perf-inline", inline(always))]
    fn capacity(&self) -> usize {
        self.data.len()
    }
}

/// Construct a borrowed buffer for writing into a `&mut [u8]`.
///
/// This typically isn't useful on its own since `&mut [u8]` is already
/// guaranteed to be initialized and doesn't require handling with
/// care. However, this is useful when using with APIs that expect a
/// `BorrowedBuffer`.
///
/// # Panics
///
/// When the slice exceeds the maximum capacity supported by `BorrowedBuffer`.
impl<'data> From<&'data mut [u8]> for BorrowedBuffer<'data> {
    #[cfg_attr(feature = "perf-inline", inline(always))]
    fn from(data: &'data mut [u8]) -> BorrowedBuffer<'data> {
        assert!(
            data.len() <= MAX_CAPACITY,
            "borrowed buffer only supports {MAX_CAPACITY} bytes"
        );
        let len = data.len();
        let data: *mut MaybeUninit<u8> = data.as_mut_ptr().cast();
        // SAFETY: The length hasn't changed and `MaybeUninit<u8>` and `u8`
        // are guaranteed to have the same representation in memory.
        let data = unsafe { core::slice::from_raw_parts_mut(data, len) };
        BorrowedBuffer { data, filled: 0 }
    }
}

/// Construct a borrowed buffer directly from a slice of uninitialized data.
///
/// # Panics
///
/// When the slice exceeds the maximum capacity supported by `BorrowedBuffer`.
impl<'data> From<&'data mut [MaybeUninit<u8>]> for BorrowedBuffer<'data> {
    #[cfg_attr(feature = "perf-inline", inline(always))]
    fn from(data: &'data mut [MaybeUninit<u8>]) -> BorrowedBuffer<'data> {
        assert!(
            data.len() <= MAX_CAPACITY,
            "borrowed buffer only supports {MAX_CAPACITY} bytes"
        );
        BorrowedBuffer { data, filled: 0 }
    }
}

/// Construct a borrowed buffer directly from an array of uninitialized data.
///
/// # Panics
///
/// When the array exceeds the maximum capacity supported by `BorrowedBuffer`.
impl<'data, const N: usize> From<&'data mut [MaybeUninit<u8>; N]>
    for BorrowedBuffer<'data>
{
    #[cfg_attr(feature = "perf-inline", inline(always))]
    fn from(data: &'data mut [MaybeUninit<u8>; N]) -> BorrowedBuffer<'data> {
        BorrowedBuffer::from(&mut data[..])
    }
}

/// A buffering abstraction on top of `BorrowedBuffer`.
///
/// This lets callers make use of a monomorphic uninitialized buffer while
/// writing variable length data. For example, in use with `strftime`, where
/// the length of the resulting string can be arbitrarily long.
///
/// Essentially, once the buffer is filled up, it is emptied by writing it
/// to an underlying `jiff::fmt::Write` implementation.
///
/// # Design
///
/// We specifically do not expose the underlying `BorrowedBuffer` in this API.
/// It is too error prone because it makes it ridiculously easy for the caller
/// to try to write too much data to the buffer, thus causing a panic.
///
/// Also, we require that the total capacity of the `BorrowedBuffer` given
/// is big enough such that any of the integer formatting routines will always
/// fit. This means we don't need to break up integer formatting to support
/// pathologically small buffer sizes, e.g., 0 or 1 bytes. This is fine because
/// this is a Jiff-internal abstraction.
///
/// Callers must call `BorrowedWriter::finish` when done to ensure the internal
/// buffer is properly flushed.
///
/// One somewhat unfortunate aspect of the design here is that the integer
/// formatting routines need to know how much data is going to be written. This
/// sometimes requires doing some work to figure out. And that work is usually
/// repeated by `BorrowedBuffer`. My hope at time of writing (2026-01-02) is
/// that compiler eliminates the duplication, but I haven't actually checked
/// this yet.
///
/// `BorrowedWriter::write_str` is the only method where there is some
/// awareness of the underlying `Write` implementation. This is because the
/// string can be of arbitrary length, and thus, may exceed the size of
/// the buffer. (In which case, we pass it through directly to the `Write`
/// implementation.)
pub(crate) struct BorrowedWriter<'buffer, 'data, 'write> {
    bbuf: &'buffer mut BorrowedBuffer<'data>,
    wtr: &'write mut dyn Write,
}

impl<'buffer, 'data, 'write> BorrowedWriter<'buffer, 'data, 'write> {
    /// Creates a new borrowed writer that buffers writes in `bbuf` and flushes
    /// them to `wtr`.
    ///
    /// # Panics
    ///
    /// When `BorrowedBuffer` is too small to handle formatting a single
    /// integer (including padding).
    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn new(
        bbuf: &'buffer mut BorrowedBuffer<'data>,
        wtr: &'write mut dyn Write,
    ) -> BorrowedWriter<'buffer, 'data, 'write> {
        assert!(bbuf.capacity() >= BROAD_MINIMUM_BUFFER_LEN);
        BorrowedWriter { bbuf, wtr }
    }

    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn finish(self) -> Result<(), Error> {
        self.wtr.write_str(self.bbuf.filled())?;
        self.bbuf.clear();
        Ok(())
    }

    #[cold]
    #[inline(never)]
    pub(crate) fn flush(&mut self) -> Result<(), Error> {
        self.wtr.write_str(self.bbuf.filled())?;
        self.bbuf.clear();
        Ok(())
    }

    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn if_will_fill_then_flush(
        &mut self,
        additional: impl Into<usize>,
    ) -> Result<(), Error> {
        let n = additional.into();
        if self.bbuf.len().saturating_add(n) > self.bbuf.capacity() {
            self.flush()?;
        }
        Ok(())
    }

    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn write_str(&mut self, string: &str) -> Result<(), Error> {
        if string.len() > self.bbuf.available_capacity() {
            self.flush()?;
            if string.len() > self.bbuf.available_capacity() {
                return self.wtr.write_str(string);
            }
        }
        self.bbuf.write_str(string);
        Ok(())
    }

    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn write_char(&mut self, ch: char) -> Result<(), Error> {
        self.if_will_fill_then_flush(ch.len_utf8())?;
        self.bbuf.write_char(ch);
        Ok(())
    }

    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn write_ascii_char(&mut self, byte: u8) -> Result<(), Error> {
        if self.bbuf.available_capacity() == 0 {
            self.flush()?;
        }
        self.bbuf.write_ascii_char(byte);
        Ok(())
    }

    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn write_int_pad(
        &mut self,
        n: impl Into<u64>,
        pad_byte: u8,
        pad_len: u8,
    ) -> Result<(), Error> {
        let n = n.into();
        let pad_len = pad_len.min(MAX_INTEGER_LEN);
        let digits = pad_len.max(digits(n));
        self.if_will_fill_then_flush(digits)?;
        self.bbuf.write_int_pad(n, pad_byte, pad_len);
        Ok(())
    }

    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn write_int_pad2(
        &mut self,
        n: impl Into<u64>,
    ) -> Result<(), Error> {
        self.if_will_fill_then_flush(2usize)?;
        self.bbuf.write_int_pad2(n);
        Ok(())
    }

    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn write_int_pad2_space(
        &mut self,
        n: impl Into<u64>,
    ) -> Result<(), Error> {
        self.if_will_fill_then_flush(2usize)?;
        self.bbuf.write_int_pad2_space(n);
        Ok(())
    }

    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn write_int_pad4(
        &mut self,
        n: impl Into<u64>,
    ) -> Result<(), Error> {
        self.if_will_fill_then_flush(4usize)?;
        self.bbuf.write_int_pad4(n);
        Ok(())
    }

    #[cfg_attr(feature = "perf-inline", inline(always))]
    pub(crate) fn write_fraction(
        &mut self,
        precision: Option<u8>,
        n: u32,
    ) -> Result<(), Error> {
        // It's hard to know up front how many digits we're going to print
        // without doing the work required to print the digits. So we just
        // assume this will always write 9 digits when called. We could do
        // a little better here when `precision` is not `None`, but I'm not
        // clear if it's worth it or not. I think in practice, for common
        // cases, our uninit buffer will be big enough anyway even when we're
        // pessimistic about the number of digits we'll print.
        self.if_will_fill_then_flush(9usize)?;
        self.bbuf.write_fraction(precision, n);
        Ok(())
    }
}

/// We come full circle and make a `BorrowedWriter` implement
/// `jiff::fmt::Write`.
///
/// This is concretely useful for `strftime` and passing a borrowed writer
/// to methods on the `Custom` trait.
impl<'buffer, 'data, 'write> Write for BorrowedWriter<'buffer, 'data, 'write> {
    fn write_str(&mut self, string: &str) -> Result<(), Error> {
        BorrowedWriter::write_str(self, string)
    }
}

/// Returns the number of digits in the decimal representation of `n`.
///
/// This calculation to figure out the number of digits to write in `n` is
/// the expense we incur by having our printers write forwards. If we instead
/// wrote backwards, then we could omit this calculation. I ended up choosing
/// this design because 1) most integer writes in datetime (not span) printing
/// are fixed 2 or 4 digits, and don't require this extra computation and 2)
/// writing backwards just overall seems like a pain.
#[cfg_attr(feature = "perf-inline", inline(always))]
fn digits(n: u64) -> u8 {
    // It's faster by about 1-5% (on microbenchmarks) to make this more
    // branch-y and specialize the smaller and more common integers in lieu
    // of calling `ilog10`.
    match n {
        0..=9 => 1,
        10..=99 => 2,
        100..=999 => 3,
        1000..=9999 => 4,
        _ => n.ilog10() as u8 + 1,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn write_str_array() {
        let mut buf = ArrayBuffer::<100>::default();
        let mut bbuf = buf.as_borrowed();
        bbuf.write_str("Hello, world!");
        assert_eq!(bbuf.filled(), "Hello, world!");
        let buf = bbuf.filled();
        assert_eq!(buf, "Hello, world!");
    }

    #[test]
    fn write_int_array() {
        let mut buf = ArrayBuffer::<100>::default();
        let mut bbuf = buf.as_borrowed();

        bbuf.write_int(0u64);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "0");
        }

        bbuf.clear();
        bbuf.write_int(1u64);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "1");
        }

        bbuf.clear();
        bbuf.write_int(10u64);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "10");
        }

        bbuf.clear();
        bbuf.write_int(100u64);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "100");
        }

        bbuf.clear();
        bbuf.write_int(u64::MAX);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "18446744073709551615");
        }
    }

    #[test]
    fn write_int_pad2() {
        let mut buf = ArrayBuffer::<100>::default();
        let mut bbuf = buf.as_borrowed();

        bbuf.write_int_pad2(0u64);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "00");
        }

        bbuf.clear();
        bbuf.write_int_pad2(1u64);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "01");
        }

        bbuf.clear();
        bbuf.write_int_pad2(10u64);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "10");
        }

        bbuf.clear();
        bbuf.write_int_pad2(99u64);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "99");
        }
    }

    #[test]
    #[should_panic]
    fn write_int_pad2_panic() {
        let mut buf = ArrayBuffer::<100>::default();
        let mut bbuf = buf.as_borrowed();
        // technically unspecified behavior,
        // but should not result in undefined behavior.
        bbuf.write_int_pad2(u64::MAX);
    }

    #[test]
    fn write_int_pad4() {
        let mut buf = ArrayBuffer::<100>::default();
        let mut bbuf = buf.as_borrowed();

        bbuf.write_int_pad4(0u64);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "0000");
        }

        bbuf.clear();
        bbuf.write_int_pad4(1u64);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "0001");
        }

        bbuf.clear();
        bbuf.write_int_pad4(10u64);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "0010");
        }

        bbuf.clear();
        bbuf.write_int_pad4(99u64);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "0099");
        }

        bbuf.clear();
        bbuf.write_int_pad4(999u64);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "0999");
        }

        bbuf.clear();
        bbuf.write_int_pad4(9999u64);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "9999");
        }
    }

    #[test]
    #[should_panic]
    fn write_int_pad4_panic() {
        let mut buf = ArrayBuffer::<100>::default();
        let mut bbuf = buf.as_borrowed();
        // technically unspecified behavior,
        // but should not result in undefined behavior.
        bbuf.write_int_pad4(u64::MAX);
    }

    #[test]
    fn write_int_pad_zero() {
        let mut buf = ArrayBuffer::<100>::default();
        let mut bbuf = buf.as_borrowed();

        bbuf.write_int_pad(0u64, b'0', 0);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "0");
        }

        bbuf.clear();
        bbuf.write_int_pad(0u64, b'0', 1);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "0");
        }

        bbuf.clear();
        bbuf.write_int_pad(0u64, b'0', 2);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "00");
        }

        bbuf.clear();
        bbuf.write_int_pad(0u64, b'0', 20);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "00000000000000000000");
        }

        bbuf.clear();
        // clamped to 20
        bbuf.write_int_pad(0u64, b'0', 21);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "00000000000000000000");
        }

        bbuf.clear();
        bbuf.write_int_pad(0u64, b' ', 2);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, " 0");
        }
    }

    #[test]
    fn write_int_pad_one() {
        let mut buf = ArrayBuffer::<100>::default();
        let mut bbuf = buf.as_borrowed();

        bbuf.write_int_pad(1u64, b'0', 0);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "1");
        }

        bbuf.clear();
        bbuf.write_int_pad(1u64, b'0', 1);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "1");
        }

        bbuf.clear();
        bbuf.write_int_pad(1u64, b'0', 2);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "01");
        }

        bbuf.clear();
        bbuf.write_int_pad(1u64, b'0', 20);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "00000000000000000001");
        }

        bbuf.clear();
        // clamped to 20
        bbuf.write_int_pad(1u64, b'0', 21);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "00000000000000000001");
        }

        bbuf.clear();
        bbuf.write_int_pad(1u64, b' ', 2);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, " 1");
        }
    }

    #[test]
    fn write_int_pad_max() {
        let mut buf = ArrayBuffer::<100>::default();
        let mut bbuf = buf.as_borrowed();

        bbuf.write_int_pad(u64::MAX, b'0', 0);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "18446744073709551615");
        }

        bbuf.clear();
        bbuf.write_int_pad(u64::MAX, b'0', 1);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "18446744073709551615");
        }

        bbuf.clear();
        bbuf.write_int_pad(u64::MAX, b'0', 2);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "18446744073709551615");
        }

        bbuf.clear();
        bbuf.write_int_pad(u64::MAX, b'0', 20);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "18446744073709551615");
        }

        bbuf.clear();
        // clamped to 20
        bbuf.write_int_pad(u64::MAX, b'0', 21);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "18446744073709551615");
        }

        bbuf.clear();
        bbuf.write_int_pad(u64::MAX, b' ', 2);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "18446744073709551615");
        }
    }

    #[test]
    #[should_panic]
    fn write_int_pad_non_ascii_panic() {
        let mut buf = ArrayBuffer::<100>::default();
        let mut bbuf = buf.as_borrowed();
        bbuf.write_int_pad(0u64, 0xFF, 0);
    }

    #[test]
    #[should_panic]
    fn write_int_pad_insufficient_capacity_panic() {
        let mut buf = ArrayBuffer::<19>::default();
        let mut bbuf = buf.as_borrowed();
        bbuf.write_int_pad(0u64, b'0', 20);
    }

    #[test]
    fn write_fraction_no_precision() {
        let mut buf = ArrayBuffer::<100>::default();
        let mut bbuf = buf.as_borrowed();

        bbuf.write_fraction(None, 0);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "");
        }

        bbuf.clear();
        bbuf.write_fraction(None, 1);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "000000001");
        }

        bbuf.clear();
        bbuf.write_fraction(None, 123_000_000);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "123");
        }

        bbuf.clear();
        bbuf.write_fraction(None, 999_999_999);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "999999999");
        }
    }

    #[test]
    fn write_fraction_precision() {
        let mut buf = ArrayBuffer::<100>::default();
        let mut bbuf = buf.as_borrowed();

        bbuf.write_fraction(Some(0), 0);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "");
        }

        bbuf.clear();
        bbuf.write_fraction(Some(1), 0);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "0");
        }

        bbuf.clear();
        bbuf.write_fraction(Some(9), 0);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "000000000");
        }

        bbuf.clear();
        bbuf.write_fraction(Some(0), 1);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "");
        }

        bbuf.clear();
        bbuf.write_fraction(Some(9), 1);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "000000001");
        }

        bbuf.clear();
        bbuf.write_fraction(Some(0), 123_000_000);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "");
        }

        bbuf.clear();
        bbuf.write_fraction(Some(1), 123_000_000);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "1");
        }

        bbuf.clear();
        bbuf.write_fraction(Some(2), 123_000_000);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "12");
        }

        bbuf.clear();
        bbuf.write_fraction(Some(3), 123_000_000);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "123");
        }

        bbuf.clear();
        bbuf.write_fraction(Some(6), 123_000_000);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "123000");
        }

        bbuf.clear();
        bbuf.write_fraction(Some(9), 123_000_000);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "123000000");
        }

        bbuf.clear();
        // clamps to 9
        bbuf.write_fraction(Some(10), 123_000_000);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "123000000");
        }

        bbuf.clear();
        bbuf.write_fraction(Some(0), 999_999_999);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "");
        }

        bbuf.clear();
        bbuf.write_fraction(Some(1), 999_999_999);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "9");
        }

        bbuf.clear();
        bbuf.write_fraction(Some(3), 999_999_999);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "999");
        }

        bbuf.clear();
        bbuf.write_fraction(Some(6), 999_999_999);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "999999");
        }

        bbuf.clear();
        bbuf.write_fraction(Some(9), 999_999_999);
        {
            let buf = bbuf.filled();
            assert_eq!(buf, "999999999");
        }
    }

    #[test]
    #[should_panic]
    fn write_fraction_too_big_panic() {
        let mut buf = ArrayBuffer::<100>::default();
        let mut bbuf = buf.as_borrowed();
        bbuf.write_fraction(None, 1_000_000_000);
    }
}