| 1 |
use num_conv::prelude::*; |
| 2 |
|
| 3 |
/// A trait that indicates the formatted width of the value can be determined. |
| 4 |
/// |
| 5 |
/// Note that this should not be implemented for any signed integers. This forces the caller to |
| 6 |
/// write the sign if desired. |
| 7 |
pub(crate) trait DigitCount { |
| 8 |
/// The number of digits in the stringified value. |
| 9 |
fn num_digits(self) -> u8; |
| 10 |
} |
| 11 |
|
| 12 |
/// A macro to generate implementations of `DigitCount` for unsigned integers. |
| 13 |
macro_rules! impl_digit_count { |
| 14 |
($($t:ty),* $(,)?) => { |
| 15 |
$(impl DigitCount for $t { |
| 16 |
#[inline] |
| 17 |
fn num_digits(self) -> u8 { |
| 18 |
match self.checked_ilog10() { |
| 19 |
Some(n) => n.truncate::<u8>() + 1, |
| 20 |
None => 1, |
| 21 |
} |
| 22 |
} |
| 23 |
})* |
| 24 |
}; |
| 25 |
} |
| 26 |
|
| 27 |
impl_digit_count!(u8, u16, u32); |