Skip to main content

core/num/imp/
fmt.rs

1//! Shared utilities used by both float and integer formatting.
2#![doc(hidden)]
3#![unstable(
4    feature = "numfmt",
5    reason = "internal routines only exposed for testing",
6    issue = "none"
7)]
8
9/// Formatted parts.
10#[derive(Copy, Clone, PartialEq, Eq, Debug)]
11#[ferrocene::prevalidated]
12pub enum Part<'a> {
13    /// Given number of zero digits.
14    Zero(usize),
15    /// A literal number up to 5 digits.
16    Num(u16),
17    /// A verbatim copy of given bytes.
18    Copy(&'a [u8]),
19}
20
21impl<'a> Part<'a> {
22    /// Returns the exact byte length of given part.
23    #[ferrocene::prevalidated]
24    pub fn len(&self) -> usize {
25        match *self {
26            Part::Zero(nzeroes) => nzeroes,
27            Part::Num(v) => v.checked_ilog10().unwrap_or_default() as usize + 1,
28            Part::Copy(buf) => buf.len(),
29        }
30    }
31
32    /// Writes a part into the supplied buffer.
33    /// Returns the number of written bytes, or `None` if the buffer is not enough.
34    /// (It may still leave partially written bytes in the buffer; do not rely on that.)
35    pub fn write(&self, out: &mut [u8]) -> Option<usize> {
36        let len = self.len();
37        if out.len() >= len {
38            match *self {
39                Part::Zero(nzeroes) => {
40                    for c in &mut out[..nzeroes] {
41                        *c = b'0';
42                    }
43                }
44                Part::Num(mut v) => {
45                    for c in out[..len].iter_mut().rev() {
46                        *c = b'0' + (v % 10) as u8;
47                        v /= 10;
48                    }
49                }
50                Part::Copy(buf) => {
51                    out[..buf.len()].copy_from_slice(buf);
52                }
53            }
54            Some(len)
55        } else {
56            None
57        }
58    }
59}
60
61/// Formatted result containing one or more parts.
62/// This can be written to the byte buffer or converted to the allocated string.
63#[allow(missing_debug_implementations)]
64#[derive(Clone)]
65#[ferrocene::prevalidated]
66pub struct Formatted<'a> {
67    /// A byte slice representing a sign, either `""`, `"-"` or `"+"`.
68    pub sign: &'static str,
69    /// Formatted parts to be rendered after a sign and optional zero padding.
70    pub parts: &'a [Part<'a>],
71}
72
73impl<'a> Formatted<'a> {
74    /// Returns the byte length of combined formatted result.
75    ///
76    /// Saturates at `usize::MAX` if the actual length is larger.
77    ///
78    /// This matters on 16-bit targets, where exponential formatting can exceed
79    /// `usize::MAX` by emitting `u16::MAX` trailing zeroes plus `"1."` / `"e0"`.
80    #[ferrocene::prevalidated]
81    pub fn len(&self) -> usize {
82        self.parts.iter().fold(self.sign.len(), |len, part| len.saturating_add(part.len()))
83    }
84
85    /// Writes all formatted parts into the supplied buffer.
86    /// Returns the number of written bytes, or `None` if the buffer is not enough.
87    /// (It may still leave partially written bytes in the buffer; do not rely on that.)
88    pub fn write(&self, out: &mut [u8]) -> Option<usize> {
89        out.get_mut(..self.sign.len())?.copy_from_slice(self.sign.as_bytes());
90
91        let mut written = self.sign.len();
92        for part in self.parts {
93            let len = part.write(&mut out[written..])?;
94            written += len;
95        }
96        Some(written)
97    }
98}