rustclamp_core/
reference.rs1use std::cell::RefCell;
4use std::fmt;
5use std::str::FromStr;
6use std::sync::atomic::{AtomicU64, Ordering};
7use std::time::{Duration, SystemTime, UNIX_EPOCH};
8
9#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
27pub struct Reference([u8; 16]);
28
29#[allow(clippy::new_without_default)]
31impl Reference {
32 pub fn new() -> Self {
44 let fresh = (millis(SystemTime::now()) << 16) | 0x7000;
46 let next = |last: u64| if fresh > last { fresh } else { increment(last) };
47 let high = match LAST.try_update(Ordering::Relaxed, Ordering::Relaxed, |last| {
48 Some(next(last))
49 }) {
50 Ok(last) | Err(last) => next(last),
51 };
52 let mut low = RANDOM.with_borrow_mut(Random::take).to_be_bytes();
53 low[0] = (low[0] & 0x3f) | 0x80;
54 let mut bytes = [0; 16];
55 bytes[..8].copy_from_slice(&high.to_be_bytes());
56 bytes[8..].copy_from_slice(&low);
57 Self(bytes)
58 }
59
60 pub fn created_at(&self) -> SystemTime {
62 let mut millis = [0; 8];
63 millis[2..].copy_from_slice(&self.0[..6]);
64 UNIX_EPOCH + Duration::from_millis(u64::from_be_bytes(millis))
65 }
66
67 pub fn range(from: SystemTime, to: SystemTime) -> (Self, Self) {
81 let mut low = [0; 16];
82 low[..6].copy_from_slice(&millis(from).to_be_bytes()[2..]);
83 low[6] = 0x70;
84 low[8] = 0x80;
85 let mut high = [0xff; 16];
86 high[..6].copy_from_slice(&millis(to).to_be_bytes()[2..]);
87 high[6] = 0x7f;
88 high[8] = 0xbf;
89 (Self(low), Self(high))
90 }
91
92 pub fn as_bytes(&self) -> &[u8; 16] {
94 &self.0
95 }
96}
97
98impl fmt::Display for Reference {
99 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
101 const HEX: &[u8; 16] = b"0123456789abcdef";
103 let mut text = [b'-'; 36];
104 let mut at = 0;
105 for (index, byte) in self.0.iter().enumerate() {
106 if matches!(index, 4 | 6 | 8 | 10) {
107 at += 1;
108 }
109 text[at] = HEX[usize::from(byte >> 4)];
110 text[at + 1] = HEX[usize::from(byte & 0x0f)];
111 at += 2;
112 }
113 formatter.write_str(std::str::from_utf8(&text).map_err(|_| fmt::Error)?)
114 }
115}
116
117impl fmt::Debug for Reference {
118 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
119 write!(formatter, "Reference({self})")
120 }
121}
122
123impl FromStr for Reference {
124 type Err = ParseReferenceError;
125
126 fn from_str(text: &str) -> Result<Self, Self::Err> {
129 let text = text.as_bytes();
130 if text.len() != 36 || [8, 13, 18, 23].iter().any(|&dash| text[dash] != b'-') {
131 return Err(ParseReferenceError);
132 }
133 let mut digits = text.iter().filter(|&&byte| byte != b'-');
134 let mut bytes = [0; 16];
135 for byte in &mut bytes {
136 let (Some(high), Some(low)) = (digits.next(), digits.next()) else {
137 return Err(ParseReferenceError);
138 };
139 *byte = (hex(*high)? << 4) | hex(*low)?;
140 }
141 if bytes[6] >> 4 != 7 || bytes[8] >> 6 != 0b10 {
142 return Err(ParseReferenceError);
143 }
144 Ok(Self(bytes))
145 }
146}
147
148#[derive(Clone, Copy, Debug, Eq, PartialEq)]
151#[non_exhaustive]
152pub struct ParseReferenceError;
153
154impl fmt::Display for ParseReferenceError {
155 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
156 formatter.write_str("not a UUIDv7 reference")
157 }
158}
159
160impl std::error::Error for ParseReferenceError {}
161
162fn hex(digit: u8) -> Result<u8, ParseReferenceError> {
163 match digit {
164 b'0'..=b'9' => Ok(digit - b'0'),
165 b'a'..=b'f' => Ok(digit - b'a' + 10),
166 b'A'..=b'F' => Ok(digit - b'A' + 10),
167 _ => Err(ParseReferenceError),
168 }
169}
170
171fn millis(time: SystemTime) -> u64 {
173 time.duration_since(UNIX_EPOCH)
174 .map_or(0, |since| since.as_millis() as u64)
175}
176
177static LAST: AtomicU64 = AtomicU64::new(0);
180
181fn increment(high: u64) -> u64 {
184 if high & 0x0fff < 0x0fff {
185 high + 1
186 } else {
187 (((high >> 16) + 1) << 16) | 0x7000
188 }
189}
190
191struct Random {
193 pool: [u8; 4096],
194 used: usize,
195}
196
197thread_local! {
198 static RANDOM: RefCell<Random> = const { RefCell::new(Random { pool: [0; 4096], used: 4096 }) };
199}
200
201impl Random {
202 fn take(&mut self) -> u64 {
203 if self.used == self.pool.len() {
204 fill(&mut self.pool);
205 self.used = 0;
206 }
207 let mut bytes = [0; 8];
208 bytes.copy_from_slice(&self.pool[self.used..self.used + 8]);
209 self.used += 8;
210 u64::from_be_bytes(bytes)
211 }
212}
213
214#[cfg(not(windows))]
217fn fill(pool: &mut [u8]) {
218 std::fs::File::open("/dev/urandom")
219 .and_then(|mut source| std::io::Read::read_exact(&mut source, pool))
220 .expect("references need the operating system random source /dev/urandom");
221}
222
223#[cfg(windows)]
224fn fill(pool: &mut [u8]) {
225 getrandom::fill(pool).expect("references need the operating system random source");
226}
227
228#[cfg(test)]
229mod tests {
230 use super::*;
231
232 #[test]
233 fn references_carry_the_time_and_stay_ordered() {
234 let before = SystemTime::now();
235 let references: Vec<Reference> = (0..1000).map(|_| Reference::new()).collect();
236 let after = SystemTime::now();
237 assert!(references.windows(2).all(|pair| pair[0] < pair[1]));
238 assert!(
239 references
240 .windows(2)
241 .all(|pair| pair[0].to_string() < pair[1].to_string())
242 );
243 for reference in &references {
244 assert_eq!((reference.0[6] >> 4, reference.0[8] >> 6), (7, 0b10));
245 let made = reference.created_at();
246 assert!(made + Duration::from_millis(1) > before);
249 assert!(made <= after + Duration::from_millis(100));
250 }
251 }
252
253 #[test]
254 fn a_full_counter_carries_into_the_next_millisecond() {
255 let high = (5 << 16) | 0x7ffe;
256 assert_eq!(increment(high), (5 << 16) | 0x7fff);
257 assert_eq!(increment(increment(high)), (6 << 16) | 0x7000);
258 }
259
260 #[test]
261 fn threads_share_one_increasing_sequence() {
262 let threads: Vec<_> = (0..8)
263 .map(|_| std::thread::spawn(|| (0..2000).map(|_| Reference::new()).collect::<Vec<_>>()))
264 .collect();
265 let mut all: Vec<Reference> = threads
266 .into_iter()
267 .flat_map(|t| t.join().unwrap())
268 .collect();
269 let count = all.len();
270 all.sort();
271 all.dedup_by_key(|reference| reference.0[..8].to_vec());
272 assert_eq!(all.len(), count, "no two references share time and counter");
273 }
274
275 #[test]
276 fn range_brackets_its_window_only() {
277 let at = |millis| UNIX_EPOCH + Duration::from_millis(millis);
278 let (low, high) = Reference::range(at(1_000), at(2_000));
279 let inside = [at(1_000), at(1_500), at(2_000)];
280 for time in inside {
281 let (first, last) = Reference::range(time, time);
282 assert!(low <= first && last <= high, "{time:?}");
283 }
284 assert!(Reference::range(at(999), at(999)).1 < low);
285 assert!(Reference::range(at(2_001), at(2_001)).0 > high);
286 assert_eq!(low.created_at(), at(1_000));
287 assert_eq!(high.created_at(), at(2_000));
288 assert!(low.to_string().parse::<Reference>().is_ok());
289 assert!(high.to_string().parse::<Reference>().is_ok());
290 }
291
292 #[test]
293 fn parse_round_trips_and_refuses_everything_else() {
294 let text = "0192f1c2-3b4a-7c5d-8e6f-a1b2c3d4e5f6";
295 let reference: Reference = text.parse().unwrap();
296 assert_eq!(reference.to_string(), text);
297 assert_eq!(text.to_uppercase().parse(), Ok(reference));
298 assert_eq!(format!("{reference:?}"), format!("Reference({text})"));
299 for junk in [
300 "",
301 "0192f1c2-3b4a-7c5d-8e6f-a1b2c3d4e5f",
302 "0192f1c2x3b4a-7c5d-8e6f-a1b2c3d4e5f6",
303 "zz92f1c2-3b4a-7c5d-8e6f-a1b2c3d4e5f6",
304 "0192f1c2-3b4a-4c5d-8e6f-a1b2c3d4e5f6", "0192f1c2-3b4a-7c5d-ce6f-a1b2c3d4e5f6", "0192f1c2-3b4a-7c5d-8e6f-a1b2c3d4e5fé",
307 ] {
308 assert_eq!(
309 junk.parse::<Reference>(),
310 Err(ParseReferenceError),
311 "{junk}"
312 );
313 }
314 }
315}