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