1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
/// Formats a positive number into a `StackStr<N>`. The parameters required are the number that must be converted and the length of `N`, namely the number of digits of the given number, separated by a semicolon. In case the number has less digits than the specified length, it will have trailing zeros, represented as their utf-8 value: `48`. In case the length is less than required, it will result in undefined behavior.
/// 
/// # Examples
/// 
/// ```
/// 
/// assert_eq!("291", usize_to_str!(291; 3).str());
/// assert_eq!("0291", usize_to_str!(291; 4).str());
/// 
/// ```
/// 
///  This function by default accepts values up to `u64`. If values up to `u128` are needed, as a third parameter specify bit_128.
/// # Examples
/// 
/// ```
/// 
/// assert_eq!("000123714384710312239874874388", usize_to_str!(123714384710312239874874388; 30, bit_128).str());
/// 
/// ```
#[macro_export]
macro_rules! usize_to_str {
    ( $n:expr; 1 ) => ({
        let bytes = [$n | 48];
        unsafe {
            StackStr {
                bytes,
                str_: core::str::from_utf8_unchecked(&bytes)
            }
        }
    });
    ( $n:expr; 2 ) => ({
        let tens_str_digit = ($n / 10) | 48;
        let units_str_digit = ($n % 10) | 48;
        let bytes = [tens_str_digit, units_str_digit];
        unsafe {
            StackStr {
                bytes,
                str_: core::str::from_utf8_unchecked(&bytes)
            }
        }
    });
    ( $n:expr; $len:expr ) => ({
        let mut bytes = [0u8; $len];
        let mut n = $n as u64;
        let mut len = $len;
        for byte in bytes.iter_mut() {
            let divisor = 10_u64.pow(len - 1);
            let str_digit = (n / divisor) | 48;
            *byte = str_digit as u8;
            n %= divisor;
            len -= 1;
        }
        unsafe {
            StackStr {
                bytes,
                str_: core::str::from_utf8_unchecked(&bytes)
            }
        }
    });
    ( $n:expr; $len:expr, bit_128 ) => ({
        let mut bytes = [0u8; $len];
        let mut n = $n;
        let mut len = $len;
        for byte in bytes.iter_mut() {
            let divisor = 10_u128.pow(len - 1);
            let str_digit = (n / divisor) | 48;
            *byte = str_digit as u8;
            n %= divisor;
            len -= 1;
        }
        unsafe {
            StackStr {
                bytes,
                str_: core::str::from_utf8_unchecked(&bytes)
            }
        }
    })
}