diff options
| author | bors <bors@rust-lang.org> | 2025-07-08 10:54:22 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2025-07-08 10:54:22 +0000 |
| commit | 040e2f8b9ff2d76fbe2146d6003e297ed4532088 (patch) | |
| tree | c7f6558b1f5d1b064d080239b695e6ea5cd25e05 | |
| parent | 45b80ac21a454d343833aad763ef604510c88375 (diff) | |
| parent | 09cf02c8af6657ffdf0faba8afd2efa652d299c6 (diff) | |
| download | rust-040e2f8b9ff2d76fbe2146d6003e297ed4532088.tar.gz rust-040e2f8b9ff2d76fbe2146d6003e297ed4532088.zip | |
Auto merge of #143540 - yotamofek:pr/library/simplify-num-fmt, r=tgross35
Simplify num formatting helpers Noticed `ilog10` was being open-coded when looking at this diff: https://github.com/rust-lang/rust/pull/143423/files/85d6768f4c437a0f3799234df20535ff65ee17c2..76d9775912ef3a7ee145053a5119538bf229d6e5#diff-6be9b44b52d946ccac652ddb7c98146a01b22ea0fc5737bc10db245a24796a45 That, and two other small cleanups 😁 (should probably go through perf just to make sure it doesn't regress formatting)
| -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 { |
