1use super::{Ulid, UlidEntropyError, UlidGenerationError, UlidGenerator, platform};
3use crate::Timestamp;
4use sha2::{Digest, Sha256};
5use std::cell::{Cell, RefCell};
6
7thread_local! {
8 static DEFAULT_STREAM: RefCell<Option<SeededUlidGenerator>> = const { RefCell::new(None) };
9 static LAST_STREAM: Cell<u64> = const { Cell::new(0) };
10}
11
12pub struct SeededUlidGenerator {
15 issuer: UlidGenerator,
16 seed: [u8; 10],
17}
18
19impl SeededUlidGenerator {
20 fn new(mut seed: [u8; 10]) -> Self {
21 seed[0] &= 0x7f;
22 Self {
23 issuer: UlidGenerator::new(),
24 seed,
25 }
26 }
27
28 pub fn next_at(&mut self, timestamp: Timestamp) -> Result<Ulid, UlidGenerationError> {
35 self.issuer.generate(timestamp, self.seed)
36 }
37
38 fn at(&mut self, time_ns: u64) -> Ulid {
39 self.next_at(Timestamp::from_millis((time_ns / 1_000_000) as i64))
40 .expect("ULID suffix exhausted at the current logical timestamp")
41 }
42
43 pub fn next_id(&mut self) -> Ulid {
48 self.at(platform::time())
49 }
50}
51
52fn stream((owner, version): (impl AsRef<[u8]>, u64), number: Option<u64>) -> SeededUlidGenerator {
53 let domain: &[u8] = if number.is_some() {
54 b"ic-db:ulid-owned:v1"
55 } else {
56 b"ic-db:ulid-stream:v1"
57 };
58 let mut hash = Sha256::new()
59 .chain_update(domain)
60 .chain_update(owner.as_ref())
61 .chain_update(version.to_be_bytes());
62 if let Some(number) = number {
63 hash.update(number.to_be_bytes());
65 }
66 let digest = hash.finalize();
67 SeededUlidGenerator::new(std::array::from_fn(|i| digest[i]))
68}
69
70pub(super) fn generate<T: AsRef<[u8]>>(time_ns: u64, identity: impl FnOnce() -> (T, u64)) -> Ulid {
71 DEFAULT_STREAM.with_borrow_mut(|slot| {
72 slot.get_or_insert_with(|| stream(identity(), None))
73 .at(time_ns)
74 })
75}
76
77pub(super) fn owned(identity: (impl AsRef<[u8]>, u64)) -> SeededUlidGenerator {
78 let number = LAST_STREAM.with(|slot| {
79 let next = slot
80 .get()
81 .checked_add(1)
82 .expect("ULID stream numbers exhausted");
83 slot.set(next);
84 next
85 });
86 stream(identity, Some(number))
87}
88
89impl Ulid {
90 #[must_use]
94 pub fn generate_prand() -> Self {
95 generate(platform::time(), platform::identity)
96 }
97
98 pub async fn generator() -> Result<SeededUlidGenerator, UlidEntropyError> {
102 Ok(SeededUlidGenerator::new(platform::fresh_suffix().await?))
103 }
104
105 #[must_use]
109 pub fn generator_prand() -> SeededUlidGenerator {
110 owned(platform::identity())
111 }
112}