use ulid::Ulid;
pub trait UlidRng: Send + Sync {
fn next_ulid(&mut self) -> Ulid;
}
#[derive(Debug, Default)]
pub struct SystemUlidRng;
impl UlidRng for SystemUlidRng {
fn next_ulid(&mut self) -> Ulid {
Ulid::new()
}
}
#[derive(Debug, Default)]
pub struct CountingUlidRng {
counter: u128,
}
impl CountingUlidRng {
pub fn new() -> Self {
Self { counter: 0 }
}
}
impl UlidRng for CountingUlidRng {
fn next_ulid(&mut self) -> Ulid {
self.counter += 1;
Ulid::from_parts(0, self.counter)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn system_ulid_rng_produces_unique_values() {
let mut rng = SystemUlidRng;
let a = rng.next_ulid();
let b = rng.next_ulid();
assert_ne!(a, b);
}
#[test]
fn counting_ulid_rng_starts_at_one() {
let mut rng = CountingUlidRng::new();
let first = rng.next_ulid();
assert_eq!(first, Ulid::from_parts(0, 1));
}
#[test]
fn counting_ulid_rng_is_monotonic() {
let mut rng = CountingUlidRng::new();
let a = rng.next_ulid();
let b = rng.next_ulid();
let c = rng.next_ulid();
assert!(a < b);
assert!(b < c);
}
}