Skip to content

Commit 040e2f8

Browse files
committed
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)
2 parents 45b80ac + 09cf02c commit 040e2f8

File tree

1 file changed

+3
-22
lines changed

1 file changed

+3
-22
lines changed

library/core/src/num/fmt.rs

Lines changed: 3 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -22,19 +22,7 @@ impl<'a> Part<'a> {
2222
pub fn len(&self) -> usize {
2323
match *self {
2424
Part::Zero(nzeroes) => nzeroes,
25-
Part::Num(v) => {
26-
if v < 1_000 {
27-
if v < 10 {
28-
1
29-
} else if v < 100 {
30-
2
31-
} else {
32-
3
33-
}
34-
} else {
35-
if v < 10_000 { 4 } else { 5 }
36-
}
37-
}
25+
Part::Num(v) => v.checked_ilog10().unwrap_or_default() as usize + 1,
3826
Part::Copy(buf) => buf.len(),
3927
}
4028
}
@@ -82,21 +70,14 @@ pub struct Formatted<'a> {
8270
impl<'a> Formatted<'a> {
8371
/// Returns the exact byte length of combined formatted result.
8472
pub fn len(&self) -> usize {
85-
let mut len = self.sign.len();
86-
for part in self.parts {
87-
len += part.len();
88-
}
89-
len
73+
self.sign.len() + self.parts.iter().map(|part| part.len()).sum::<usize>()
9074
}
9175

9276
/// Writes all formatted parts into the supplied buffer.
9377
/// Returns the number of written bytes, or `None` if the buffer is not enough.
9478
/// (It may still leave partially written bytes in the buffer; do not rely on that.)
9579
pub fn write(&self, out: &mut [u8]) -> Option<usize> {
96-
if out.len() < self.sign.len() {
97-
return None;
98-
}
99-
out[..self.sign.len()].copy_from_slice(self.sign.as_bytes());
80+
out.get_mut(..self.sign.len())?.copy_from_slice(self.sign.as_bytes());
10081

10182
let mut written = self.sign.len();
10283
for part in self.parts {

0 commit comments

Comments
 (0)