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 = timestamp.as_millis();
if !(0..Ulid::MILLIS_END).contains(&millis) {
return Err(UlidGenerationError::InvalidTimestamp);
}
let id = if let Some(previous) = self.last.filter(|id| timestamp <= id.timestamp()) {
let next = ::ulid::Ulid::from_bytes(previous.to_bytes())
.increment()
.map_err(|_| UlidGenerationError::Exhausted)?;
Ulid::from_bytes(next.to_bytes())
} else {
Ulid::from_millis_and_suffix(millis as u64, randomness)
};
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 {}