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
use core::fmt;
pub trait CustomFormat<const SPEC: u128> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result;
}
#[derive(Debug, Clone)]
pub struct CustomFormatter<'a, T, const SPEC: u128> {
value: &'a T,
}
impl<'a, T, const SPEC: u128> CustomFormatter<'a, T, SPEC> {
pub fn new(value: &'a T) -> Self {
Self { value }
}
}
#[macro_export]
macro_rules! custom_formatter {
($spec:literal, $value:expr) => {{
$crate::compile_time::CustomFormatter::<_, { $crate::compile_time::spec($spec) }>::new($value)
}};
}
impl<T: CustomFormat<SPEC>, const SPEC: u128> fmt::Display for CustomFormatter<'_, T, SPEC> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
CustomFormat::fmt(self.value, f)
}
}
pub const fn spec(s: &str) -> u128 {
let bytes = s.as_bytes();
let len = s.len();
if len > 16 {
#[allow(unconditional_panic)]
let _ = ["format specifier is limited to 16 bytes"][usize::MAX];
}
let mut result = [0u8; 16];
let mut i = 0;
while i < len {
result[i] = bytes[i];
i += 1;
}
u128::from_le_bytes(result)
}
pub use custom_format_macros::compile_time_eprint as eprint;
pub use custom_format_macros::compile_time_eprintln as eprintln;
pub use custom_format_macros::compile_time_format as format;
pub use custom_format_macros::compile_time_format_args as format_args;
pub use custom_format_macros::compile_time_panic as panic;
pub use custom_format_macros::compile_time_print as print;
pub use custom_format_macros::compile_time_println as println;
pub use custom_format_macros::compile_time_write as write;
pub use custom_format_macros::compile_time_writeln as writeln;