use super::Ulid;
use crate::Timestamp;
use std::fmt;
#[derive(Debug, Default)]
pub struct UlidGenerator {
last: Option<Ulid>,
}
impl UlidGenerator {
#[must_use]
pub const fn new() -> Self {
Self { last: None }
}
#[must_use]
pub const fn resume_after(last: Ulid) -> Self {
Self { last: Some(last) }
}
#[must_use]
pub const fn last(&self) -> Option<Ulid> {
self.last
}
pub fn generate(
&mut self,
timestamp: Timestamp,
randomness: [u8; 10],
) -> Result<Ulid, UlidGenerationError> {
let millis = u64::try_from(timestamp.as_millis())
.ok()
.filter(|value| *value < (1_u64 << 48))
.ok_or(UlidGenerationError::InvalidTimestamp)?;
let previous = self.last.map(|id| ::ulid::Ulid::from_bytes(id.to_bytes()));
let next = if let Some(previous) = previous.filter(|id| millis <= id.timestamp_ms()) {
previous
.increment()
.map_err(|_| UlidGenerationError::Exhausted)?
} else {
let mut component = [0; 16];
component[6..].copy_from_slice(&randomness);
::ulid::Ulid::from_parts(millis, u128::from_be_bytes(component))
};
let id = Ulid::from_bytes(next.to_bytes());
self.last = Some(id);
Ok(id)
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum UlidGenerationError {
InvalidTimestamp,
Exhausted,
}
impl fmt::Display for UlidGenerationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::InvalidTimestamp => "ULID timestamp must fit unsigned 48-bit milliseconds",
Self::Exhausted => "ULID suffix exhausted at the current logical timestamp",
})
}
}
impl std::error::Error for UlidGenerationError {}