1use core::mem::MaybeUninit;
23use crate::{Error, fmt::Write};
45const MAX_CAPACITY: usize = u16::MAXas usize;
6// From `u64::MAX.to_string().len()`.
7const MAX_INTEGER_LEN: u8 = 20;
8const MAX_PRECISION: usize = 9;
910/// The minimum buffer length required for *any* of `BorrowedBuffer`'s
11/// integer formatting APIs to work.
12///
13/// This relies on the fact that the maximum padding is clamped to `20`.
14const BROAD_MINIMUM_BUFFER_LEN: usize = 20;
1516/// All integers in the range `0..=99`, zero padded.
17const RADIX_100_ZERO: [u8; 200] = *b"00010203040506070809\
18 10111213141516171819\
19 20212223242526272829\
20 30313233343536373839\
21 40414243444546474849\
22 50515253545556575859\
23 60616263646566676869\
24 70717273747576777879\
25 80818283848586878889\
26 90919293949596979899";
2728/// All integers in the range `0..=99`, space padded.
29const RADIX_100_SPACE: [u8; 200] = *b" 0 1 2 3 4 5 6 7 8 9\
30 10111213141516171819\
31 20212223242526272829\
32 30313233343536373839\
33 40414243444546474849\
34 50515253545556575859\
35 60616263646566676869\
36 70717273747576777879\
37 80818283848586878889\
38 90919293949596979899";
3940/// An uninitialized slice of bytes of fixed size.
41///
42/// This is typically used with `BorrowedBuffer`.
43#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl<const N : usize>
::core::clone::TrivialClone for ArrayBuffer<N> {
}
#[automatically_derived]impl<const N : usize> ::core::clone::Clone for
ArrayBuffer<N> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<[MaybeUninit<u8>; N]>;
*self
}
}Clone, #[automatically_derived]impl<const N : usize> ::core::marker::Copy for
ArrayBuffer<N> {
}Copy)]
44pub(crate) struct ArrayBuffer<const N: usize> {
45 data: [MaybeUninit<u8>; N],
46}
4748impl<const N: usize> ArrayBuffer<N> {
49/// Return a writable buffer into this storage.
50#[cfg_attr(feature = "perf-inline", inline(always))]
51pub(crate) fn as_borrowed<'data>(&mut self) -> BorrowedBuffer<'_> {
52BorrowedBuffer::from(&mut self.data)
53 }
5455/// Assume this entire buffer is initialized and return it as an array.
56 ///
57 /// # Safety
58 ///
59 /// Callers must ensure the entire buffer is initialized.
60unsafe fn assume_init(self) -> [u8; N] {
61// SAFETY: Callers are responsible for ensuring that `self.data`
62 // is initialized. Otherwise, `MaybeUninit<u8>` and `u8` have the
63 // same representation.
64unsafe {
65*(&self.data as *const [MaybeUninit<u8>; N] as *const [u8; N])
66 }
67 }
68}
6970/// Construct an uninitialized buffer of data of size `N`.
71impl<const N: usize> Defaultfor ArrayBuffer<N> {
72#[cfg_attr(feature = "perf-inline", inline(always))]
73fn default() -> ArrayBuffer<N> {
74ArrayBuffer { data: [MaybeUninit::uninit(); N] }
75 }
76}
7778/// A borrowed buffer for writing into an uninitialized slice of bytes.
79///
80/// This can be used with, e.g., an `ArrayBuffer` as backing storage. This
81/// type will managed actually writing to the backing storage, keeping track
82/// of how much data has been written and exposing a safe API.
83///
84/// This type is principally used in Jiff's printer implementations. In
85/// particular, this helps printers generate tighter and more efficient code.
86/// Once printing is done, the data in the buffer is then copied to the caller
87/// provided implementation of `jiff::fmt::Write`. This double write is
88/// unfortunate, but it turned out that threading a `jiff::fmt::Write` down
89/// through the printers and using it directly leads to slower code overall
90/// *and* more code bloat. This is because a `BorrowedBuffer` is an incredibly
91/// lightweight abstraction that never has to deal with I/O or growing an
92/// allocation.
93///
94/// # Design
95///
96/// * Requires valid UTF-8 so that we can provide higher level safe APIs for
97/// interfacing with `String`.
98/// * Specifically panics when a write would exceed available capacity. This
99/// introduces a branch, but effectively decouples "get the maximum size
100/// correct" from "is memory safe."
101#[derive(#[automatically_derived]impl<'data> ::core::fmt::Debug for
BorrowedBuffer<'data> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"BorrowedBuffer data filled", &self.data, &&self.filled)
}
}Debug)]
102pub(crate) struct BorrowedBuffer<'data> {
103 data: &'data mut [MaybeUninit<u8>],
104 filled: u16,
105}
106107impl<'data> BorrowedBuffer<'data> {
108/// A high level API for writing to a `jiff::fmt::Write` via a buffer of
109 /// uninitialized bytes.
110 ///
111 /// When the `alloc` crate feature is enabled and `W` provides a
112 /// `&mut Vec<u8>`, then the buffer is extracted directly from the
113 /// spare capacity of the `Vec<u8>`.
114#[cfg_attr(feature = "perf-inline", inline(always))]
115pub(crate) fn with_writer<const N: usize>(
116 wtr: &mut dyn Write,
117 _runtime_allocation: usize,
118mut with: impl FnMut(&mut BorrowedBuffer<'_>) -> Result<(), Error>,
119 ) -> Result<(), Error> {
120// Specialize for the common case of `W = String` or `W = Vec<u8>`.
121 // In effect, we write directly into the excess capacity of `W`
122 // instead of first writing into a stack array and then copying that
123 // into `W`.
124 //
125 // This can provide up to a 40% improvement in runtime in some
126 // microbenchmarks.
127 //
128 // SAFETY: We only ever write valid UTF-8. Namely, `BorrowedBuffer`
129 // enforces this invariant.
130#[cfg(feature = "alloc")]
131if let Some(buf) = unsafe { wtr.as_mut_vec() } {
132buf.reserve(_runtime_allocation);
133return BorrowedBuffer::with_vec_spare_capacity(buf, with);
134 }
135let mut buf = ArrayBuffer::<N>::default();
136let mut bbuf = buf.as_borrowed();
137 with(&mut bbuf)?;
138 wtr.write_str(bbuf.filled())?;
139Ok(())
140 }
141142/// Provides a borrowed buffer into the first 255 bytes of the spare
143 /// capacity in the given `Vec<u8>` and updates the length on `Vec<u8>`
144 /// after the closure completes to account for any new data written.
145 ///
146 /// In effect, this safely encapsulates writing into the uninitialized
147 /// portion of a `Vec<u8>`.
148 ///
149 /// If the provided closure panics, then there is no guarantee that the
150 /// `buf`'s length will be updated to reflect what has been written.
151 /// However, it is guaranteed that the length setting will not lead to
152 /// undefined behavior.
153#[cfg(feature = "alloc")]
154 #[cfg_attr(feature = "perf-inline", inline(always))]
155pub(crate) fn with_vec_spare_capacity<T>(
156 buf: &'data mut alloc::vec::Vec<u8>,
157mut with: impl FnMut(&mut BorrowedBuffer<'_>) -> T,
158 ) -> T {
159let old_len = buf.len();
160let mut bbuf = BorrowedBuffer::from_vec_spare_capacity(buf);
161let returned = with(&mut bbuf);
162let new_len = bbuf.len();
163// SAFETY: `new_len` always reflects the number of bytes that have been
164 // written to. Moreover, the buffer provided may not be empty, in which
165 // case `old_len` reflects the number of bytes already there. Thus, the
166 // data up to the given new length is guaranteed to be initialized.
167 //
168 // Note that the addition here is guaranteed not to overflow (and
169 // thus potentially wrap in release mode) since it reflects the total
170 // capacity of `buf`. If it overflowed, then it would imply that the
171 // capacity for `buf` was invalid.
172unsafe {
173buf.set_len(old_len + new_len);
174 }
175returned176 }
177178/// Build a borrowed buffer for writing into the spare capacity of a
179 /// `Vec<u8>` allocation.
180 ///
181 /// This is limited only to the first `255` bytes of the spare capacity.
182#[cfg(feature = "alloc")]
183 #[cfg_attr(feature = "perf-inline", inline(always))]
184pub(crate) fn from_vec_spare_capacity(
185 vec: &'data mut alloc::vec::Vec<u8>,
186 ) -> BorrowedBuffer<'data> {
187let data = vec.spare_capacity_mut();
188let len = data.len().min(MAX_CAPACITY);
189BorrowedBuffer::from(&mut data[..len])
190 }
191192/// Write the provided string to the available space in this buffer.
193 ///
194 /// # Panics
195 ///
196 /// When the available space is shorter than the length of the provided
197 /// string. That is, when `capacity() - filled().len() < string.len()`.
198#[cfg_attr(feature = "perf-inline", inline(always))]
199pub(crate) fn write_str(&mut self, string: &str) {
200// SAFETY: A `&str`, `&[u8]` and `&[MaybeUninit<u8>]` all have the
201 // same representation in memory.
202let data: &[MaybeUninit<u8>] = unsafe {
203 core::slice::from_raw_parts(
204string.as_ptr().cast::<MaybeUninit<u8>>(),
205string.len(),
206 )
207 };
208self.available()
209 .get_mut(..string.len())
210 .expect("string data exceeds available buffer space")
211 .copy_from_slice(data);
212// Cast here will never truncate because `BorrowedBuffer` is limited
213 // to `u16::MAX` in total capacity. Above will panic if `string.len()`
214 // exceeds available capacity, which can never be above total capacity.
215 // Thus, if we're here, `string.len() <= u16::MAX` is guaranteed to
216 // hold.
217self.filled += string.len() as u16;
218 }
219220/// Writes the given Unicode scalar value (as UTF-8) to this writer.
221 ///
222 /// # Panics
223 ///
224 /// When the available space is shorter than the UTF-8 encoding of the
225 /// given Unicode scalar value (up to and including 4 bytes).
226#[cfg_attr(feature = "perf-inline", inline(always))]
227pub(crate) fn write_char(&mut self, ch: char) {
228self.write_str(ch.encode_utf8(&mut [0; 4]));
229 }
230231/// Writes the given ASCII byte to this writer.
232 ///
233 /// # Panics
234 ///
235 /// When the available space is shorter than 1 or if `byte` is not ASCII.
236#[cfg_attr(feature = "perf-inline", inline(always))]
237pub(crate) fn write_ascii_char(&mut self, byte: u8) {
238if !byte.is_ascii() {
::core::panicking::panic("assertion failed: byte.is_ascii()")
};assert!(byte.is_ascii());
239self.available()
240 .get_mut(0)
241 .expect("insufficient buffer space to write one byte")
242 .write(byte);
243self.filled += 1;
244 }
245246/// Writes the given `u8` integer to this buffer. No padding is performed.
247 ///
248 /// # Panics
249 ///
250 /// When the available space is insufficient to encode the number of
251 /// digits in the decimal representation of `n`.
252#[cfg_attr(feature = "perf-inline", inline(always))]
253pub(crate) fn write_int(&mut self, n: impl Into<u64>) {
254let mut n = n.into();
255let digits = digits(n);
256let mut remaining_digits = usize::from(digits);
257let available = self258 .available()
259 .get_mut(..remaining_digits)
260 .expect("u8 integer digits exceeds available buffer space");
261while remaining_digits > 0 {
262 remaining_digits -= 1;
263// SAFETY: The assert above guarantees that `remaining_digits` is
264 // always in bounds.
265unsafe {
266 available
267 .get_unchecked_mut(remaining_digits)
268 .write(b'0' + ((n % 10) as u8));
269 }
270 n /= 10;
271 }
272self.filled += u16::from(digits);
273 }
274275/// Writes the given `u8` integer to this buffer using the given padding.
276 ///
277 /// The maximum allowed padding is `20`. Any values bigger than that are
278 /// silently clamped to `20`.
279 ///
280 /// This always pads with zeroes.
281 ///
282 /// # Panics
283 ///
284 /// When the available space is insufficient to encode the number of
285 /// digits in the decimal representation of `n`.
286 ///
287 /// This also panics when `pad_byte` is not ASCII.
288#[cfg_attr(feature = "perf-inline", inline(always))]
289pub(crate) fn write_int_pad0(&mut self, n: impl Into<u64>, pad_len: u8) {
290let mut n = n.into();
291let pad_len = pad_len.min(MAX_INTEGER_LEN);
292let digits = pad_len.max(digits(n));
293let mut remaining_digits = usize::from(digits);
294let available = self295 .available()
296 .get_mut(..remaining_digits)
297 .expect("u8 integer digits exceeds available buffer space");
298while remaining_digits > 0 {
299 remaining_digits -= 1;
300// SAFETY: The assert above guarantees that `remaining_digits` is
301 // always in bounds.
302unsafe {
303 available
304 .get_unchecked_mut(remaining_digits)
305 .write(b'0' + ((n % 10) as u8));
306 }
307 n /= 10;
308 }
309self.filled += u16::from(digits);
310 }
311312/// Writes the given `u8` integer to this buffer using the given padding.
313 ///
314 /// The maximum allowed padding is `20`. Any values bigger than that are
315 /// silently clamped to `20`.
316 ///
317 /// # Panics
318 ///
319 /// When the available space is insufficient to encode the number of
320 /// digits in the decimal representation of `n`.
321 ///
322 /// This also panics when `pad_byte` is not ASCII.
323#[cfg_attr(feature = "perf-inline", inline(always))]
324pub(crate) fn write_int_pad(
325&mut self,
326 n: impl Into<u64>,
327 pad_byte: u8,
328 pad_len: u8,
329 ) {
330if !pad_byte.is_ascii() {
{
::core::panicking::panic_fmt(format_args!("padding byte must be ASCII"));
}
};assert!(pad_byte.is_ascii(), "padding byte must be ASCII");
331332let mut n = n.into();
333let pad_len = pad_len.min(MAX_INTEGER_LEN);
334let digits = pad_len.max(digits(n));
335let mut remaining_digits = usize::from(digits);
336let available = self337 .available()
338 .get_mut(..remaining_digits)
339 .expect("u8 integer digits exceeds available buffer space");
340while remaining_digits > 0 {
341 remaining_digits -= 1;
342// SAFETY: The assert above guarantees that `remaining_digits` is
343 // always in bounds.
344unsafe {
345 available
346 .get_unchecked_mut(remaining_digits)
347 .write(b'0' + ((n % 10) as u8));
348 }
349 n /= 10;
350if n == 0 {
351break;
352 }
353 }
354while remaining_digits > 0 {
355 remaining_digits -= 1;
356// SAFETY: The assert above guarantees that `remaining_digits` is
357 // always in bounds.
358unsafe {
359 available.get_unchecked_mut(remaining_digits).write(pad_byte);
360 }
361 }
362self.filled += u16::from(digits);
363 }
364365/// Writes the given integer as a 1-digit integer.
366 ///
367 /// # Panics
368 ///
369 /// When the available space is shorter than 1 or if `n > 9`.
370#[cfg_attr(feature = "perf-inline", inline(always))]
371pub(crate) fn write_int1(&mut self, n: impl Into<u64>) {
372let n = n.into();
373// This is required for correctness. When `n > 9`, then the
374 // `n as u8` below could result in writing an invalid UTF-8
375 // byte. We don't mind incorrect results, but writing invalid
376 // UTF-8 can lead to undefined behavior, and we want this API
377 // to be sound.
378if !(n <= 9) { ::core::panicking::panic("assertion failed: n <= 9") };assert!(n <= 9);
379self.write_ascii_char(b'0' + (nas u8));
380 }
381382/// Writes the given integer as a 2-digit zero padded integer to this
383 /// buffer.
384 ///
385 /// # Panics
386 ///
387 /// When the available space is shorter than 2 or if `n > 99`.
388#[cfg_attr(feature = "perf-inline", inline(always))]
389pub(crate) fn write_int_pad2(&mut self, n: impl Into<u64>) {
390let n = n.into();
391// This is required for correctness. When `n > 99`, then the
392 // last `n as u8` below could result in writing an invalid UTF-8
393 // byte. We don't mind incorrect results, but writing invalid
394 // UTF-8 can lead to undefined behavior, and we want this API
395 // to be sound.
396 //
397 // We omit the final `% 10` because it makes micro-benchmark results
398 // worse. This panicking check has a more modest impact.
399if !(n <= 99) { ::core::panicking::panic("assertion failed: n <= 99") };assert!(n <= 99);
400401let dst = self402 .available()
403 .get_mut(..2)
404 .expect("padded 2 digit integer exceeds available buffer space");
405let radix_offset = ((n % 100) * 2) as usize;
406// SAFETY: Valid because of the assertion above. And also,
407 // `RADIX_100_ZERO` always has exactly 200 elements and
408 // `radix_offset` is never greater than 198. (In that case,
409 // we do access element at index 199 below as well.)
410unsafe {
411dst.get_unchecked_mut(0)
412 .write(*RADIX_100_ZERO.get_unchecked(radix_offset));
413dst.get_unchecked_mut(1)
414 .write(*RADIX_100_ZERO.get_unchecked(radix_offset + 1));
415 }
416self.filled += 2;
417 }
418419/// Writes the given integer as a 2-digit space padded integer to this
420 /// buffer.
421 ///
422 /// # Panics
423 ///
424 /// When the available space is shorter than 2 or if `n > 99`.
425#[cfg_attr(feature = "perf-inline", inline(always))]
426pub(crate) fn write_int_pad2_space(&mut self, n: impl Into<u64>) {
427let n = n.into();
428// This is required for correctness. When `n > 99`, then the
429 // last `n as u8` below could result in writing an invalid UTF-8
430 // byte. We don't mind incorrect results, but writing invalid
431 // UTF-8 can lead to undefined behavior, and we want this API
432 // to be sound.
433 //
434 // We omit the final `% 10` because it makes micro-benchmark results
435 // worse. This panicking check has a more modest impact.
436if !(n <= 99) { ::core::panicking::panic("assertion failed: n <= 99") };assert!(n <= 99);
437438let dst = self439 .available()
440 .get_mut(..2)
441 .expect("padded 2 digit integer exceeds available buffer space");
442let radix_offset = ((n % 100) * 2) as usize;
443// SAFETY: Valid because of the assertion above. And also,
444 // `RADIX_100_ZERO` always has exactly 200 elements and
445 // `radix_offset` is never greater than 198. (In that case,
446 // we do access element at index 199 below as well.)
447unsafe {
448dst.get_unchecked_mut(0)
449 .write(*RADIX_100_SPACE.get_unchecked(radix_offset));
450dst.get_unchecked_mut(1)
451 .write(*RADIX_100_SPACE.get_unchecked(radix_offset + 1));
452 }
453self.filled += 2;
454 }
455456/// Writes the given integer as a 4-digit zero padded integer to this
457 /// buffer.
458 ///
459 /// # Panics
460 ///
461 /// When the available space is shorter than 4 or if `n > 9999`.
462#[cfg_attr(feature = "perf-inline", inline(always))]
463pub(crate) fn write_int_pad4(&mut self, n: impl Into<u64>) {
464let mut n = n.into();
465// This is required for correctness. When `n > 9999`, then the
466 // last `n as u8` below could result in writing an invalid UTF-8
467 // byte. We don't mind incorrect results, but writing invalid
468 // UTF-8 can lead to undefined behavior, and we want this API
469 // to be sound.
470 //
471 // We omit the final `% 10` because it makes micro-benchmark results
472 // worse. This panicking check has a more modest impact.
473if !(n <= 9999) { ::core::panicking::panic("assertion failed: n <= 9999") };assert!(n <= 9999);
474475let dst = self476 .available()
477 .get_mut(..4)
478 .expect("padded 4 digit integer exceeds available buffer space");
479480let radix_offset = ((n % 100) * 2) as usize;
481// SAFETY: Valid because of the assertion above. And also,
482 // `RADIX_100_ZERO` always has exactly 200 elements and
483 // `radix_offset` is never greater than 198. (In that case,
484 // we do access element at index 199 below as well.)
485unsafe {
486dst.get_unchecked_mut(2)
487 .write(*RADIX_100_ZERO.get_unchecked(radix_offset));
488dst.get_unchecked_mut(3)
489 .write(*RADIX_100_ZERO.get_unchecked(radix_offset + 1));
490 }
491492n /= 100;
493let radix_offset = ((n % 100) * 2) as usize;
494// SAFETY: Valid because of the assertion above. And also,
495 // `RADIX_100_ZERO` always has exactly 200 elements and
496 // `radix_offset` is never greater than 198. (In that case,
497 // we do access element at index 199 below as well.)
498unsafe {
499dst.get_unchecked_mut(0)
500 .write(*RADIX_100_ZERO.get_unchecked(radix_offset));
501dst.get_unchecked_mut(1)
502 .write(*RADIX_100_ZERO.get_unchecked(radix_offset + 1));
503 }
504505self.filled += 4;
506 }
507508/// Writes `n` as a fractional component to the given `precision`.
509 ///
510 /// When `precision` is absent, then it is automatically detected based
511 /// on the value of `n`.
512 ///
513 /// When `precision` is bigger than `9`, then it is clamped to `9`.
514 ///
515 /// # Panics
516 ///
517 /// When the available space is shorter than the number of digits required
518 /// to write `n` as a fractional value.
519#[cfg_attr(feature = "perf-inline", inline(always))]
520pub(crate) fn write_fraction(
521&mut self,
522 precision: Option<u8>,
523mut n: u32,
524 ) {
525if !(n <= 999_999_999) {
::core::panicking::panic("assertion failed: n <= 999_999_999")
};assert!(n <= 999_999_999);
526let mut buf = ArrayBuffer::<MAX_PRECISION>::default();
527for i in (0..MAX_PRECISION).rev() {
528// SAFETY: Okay since `i` is guaranteed to be a valid index in
529 // `buf`. Namely, `buf` is created with `MAX_PRECISION` slots and
530 // `MAX_PRECISION - 1` is the largest value of `i` possible here.
531unsafe {
532 buf.data.get_unchecked_mut(i).write(b'0' + ((n % 10) as u8));
533 }
534 n /= 10;
535 }
536537let end = precision538 .map(|p| p.min(MAX_PRECISIONas u8))
539 .unwrap_or_else(|| {
540// SAFETY: The loop above is guaranteed to initialize `buf` in
541 // its entirety.
542let buf = unsafe { buf.assume_init() };
543let mut end = MAX_PRECISIONas u8;
544while end > 0 && buf[usize::from(end) - 1] == b'0' {
545 end -= 1;
546 }
547end548 });
549550let buf = &buf.data[..usize::from(end)];
551self.available()
552 .get_mut(..buf.len())
553 .expect("fraction exceeds available buffer space")
554 .copy_from_slice(buf);
555self.filled += u16::from(end);
556 }
557558/// Clears this buffer so that there are no filled bytes.
559 ///
560 /// Note that no actual clearing of data is done, but this does lose
561 /// track of data that has been initialized and data that hasn't been
562 /// initialized.
563#[cfg_attr(feature = "perf-inline", inline(always))]
564pub(crate) fn clear(&mut self) {
565self.filled = 0;
566 }
567568/// Returns the filled portion of this buffer.
569#[cfg_attr(feature = "perf-inline", inline(always))]
570pub(crate) fn filled(&self) -> &str {
571// SAFETY: It is guaranteed that `..self.len()` is always a valid
572 // range into `self.data` since `self.filled` is only increased upon
573 // a valid write.
574let filled = unsafe { self.data.get_unchecked(..self.len()) };
575// SAFETY: Everything up to `self.filled` is guaranteed to be
576 // initialized. Also, since `MaybeUninit<u8>` and `u8` have the same
577 // representation, we can cast from `&[MaybeUninit<u8>]` to `&[u8]`.
578 // Finally, the `BorrowedBuffer` API specifically guarantees that
579 // all writes to `self.data` are valid UTF-8.
580unsafe {
581 core::str::from_utf8_unchecked(core::slice::from_raw_parts(
582filled.as_ptr().cast::<u8>(),
583self.len(),
584 ))
585 }
586 }
587588/// Returns the available space in this buffer.
589#[cfg_attr(feature = "perf-inline", inline(always))]
590fn available(&mut self) -> &mut [MaybeUninit<u8>] {
591// SAFETY: `self.len()` is guaranteed to be a valid offset for the
592 // start of a slice into `self.data`.
593unsafe { self.data.get_unchecked_mut(self.len()..) }
594 }
595596/// Return the length of the "filled" in bytes.
597 ///
598 /// This is always equivalent to the length of the slice returned by
599 /// `BorrowedBuffer::filled`.
600#[cfg_attr(feature = "perf-inline", inline(always))]
601fn len(&self) -> usize {
602usize::from(self.filled)
603 }
604605/// Return the total unused capacity available to this buffer.
606#[cfg_attr(feature = "perf-inline", inline(always))]
607fn available_capacity(&self) -> usize {
608self.capacity() - self.len()
609 }
610611/// Return the total capacity available to this buffer.
612#[cfg_attr(feature = "perf-inline", inline(always))]
613fn capacity(&self) -> usize {
614self.data.len()
615 }
616}
617618/// Construct a borrowed buffer for writing into a `&mut [u8]`.
619///
620/// This typically isn't useful on its own since `&mut [u8]` is already
621/// guaranteed to be initialized and doesn't require handling with
622/// care. However, this is useful when using with APIs that expect a
623/// `BorrowedBuffer`.
624///
625/// # Panics
626///
627/// When the slice exceeds the maximum capacity supported by `BorrowedBuffer`.
628impl<'data> From<&'data mut [u8]> for BorrowedBuffer<'data> {
629#[cfg_attr(feature = "perf-inline", inline(always))]
630fn from(data: &'data mut [u8]) -> BorrowedBuffer<'data> {
631if !(data.len() <= MAX_CAPACITY) {
{
::core::panicking::panic_fmt(format_args!("borrowed buffer only supports {0} bytes",
MAX_CAPACITY));
}
};assert!(
632 data.len() <= MAX_CAPACITY,
633"borrowed buffer only supports {MAX_CAPACITY} bytes"
634);
635let len = data.len();
636let data: *mut MaybeUninit<u8> = data.as_mut_ptr().cast();
637// SAFETY: The length hasn't changed and `MaybeUninit<u8>` and `u8`
638 // are guaranteed to have the same representation in memory.
639let data = unsafe { core::slice::from_raw_parts_mut(data, len) };
640BorrowedBuffer { data, filled: 0 }
641 }
642}
643644/// Construct a borrowed buffer directly from a slice of uninitialized data.
645///
646/// # Panics
647///
648/// When the slice exceeds the maximum capacity supported by `BorrowedBuffer`.
649impl<'data> From<&'data mut [MaybeUninit<u8>]> for BorrowedBuffer<'data> {
650#[cfg_attr(feature = "perf-inline", inline(always))]
651fn from(data: &'data mut [MaybeUninit<u8>]) -> BorrowedBuffer<'data> {
652if !(data.len() <= MAX_CAPACITY) {
{
::core::panicking::panic_fmt(format_args!("borrowed buffer only supports {0} bytes",
MAX_CAPACITY));
}
};assert!(
653 data.len() <= MAX_CAPACITY,
654"borrowed buffer only supports {MAX_CAPACITY} bytes"
655);
656BorrowedBuffer { data, filled: 0 }
657 }
658}
659660/// Construct a borrowed buffer directly from an array of uninitialized data.
661///
662/// # Panics
663///
664/// When the array exceeds the maximum capacity supported by `BorrowedBuffer`.
665impl<'data, const N: usize> From<&'data mut [MaybeUninit<u8>; N]>
666for BorrowedBuffer<'data>
667{
668#[cfg_attr(feature = "perf-inline", inline(always))]
669fn from(data: &'data mut [MaybeUninit<u8>; N]) -> BorrowedBuffer<'data> {
670BorrowedBuffer::from(&mut data[..])
671 }
672}
673674/// A buffering abstraction on top of `BorrowedBuffer`.
675///
676/// This lets callers make use of a monomorphic uninitialized buffer while
677/// writing variable length data. For example, in use with `strftime`, where
678/// the length of the resulting string can be arbitrarily long.
679///
680/// Essentially, once the buffer is filled up, it is emptied by writing it
681/// to an underlying `jiff::fmt::Write` implementation.
682///
683/// # Design
684///
685/// We specifically do not expose the underlying `BorrowedBuffer` in this API.
686/// It is too error prone because it makes it ridiculously easy for the caller
687/// to try to write too much data to the buffer, thus causing a panic.
688///
689/// Also, we require that the total capacity of the `BorrowedBuffer` given
690/// is big enough such that any of the integer formatting routines will always
691/// fit. This means we don't need to break up integer formatting to support
692/// pathologically small buffer sizes, e.g., 0 or 1 bytes. This is fine because
693/// this is a Jiff-internal abstraction.
694///
695/// Callers must call `BorrowedWriter::finish` when done to ensure the internal
696/// buffer is properly flushed.
697///
698/// One somewhat unfortunate aspect of the design here is that the integer
699/// formatting routines need to know how much data is going to be written. This
700/// sometimes requires doing some work to figure out. And that work is usually
701/// repeated by `BorrowedBuffer`. My hope at time of writing (2026-01-02) is
702/// that compiler eliminates the duplication, but I haven't actually checked
703/// this yet.
704///
705/// `BorrowedWriter::write_str` is the only method where there is some
706/// awareness of the underlying `Write` implementation. This is because the
707/// string can be of arbitrary length, and thus, may exceed the size of
708/// the buffer. (In which case, we pass it through directly to the `Write`
709/// implementation.)
710pub(crate) struct BorrowedWriter<'buffer, 'data, 'write> {
711 bbuf: &'buffer mut BorrowedBuffer<'data>,
712 wtr: &'write mut dyn Write,
713}
714715impl<'buffer, 'data, 'write> BorrowedWriter<'buffer, 'data, 'write> {
716/// Creates a new borrowed writer that buffers writes in `bbuf` and flushes
717 /// them to `wtr`.
718 ///
719 /// # Panics
720 ///
721 /// When `BorrowedBuffer` is too small to handle formatting a single
722 /// integer (including padding).
723#[cfg_attr(feature = "perf-inline", inline(always))]
724pub(crate) fn new(
725 bbuf: &'buffer mut BorrowedBuffer<'data>,
726 wtr: &'write mut dyn Write,
727 ) -> BorrowedWriter<'buffer, 'data, 'write> {
728if !(bbuf.capacity() >= BROAD_MINIMUM_BUFFER_LEN) {
{
::core::panicking::panic_fmt(format_args!("capacity ({0}) must be at least {1} to handle integer formatting",
bbuf.capacity(), BROAD_MINIMUM_BUFFER_LEN));
}
};assert!(
729 bbuf.capacity() >= BROAD_MINIMUM_BUFFER_LEN,
730"capacity ({capacity}) must be \
731 at least {BROAD_MINIMUM_BUFFER_LEN} \
732 to handle integer formatting",
733 capacity = bbuf.capacity(),
734 );
735BorrowedWriter { bbuf, wtr }
736 }
737738#[cfg_attr(feature = "perf-inline", inline(always))]
739pub(crate) fn finish(self) -> Result<(), Error> {
740self.wtr.write_str(self.bbuf.filled())?;
741self.bbuf.clear();
742Ok(())
743 }
744745#[cold]
746 #[inline(never)]
747pub(crate) fn flush(&mut self) -> Result<(), Error> {
748self.wtr.write_str(self.bbuf.filled())?;
749self.bbuf.clear();
750Ok(())
751 }
752753#[cfg_attr(feature = "perf-inline", inline(always))]
754pub(crate) fn if_will_fill_then_flush(
755&mut self,
756 additional: impl Into<usize>,
757 ) -> Result<(), Error> {
758let n = additional.into();
759if self.bbuf.len().saturating_add(n) > self.bbuf.capacity() {
760self.flush()?;
761 }
762Ok(())
763 }
764765#[cfg_attr(feature = "perf-inline", inline(always))]
766pub(crate) fn write_str(&mut self, string: &str) -> Result<(), Error> {
767if string.len() > self.bbuf.available_capacity() {
768self.flush()?;
769if string.len() > self.bbuf.available_capacity() {
770return self.wtr.write_str(string);
771 }
772 }
773self.bbuf.write_str(string);
774Ok(())
775 }
776777#[cfg_attr(feature = "perf-inline", inline(always))]
778pub(crate) fn write_char(&mut self, ch: char) -> Result<(), Error> {
779self.if_will_fill_then_flush(ch.len_utf8())?;
780self.bbuf.write_char(ch);
781Ok(())
782 }
783784#[cfg_attr(feature = "perf-inline", inline(always))]
785pub(crate) fn write_ascii_char(&mut self, byte: u8) -> Result<(), Error> {
786if self.bbuf.available_capacity() == 0 {
787self.flush()?;
788 }
789self.bbuf.write_ascii_char(byte);
790Ok(())
791 }
792793#[cfg_attr(feature = "perf-inline", inline(always))]
794pub(crate) fn write_int(
795&mut self,
796 n: impl Into<u64>,
797 ) -> Result<(), Error> {
798let n = n.into();
799self.if_will_fill_then_flush(digits(n))?;
800self.bbuf.write_int(n);
801Ok(())
802 }
803804#[cfg_attr(feature = "perf-inline", inline(always))]
805pub(crate) fn write_int1(
806&mut self,
807 n: impl Into<u64>,
808 ) -> Result<(), Error> {
809let n = n.into();
810self.if_will_fill_then_flush(1usize)?;
811self.bbuf.write_int1(n);
812Ok(())
813 }
814815#[cfg_attr(feature = "perf-inline", inline(always))]
816pub(crate) fn write_int_pad(
817&mut self,
818 n: impl Into<u64>,
819 pad_byte: u8,
820 pad_len: u8,
821 ) -> Result<(), Error> {
822let n = n.into();
823let pad_len = pad_len.min(MAX_INTEGER_LEN);
824let digits = pad_len.max(digits(n));
825self.if_will_fill_then_flush(digits)?;
826self.bbuf.write_int_pad(n, pad_byte, pad_len);
827Ok(())
828 }
829830#[cfg_attr(feature = "perf-inline", inline(always))]
831pub(crate) fn write_int_pad2(
832&mut self,
833 n: impl Into<u64>,
834 ) -> Result<(), Error> {
835self.if_will_fill_then_flush(2usize)?;
836self.bbuf.write_int_pad2(n);
837Ok(())
838 }
839840#[cfg_attr(feature = "perf-inline", inline(always))]
841pub(crate) fn write_int_pad2_space(
842&mut self,
843 n: impl Into<u64>,
844 ) -> Result<(), Error> {
845self.if_will_fill_then_flush(2usize)?;
846self.bbuf.write_int_pad2_space(n);
847Ok(())
848 }
849850#[cfg_attr(feature = "perf-inline", inline(always))]
851pub(crate) fn write_int_pad4(
852&mut self,
853 n: impl Into<u64>,
854 ) -> Result<(), Error> {
855self.if_will_fill_then_flush(4usize)?;
856self.bbuf.write_int_pad4(n);
857Ok(())
858 }
859860#[cfg_attr(feature = "perf-inline", inline(always))]
861pub(crate) fn write_fraction(
862&mut self,
863 precision: Option<u8>,
864 n: u32,
865 ) -> Result<(), Error> {
866// It's hard to know up front how many digits we're going to print
867 // without doing the work required to print the digits. So we just
868 // assume this will always write 9 digits when called. We could do
869 // a little better here when `precision` is not `None`, but I'm not
870 // clear if it's worth it or not. I think in practice, for common
871 // cases, our uninit buffer will be big enough anyway even when we're
872 // pessimistic about the number of digits we'll print.
873self.if_will_fill_then_flush(9usize)?;
874self.bbuf.write_fraction(precision, n);
875Ok(())
876 }
877}
878879/// We come full circle and make a `BorrowedWriter` implement
880/// `jiff::fmt::Write`.
881///
882/// This is concretely useful for `strftime` and passing a borrowed writer
883/// to methods on the `Custom` trait.
884impl<'buffer, 'data, 'write> Writefor BorrowedWriter<'buffer, 'data, 'write> {
885fn write_str(&mut self, string: &str) -> Result<(), Error> {
886BorrowedWriter::write_str(self, string)
887 }
888}
889890/// Returns the number of digits in the decimal representation of `n`.
891///
892/// This calculation to figure out the number of digits to write in `n` is
893/// the expense we incur by having our printers write forwards. If we instead
894/// wrote backwards, then we could omit this calculation. I ended up choosing
895/// this design because 1) most integer writes in datetime (not span) printing
896/// are fixed 2 or 4 digits, and don't require this extra computation and 2)
897/// writing backwards just overall seems like a pain.
898#[cfg_attr(feature = "perf-inline", inline(always))]
899fn digits(n: u64) -> u8 {
900// It's faster by about 1-5% (on microbenchmarks) to make this more
901 // branch-y and specialize the smaller and more common integers in lieu
902 // of calling `ilog10`.
903match n {
9040..=9 => 1,
90510..=99 => 2,
906100..=999 => 3,
9071000..=9999 => 4,
908_ => n.ilog10() as u8 + 1,
909 }
910}
911912#[cfg(test)]
913mod tests {
914use super::*;
915916#[test]
917fn write_str_array() {
918let mut buf = ArrayBuffer::<100>::default();
919let mut bbuf = buf.as_borrowed();
920 bbuf.write_str("Hello, world!");
921assert_eq!(bbuf.filled(), "Hello, world!");
922let buf = bbuf.filled();
923assert_eq!(buf, "Hello, world!");
924 }
925926#[test]
927fn write_int_array() {
928let mut buf = ArrayBuffer::<100>::default();
929let mut bbuf = buf.as_borrowed();
930931 bbuf.write_int(0u64);
932 {
933let buf = bbuf.filled();
934assert_eq!(buf, "0");
935 }
936937 bbuf.clear();
938 bbuf.write_int(1u64);
939 {
940let buf = bbuf.filled();
941assert_eq!(buf, "1");
942 }
943944 bbuf.clear();
945 bbuf.write_int(10u64);
946 {
947let buf = bbuf.filled();
948assert_eq!(buf, "10");
949 }
950951 bbuf.clear();
952 bbuf.write_int(100u64);
953 {
954let buf = bbuf.filled();
955assert_eq!(buf, "100");
956 }
957958 bbuf.clear();
959 bbuf.write_int(u64::MAX);
960 {
961let buf = bbuf.filled();
962assert_eq!(buf, "18446744073709551615");
963 }
964 }
965966#[test]
967fn write_int_pad2() {
968let mut buf = ArrayBuffer::<100>::default();
969let mut bbuf = buf.as_borrowed();
970971 bbuf.write_int_pad2(0u64);
972 {
973let buf = bbuf.filled();
974assert_eq!(buf, "00");
975 }
976977 bbuf.clear();
978 bbuf.write_int_pad2(1u64);
979 {
980let buf = bbuf.filled();
981assert_eq!(buf, "01");
982 }
983984 bbuf.clear();
985 bbuf.write_int_pad2(10u64);
986 {
987let buf = bbuf.filled();
988assert_eq!(buf, "10");
989 }
990991 bbuf.clear();
992 bbuf.write_int_pad2(99u64);
993 {
994let buf = bbuf.filled();
995assert_eq!(buf, "99");
996 }
997 }
998999#[test]
1000 #[should_panic]
1001fn write_int_pad2_panic() {
1002let mut buf = ArrayBuffer::<100>::default();
1003let mut bbuf = buf.as_borrowed();
1004// technically unspecified behavior,
1005 // but should not result in undefined behavior.
1006bbuf.write_int_pad2(u64::MAX);
1007 }
10081009#[test]
1010fn write_int_pad4() {
1011let mut buf = ArrayBuffer::<100>::default();
1012let mut bbuf = buf.as_borrowed();
10131014 bbuf.write_int_pad4(0u64);
1015 {
1016let buf = bbuf.filled();
1017assert_eq!(buf, "0000");
1018 }
10191020 bbuf.clear();
1021 bbuf.write_int_pad4(1u64);
1022 {
1023let buf = bbuf.filled();
1024assert_eq!(buf, "0001");
1025 }
10261027 bbuf.clear();
1028 bbuf.write_int_pad4(10u64);
1029 {
1030let buf = bbuf.filled();
1031assert_eq!(buf, "0010");
1032 }
10331034 bbuf.clear();
1035 bbuf.write_int_pad4(99u64);
1036 {
1037let buf = bbuf.filled();
1038assert_eq!(buf, "0099");
1039 }
10401041 bbuf.clear();
1042 bbuf.write_int_pad4(999u64);
1043 {
1044let buf = bbuf.filled();
1045assert_eq!(buf, "0999");
1046 }
10471048 bbuf.clear();
1049 bbuf.write_int_pad4(9999u64);
1050 {
1051let buf = bbuf.filled();
1052assert_eq!(buf, "9999");
1053 }
1054 }
10551056#[test]
1057 #[should_panic]
1058fn write_int_pad4_panic() {
1059let mut buf = ArrayBuffer::<100>::default();
1060let mut bbuf = buf.as_borrowed();
1061// technically unspecified behavior,
1062 // but should not result in undefined behavior.
1063bbuf.write_int_pad4(u64::MAX);
1064 }
10651066#[test]
1067fn write_int_pad_zero() {
1068let mut buf = ArrayBuffer::<100>::default();
1069let mut bbuf = buf.as_borrowed();
10701071 bbuf.write_int_pad(0u64, b'0', 0);
1072 {
1073let buf = bbuf.filled();
1074assert_eq!(buf, "0");
1075 }
10761077 bbuf.clear();
1078 bbuf.write_int_pad(0u64, b'0', 1);
1079 {
1080let buf = bbuf.filled();
1081assert_eq!(buf, "0");
1082 }
10831084 bbuf.clear();
1085 bbuf.write_int_pad(0u64, b'0', 2);
1086 {
1087let buf = bbuf.filled();
1088assert_eq!(buf, "00");
1089 }
10901091 bbuf.clear();
1092 bbuf.write_int_pad(0u64, b'0', 20);
1093 {
1094let buf = bbuf.filled();
1095assert_eq!(buf, "00000000000000000000");
1096 }
10971098 bbuf.clear();
1099// clamped to 20
1100bbuf.write_int_pad(0u64, b'0', 21);
1101 {
1102let buf = bbuf.filled();
1103assert_eq!(buf, "00000000000000000000");
1104 }
11051106 bbuf.clear();
1107 bbuf.write_int_pad(0u64, b' ', 2);
1108 {
1109let buf = bbuf.filled();
1110assert_eq!(buf, " 0");
1111 }
1112 }
11131114#[test]
1115fn write_int_pad_one() {
1116let mut buf = ArrayBuffer::<100>::default();
1117let mut bbuf = buf.as_borrowed();
11181119 bbuf.write_int_pad(1u64, b'0', 0);
1120 {
1121let buf = bbuf.filled();
1122assert_eq!(buf, "1");
1123 }
11241125 bbuf.clear();
1126 bbuf.write_int_pad(1u64, b'0', 1);
1127 {
1128let buf = bbuf.filled();
1129assert_eq!(buf, "1");
1130 }
11311132 bbuf.clear();
1133 bbuf.write_int_pad(1u64, b'0', 2);
1134 {
1135let buf = bbuf.filled();
1136assert_eq!(buf, "01");
1137 }
11381139 bbuf.clear();
1140 bbuf.write_int_pad(1u64, b'0', 20);
1141 {
1142let buf = bbuf.filled();
1143assert_eq!(buf, "00000000000000000001");
1144 }
11451146 bbuf.clear();
1147// clamped to 20
1148bbuf.write_int_pad(1u64, b'0', 21);
1149 {
1150let buf = bbuf.filled();
1151assert_eq!(buf, "00000000000000000001");
1152 }
11531154 bbuf.clear();
1155 bbuf.write_int_pad(1u64, b' ', 2);
1156 {
1157let buf = bbuf.filled();
1158assert_eq!(buf, " 1");
1159 }
1160 }
11611162#[test]
1163fn write_int_pad_max() {
1164let mut buf = ArrayBuffer::<100>::default();
1165let mut bbuf = buf.as_borrowed();
11661167 bbuf.write_int_pad(u64::MAX, b'0', 0);
1168 {
1169let buf = bbuf.filled();
1170assert_eq!(buf, "18446744073709551615");
1171 }
11721173 bbuf.clear();
1174 bbuf.write_int_pad(u64::MAX, b'0', 1);
1175 {
1176let buf = bbuf.filled();
1177assert_eq!(buf, "18446744073709551615");
1178 }
11791180 bbuf.clear();
1181 bbuf.write_int_pad(u64::MAX, b'0', 2);
1182 {
1183let buf = bbuf.filled();
1184assert_eq!(buf, "18446744073709551615");
1185 }
11861187 bbuf.clear();
1188 bbuf.write_int_pad(u64::MAX, b'0', 20);
1189 {
1190let buf = bbuf.filled();
1191assert_eq!(buf, "18446744073709551615");
1192 }
11931194 bbuf.clear();
1195// clamped to 20
1196bbuf.write_int_pad(u64::MAX, b'0', 21);
1197 {
1198let buf = bbuf.filled();
1199assert_eq!(buf, "18446744073709551615");
1200 }
12011202 bbuf.clear();
1203 bbuf.write_int_pad(u64::MAX, b' ', 2);
1204 {
1205let buf = bbuf.filled();
1206assert_eq!(buf, "18446744073709551615");
1207 }
1208 }
12091210#[test]
1211 #[should_panic]
1212fn write_int_pad_non_ascii_panic() {
1213let mut buf = ArrayBuffer::<100>::default();
1214let mut bbuf = buf.as_borrowed();
1215 bbuf.write_int_pad(0u64, 0xFF, 0);
1216 }
12171218#[test]
1219 #[should_panic]
1220fn write_int_pad_insufficient_capacity_panic() {
1221let mut buf = ArrayBuffer::<19>::default();
1222let mut bbuf = buf.as_borrowed();
1223 bbuf.write_int_pad(0u64, b'0', 20);
1224 }
12251226#[test]
1227fn write_fraction_no_precision() {
1228let mut buf = ArrayBuffer::<100>::default();
1229let mut bbuf = buf.as_borrowed();
12301231 bbuf.write_fraction(None, 0);
1232 {
1233let buf = bbuf.filled();
1234assert_eq!(buf, "");
1235 }
12361237 bbuf.clear();
1238 bbuf.write_fraction(None, 1);
1239 {
1240let buf = bbuf.filled();
1241assert_eq!(buf, "000000001");
1242 }
12431244 bbuf.clear();
1245 bbuf.write_fraction(None, 123_000_000);
1246 {
1247let buf = bbuf.filled();
1248assert_eq!(buf, "123");
1249 }
12501251 bbuf.clear();
1252 bbuf.write_fraction(None, 999_999_999);
1253 {
1254let buf = bbuf.filled();
1255assert_eq!(buf, "999999999");
1256 }
1257 }
12581259#[test]
1260fn write_fraction_precision() {
1261let mut buf = ArrayBuffer::<100>::default();
1262let mut bbuf = buf.as_borrowed();
12631264 bbuf.write_fraction(Some(0), 0);
1265 {
1266let buf = bbuf.filled();
1267assert_eq!(buf, "");
1268 }
12691270 bbuf.clear();
1271 bbuf.write_fraction(Some(1), 0);
1272 {
1273let buf = bbuf.filled();
1274assert_eq!(buf, "0");
1275 }
12761277 bbuf.clear();
1278 bbuf.write_fraction(Some(9), 0);
1279 {
1280let buf = bbuf.filled();
1281assert_eq!(buf, "000000000");
1282 }
12831284 bbuf.clear();
1285 bbuf.write_fraction(Some(0), 1);
1286 {
1287let buf = bbuf.filled();
1288assert_eq!(buf, "");
1289 }
12901291 bbuf.clear();
1292 bbuf.write_fraction(Some(9), 1);
1293 {
1294let buf = bbuf.filled();
1295assert_eq!(buf, "000000001");
1296 }
12971298 bbuf.clear();
1299 bbuf.write_fraction(Some(0), 123_000_000);
1300 {
1301let buf = bbuf.filled();
1302assert_eq!(buf, "");
1303 }
13041305 bbuf.clear();
1306 bbuf.write_fraction(Some(1), 123_000_000);
1307 {
1308let buf = bbuf.filled();
1309assert_eq!(buf, "1");
1310 }
13111312 bbuf.clear();
1313 bbuf.write_fraction(Some(2), 123_000_000);
1314 {
1315let buf = bbuf.filled();
1316assert_eq!(buf, "12");
1317 }
13181319 bbuf.clear();
1320 bbuf.write_fraction(Some(3), 123_000_000);
1321 {
1322let buf = bbuf.filled();
1323assert_eq!(buf, "123");
1324 }
13251326 bbuf.clear();
1327 bbuf.write_fraction(Some(6), 123_000_000);
1328 {
1329let buf = bbuf.filled();
1330assert_eq!(buf, "123000");
1331 }
13321333 bbuf.clear();
1334 bbuf.write_fraction(Some(9), 123_000_000);
1335 {
1336let buf = bbuf.filled();
1337assert_eq!(buf, "123000000");
1338 }
13391340 bbuf.clear();
1341// clamps to 9
1342bbuf.write_fraction(Some(10), 123_000_000);
1343 {
1344let buf = bbuf.filled();
1345assert_eq!(buf, "123000000");
1346 }
13471348 bbuf.clear();
1349 bbuf.write_fraction(Some(0), 999_999_999);
1350 {
1351let buf = bbuf.filled();
1352assert_eq!(buf, "");
1353 }
13541355 bbuf.clear();
1356 bbuf.write_fraction(Some(1), 999_999_999);
1357 {
1358let buf = bbuf.filled();
1359assert_eq!(buf, "9");
1360 }
13611362 bbuf.clear();
1363 bbuf.write_fraction(Some(3), 999_999_999);
1364 {
1365let buf = bbuf.filled();
1366assert_eq!(buf, "999");
1367 }
13681369 bbuf.clear();
1370 bbuf.write_fraction(Some(6), 999_999_999);
1371 {
1372let buf = bbuf.filled();
1373assert_eq!(buf, "999999");
1374 }
13751376 bbuf.clear();
1377 bbuf.write_fraction(Some(9), 999_999_999);
1378 {
1379let buf = bbuf.filled();
1380assert_eq!(buf, "999999999");
1381 }
1382 }
13831384#[test]
1385 #[should_panic]
1386fn write_fraction_too_big_panic() {
1387let mut buf = ArrayBuffer::<100>::default();
1388let mut bbuf = buf.as_borrowed();
1389 bbuf.write_fraction(None, 1_000_000_000);
1390 }
13911392/// This tests that writing into an empty buffer is okay.
1393 ///
1394 /// This always worked, but we test it along with a non-empty buffer below
1395 /// for completeness.
1396 ///
1397 /// Ref: https://github.com/BurntSushi/jiff/issues/592
1398#[cfg(feature = "alloc")]
1399 #[test]
1400fn spare_capacity_empty_buffer() {
1401use crate::{civil::date, fmt::temporal::DateTimePrinter};
14021403let mut s = alloc::string::String::new();
1404let printer = DateTimePrinter::new();
1405let d = date(2024, 6, 15);
1406 printer.print_date(&d, &mut s).unwrap();
1407assert_eq!(s.chars().count(), 10);
1408 }
14091410/// This tests that writing into a non-empty buffer is okay.
1411 ///
1412 /// Previously, this would result in a truncation of the buffer that,
1413 /// when provided via a `String`, could result in the `String` containing
1414 /// invalid UTF-8. (And just generally incorrect results even if the string
1415 /// contained valid UTF-8.)
1416 ///
1417 /// Ref: https://github.com/BurntSushi/jiff/issues/592
1418#[cfg(feature = "alloc")]
1419 #[test]
1420fn spare_capacity_non_empty_buffer() {
1421use crate::{civil::date, fmt::temporal::DateTimePrinter};
14221423let mut s = alloc::string::String::from("🎉🎉🎉");
1424let printer = DateTimePrinter::new();
1425let d = date(2024, 6, 15);
1426 printer.print_date(&d, &mut s).unwrap();
1427assert_eq!(s.chars().map(|c| c.len_utf8()).sum::<usize>(), 22);
1428 }
1429}