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)
};
}
pub use custom_formatter;
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, clippy::out_of_bounds_indexing)]
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)
}