rust_assembler/stack_str/usize_to_str.rs
1/// 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.
2///
3/// # Examples
4///
5/// ```
6///
7/// assert_eq!("291", usize_to_str!(291; 3).str());
8/// assert_eq!("0291", usize_to_str!(291; 4).str());
9///
10/// ```
11///
12/// This function by default accepts values up to `u64`. If values up to `u128` are needed, as a third parameter specify bit_128.
13/// # Examples
14///
15/// ```
16///
17/// assert_eq!("000123714384710312239874874388", usize_to_str!(123714384710312239874874388; 30, bit_128).str());
18///
19/// ```
20#[macro_export]
21macro_rules! usize_to_str {
22 ( $n:expr; 1 ) => ({
23 let bytes = [$n | 48];
24
25 unsafe {
26 StackStr {
27 bytes,
28 str_: core::str::from_utf8_unchecked(&bytes)
29 }
30 }
31 });
32 ( $n:expr; 2 ) => ({
33 let tens_str_digit = ($n / 10) | 48;
34 let units_str_digit = ($n % 10) | 48;
35 let bytes = [tens_str_digit, units_str_digit];
36
37 unsafe {
38 StackStr {
39 bytes,
40 str_: core::str::from_utf8_unchecked(&bytes)
41 }
42 }
43 });
44 ( $n:expr; $len:expr ) => ({
45 let mut bytes = [0u8; $len];
46 let mut n = $n as u64;
47 let mut len = $len;
48
49 for byte in bytes.iter_mut() {
50 let divisor = 10_u64.pow(len - 1);
51
52 let str_digit = (n / divisor) | 48;
53 *byte = str_digit as u8;
54
55 n %= divisor;
56 len -= 1;
57
58 }
59
60 unsafe {
61 StackStr {
62 bytes,
63 str_: core::str::from_utf8_unchecked(&bytes)
64 }
65 }
66 });
67 ( $n:expr; $len:expr, bit_128 ) => ({
68 let mut bytes = [0u8; $len];
69 let mut n = $n;
70 let mut len = $len;
71
72 for byte in bytes.iter_mut() {
73 let divisor = 10_u128.pow(len - 1);
74
75 let str_digit = (n / divisor) | 48;
76 *byte = str_digit as u8;
77
78 n %= divisor;
79 len -= 1;
80
81 }
82
83 unsafe {
84 StackStr {
85 bytes,
86 str_: core::str::from_utf8_unchecked(&bytes)
87 }
88 }
89 })
90}