use serde::{Serialize, Deserialize};
use crate::epoch_timestamp;
use num_bigint::BigInt;
use rand::Rng;
static SEED_LEN: usize = 12;
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct AlmostSnowflake(String);
pub fn bigint(input: usize) -> BigInt {
BigInt::from(input)
}
impl AlmostSnowflake {
pub fn new(server_id: usize) -> Self {
let mut bytes = String::new();
let mut rng = rand::thread_rng();
for _ in 1..=SEED_LEN {
bytes.push_str(&rng.gen_range(0..10).to_string())
}
let mut id = bigint(epoch_timestamp(2024) as usize) << 22 as u128;
id = id | bigint((server_id % 1024) << 12);
id = id | bigint((bytes.parse::<usize>().unwrap() + 1) % 4096);
Self(id.to_string())
}
}
impl std::fmt::Display for AlmostSnowflake {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}