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 pub fn next_id(&mut self) -> Ulid {
45 self.next_at(Timestamp::now())
46 .expect("ULID suffix exhausted at the current logical timestamp")
47 }
48}
49
50fn stream((owner, version): (impl AsRef<[u8]>, u64), number: Option<u64>) -> SeededUlidGenerator {
51 let domain: &[u8] = if number.is_some() {
52 b"ic-db:ulid-owned:v1"
53 } else {
54 b"ic-db:ulid-stream:v1"
55 };
56 let mut hash = Sha256::new()
57 .chain_update(domain)
58 .chain_update(owner.as_ref())
59 .chain_update(version.to_be_bytes());
60 if let Some(number) = number {
61 hash.update(number.to_be_bytes());
63 }
64 let digest = hash.finalize();
65
66 SeededUlidGenerator::new(std::array::from_fn(|i| digest[i]))
67}
68
69pub(super) fn generate<T: AsRef<[u8]>>(
70 time: Timestamp,
71 identity: impl FnOnce() -> (T, u64),
72) -> Result<Ulid, UlidGenerationError> {
73 DEFAULT_STREAM.with_borrow_mut(|slot| {
74 slot.get_or_insert_with(|| stream(identity(), None))
75 .next_at(time)
76 })
77}
78
79#[doc(hidden)]
81pub fn insert_ulid(time: Option<Timestamp>) -> Result<Ulid, crate::Error> {
82 generate(time.unwrap_or_else(Timestamp::now), platform::identity).map_err(|error| match error {
83 UlidGenerationError::InvalidTimestamp => crate::Error::InvalidOperand,
84 UlidGenerationError::Exhausted => crate::Error::Limit,
85 })
86}
87
88pub(super) fn owned(identity: (impl AsRef<[u8]>, u64)) -> SeededUlidGenerator {
89 let number = LAST_STREAM.with(|slot| {
90 let next = slot
91 .get()
92 .checked_add(1)
93 .expect("ULID stream numbers exhausted");
94 slot.set(next);
95
96 next
97 });
98
99 stream(identity, Some(number))
100}
101
102impl Ulid {
103 #[must_use]
107 pub fn generate_prand() -> Self {
108 generate(Timestamp::now(), platform::identity)
109 .expect("ULID suffix exhausted at the current logical timestamp")
110 }
111
112 pub async fn generator() -> Result<SeededUlidGenerator, UlidEntropyError> {
116 Ok(SeededUlidGenerator::new(platform::fresh_suffix().await?))
117 }
118
119 #[must_use]
123 pub fn generator_prand() -> SeededUlidGenerator {
124 owned(platform::identity())
125 }
126}