use std::sync::OnceLock;
use num_bigint::BigUint;
use crate::codec::{Baseh, DecodeOptions};
use crate::error::BasehError;
use crate::profiles::baseh_medium_v1;
static ZERO: OnceLock<Baseh> = OnceLock::new();
fn zero() -> &'static Baseh {
ZERO.get_or_init(|| {
Baseh::new(baseh_medium_v1()).expect("the frozen baseh-medium-v1 profile is valid")
})
}
pub trait ToCodeId {
fn into_biguint(self) -> BigUint;
}
macro_rules! impl_to_code_id_for_uint {
($($t:ty),*) => {
$(impl ToCodeId for $t {
fn into_biguint(self) -> BigUint {
BigUint::from(self)
}
})*
};
}
impl_to_code_id_for_uint!(u8, u16, u32, u64, u128, usize);
impl ToCodeId for BigUint {
fn into_biguint(self) -> BigUint {
self
}
}
impl ToCodeId for &BigUint {
fn into_biguint(self) -> BigUint {
self.clone()
}
}
fn decimal_to_biguint(s: &str) -> BigUint {
if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {
panic!("to_code expects a non-negative integer or a decimal string of digits");
}
BigUint::parse_bytes(s.as_bytes(), 10).expect("validated decimal digits")
}
impl ToCodeId for &str {
fn into_biguint(self) -> BigUint {
decimal_to_biguint(self)
}
}
impl ToCodeId for String {
fn into_biguint(self) -> BigUint {
decimal_to_biguint(&self)
}
}
impl ToCodeId for &String {
fn into_biguint(self) -> BigUint {
decimal_to_biguint(self)
}
}
pub fn to_code(id: impl ToCodeId) -> Result<String, BasehError> {
zero().encode(&id.into_biguint())
}
pub fn from_code(code: &str) -> Result<BigUint, BasehError> {
let stripped: String = code.chars().filter(|c| !c.is_whitespace()).collect();
Ok(zero().decode(&stripped, &DecodeOptions::default())?.id)
}