tetratto/crates/shared/src/snow.rs

37 lines
874 B
Rust
Raw Normal View History

2025-05-06 16:13:48 -04:00
use std::time::{UNIX_EPOCH, Duration};
use serde::{Deserialize, Serialize};
2025-05-06 16:13:48 -04:00
use snowflaked::{Builder, Generator};
2025-05-06 16:13:48 -04:00
pub const EPOCH_2024: u64 = 1704067200000;
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
2025-05-06 16:13:48 -04:00
pub struct Snowflake(String);
2025-05-09 22:36:16 -04:00
impl Default for Snowflake {
fn default() -> Self {
Self::new()
}
}
2025-05-06 16:13:48 -04:00
impl Snowflake {
pub fn builder() -> Builder {
Builder::new().epoch(UNIX_EPOCH + Duration::from_millis(EPOCH_2024))
}
/// Create a new [`AlmostSnowflake`]
2025-05-06 16:13:48 -04:00
pub fn new() -> Self {
Self(
Self::builder()
.build::<Generator>()
.generate::<u64>()
.to_string(),
)
}
}
2025-05-06 16:13:48 -04:00
impl std::fmt::Display for Snowflake {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}