Skip to main content

ps_uuid/state/methods/
next_v7.rs

1use std::time::{Duration, SystemTime};
2
3use crate::State;
4
5const FIDELITY: Duration = Duration::from_nanos(256);
6
7impl State {
8    /// This method returns the next `UUIDv7`'s timestamp.
9    ///
10    /// 1. Increments this [`State`]'s timestamp by 256 ns,
11    /// 2. compares this with the timestamp provided, keeping the greater of the two,
12    /// 3. replaces this [`State`]'s timestamp with the value,
13    /// 4. returns the value.
14    ///
15    /// # Usage
16    ///
17    /// ```
18    /// use ps_uuid::STATE;
19    /// use std::time::SystemTime;
20    ///
21    /// let next_ts = STATE.lock().next_v7(SystemTime::now());
22    /// ```
23    pub fn next_v7(&mut self, timestamp: SystemTime) -> SystemTime {
24        let timestamp = timestamp.max(self.last_ts + FIDELITY);
25
26        self.last_ts = timestamp;
27
28        timestamp
29    }
30}
31
32#[cfg(test)]
33mod tests {
34    use std::time::SystemTime;
35
36    use crate::STATE;
37
38    #[test]
39    fn always_increments() {
40        let mut guard = STATE.lock_arc();
41
42        let mut previous = guard.next_v7(SystemTime::now());
43
44        for _ in 0..99999 {
45            let next = guard.next_v7(SystemTime::now());
46
47            assert!(next > previous, "Next timestamp must be greater.");
48
49            previous = next;
50        }
51
52        drop(guard);
53    }
54}