diff options
| author | Yotam Ofek <yotam.ofek@gmail.com> | 2025-07-06 20:22:21 +0000 |
|---|---|---|
| committer | Yotam Ofek <yotam.ofek@gmail.com> | 2025-07-06 20:26:04 +0000 |
| commit | 09cf02c8af6657ffdf0faba8afd2efa652d299c6 (patch) | |
| tree | c30c3772989d301f957025833f756b308e8242d6 | |
| parent | de031bbcb161b0b7fc0eb16f77b02ce9fbdf4c9e (diff) | |
| download | rust-09cf02c8af6657ffdf0faba8afd2efa652d299c6.tar.gz rust-09cf02c8af6657ffdf0faba8afd2efa652d299c6.zip | |
Simplify num formatting helpers
| -rw-r--r-- | library/core/src/num/fmt.rs | 25 |
1 files changed, 3 insertions, 22 deletions
diff --git a/library/core/src/num/fmt.rs b/library/core/src/num/fmt.rs index ed61197157b..0e4b2844d81 100644 --- a/library/core/src/num/fmt.rs +++ b/library/core/src/num/fmt.rs @@ -22,19 +22,7 @@ impl<'a> Part<'a> { pub fn len(&self) -> usize { match *self { Part::Zero(nzeroes) => nzeroes, - Part::Num(v) => { - if v < 1_000 { - if v < 10 { - 1 - } else if v < 100 { - 2 - } else { - 3 - } - } else { - if v < 10_000 { 4 } else { 5 } - } - } + Part::Num(v) => v.checked_ilog10().unwrap_or_default() as usize + 1, Part::Copy(buf) => buf.len(), } } @@ -82,21 +70,14 @@ pub struct Formatted<'a> { impl<'a> Formatted<'a> { /// Returns the exact byte length of combined formatted result. pub fn len(&self) -> usize { - let mut len = self.sign.len(); - for part in self.parts { - len += part.len(); - } - len + self.sign.len() + self.parts.iter().map(|part| part.len()).sum::<usize>() } /// Writes all formatted parts into the supplied buffer. /// Returns the number of written bytes, or `None` if the buffer is not enough. /// (It may still leave partially written bytes in the buffer; do not rely on that.) pub fn write(&self, out: &mut [u8]) -> Option<usize> { - if out.len() < self.sign.len() { - return None; - } - out[..self.sign.len()].copy_from_slice(self.sign.as_bytes()); + out.get_mut(..self.sign.len())?.copy_from_slice(self.sign.as_bytes()); let mut written = self.sign.len(); for part in self.parts { |
