Assessment reports>Pinocchio and p-token>Discussion>Statically compute max_digits in log macro

Statically compute max_digits in log macro

The impl_log_for_unsigned_integer macro in the log crate is defined as follows:

macro_rules! impl_log_for_unsigned_integer {
    ( $type:tt, $max_digits:literal ) => { 
        impl Log for $type {
            ...
        }
        ...
    },
    ...
}

Here, $max_digits is supposed to reflect the number of digits (in base 10) it takes to record the largest representable figure of type $type. We can see uses of this macro within the crate like this:

impl_log_for_unsigned_integer!(u8, 3);
impl_log_for_unsigned_integer!(u16, 5);
impl_log_for_unsigned_integer!(u32, 10);
impl_log_for_unsigned_integer!(u64, 20);
impl_log_for_unsigned_integer!(u128, 39);
// Handle the `usize` type.
#[cfg(target_pointer_width = "32")]
impl_log_for_unsigned_integer!(usize, 10);
#[cfg(target_pointer_width = "64")]
impl_log_for_unsigned_integer!(usize, 20);

We propose, instead, statically calculating these figures at compile time. It would have no impact on performance, but it would better maintain the correct figures and eliminate the need for the cfg attribute. This can be done with the following computation:

const MAX_DIGITS: usize = const { $type::MAX.ilog10() as usize + 1 };

Zellic © 2025Back to top ↑