1 //! Shared utilities used by both float and integer formatting.
5 reason = "internal routines only exposed for testing",
10 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
12 /// Given number of zero digits.
14 /// A literal number up to 5 digits.
16 /// A verbatim copy of given bytes.
21 /// Returns the exact byte length of given part.
22 pub fn len(&self) -> usize {
24 Part::Zero(nzeroes) => nzeroes,
35 if v < 10_000 { 4 } else { 5 }
38 Part::Copy(buf) => buf.len(),
42 /// Writes a part into the supplied buffer.
43 /// Returns the number of written bytes, or `None` if the buffer is not enough.
44 /// (It may still leave partially written bytes in the buffer; do not rely on that.)
45 pub fn write(&self, out: &mut [u8]) -> Option<usize> {
49 Part::Zero(nzeroes) => {
50 for c in &mut out[..nzeroes] {
55 for c in out[..len].iter_mut().rev() {
56 *c = b'0' + (v % 10) as u8;
61 out[..buf.len()].copy_from_slice(buf);
71 /// Formatted result containing one or more parts.
72 /// This can be written to the byte buffer or converted to the allocated string.
73 #[allow(missing_debug_implementations)]
75 pub struct Formatted<'a> {
76 /// A byte slice representing a sign, either `""`, `"-"` or `"+"`.
77 pub sign: &'static str,
78 /// Formatted parts to be rendered after a sign and optional zero padding.
79 pub parts: &'a [Part<'a>],
82 impl<'a> Formatted<'a> {
83 /// Returns the exact byte length of combined formatted result.
84 pub fn len(&self) -> usize {
85 let mut len = self.sign.len();
86 for part in self.parts {
92 /// Writes all formatted parts into the supplied buffer.
93 /// Returns the number of written bytes, or `None` if the buffer is not enough.
94 /// (It may still leave partially written bytes in the buffer; do not rely on that.)
95 pub fn write(&self, out: &mut [u8]) -> Option<usize> {
96 if out.len() < self.sign.len() {
99 out[..self.sign.len()].copy_from_slice(self.sign.as_bytes());
101 let mut written = self.sign.len();
102 for part in self.parts {
103 let len = part.write(&mut out[written..])?;