time/ext/
digit_count.rs

1use 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.
7pub(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.
13macro_rules! impl_digit_count {
14    ($($t:ty),* $(,)?) => {
15        $(impl DigitCount for $t {
16            fn num_digits(self) -> u8 {
17                match self.checked_ilog10() {
18                    Some(n) => n.truncate::<u8>() + 1,
19                    None => 1,
20                }
21            }
22        })*
23    };
24}
25
26impl_digit_count!(u8, u16, u32);