Skip to content

Commit 09cf02c

Browse files
committed
Simplify num formatting helpers
1 parent de031bb commit 09cf02c

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)