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