1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
use thread_rng;
use RngCore;
use SystemTime;
use UNIX_EPOCH;
use ExclusiveId;
use Id;
/// # Universal Forgettable Ordered IDs (UFOIDs)
///
/// UFOIDs are 128-bit identifiers generated by combining a 32-bit
/// timestamp with 96 bits of cryptographic randomness. The timestamp is the
/// lower 32 bits of milliseconds since the UNIX epoch, effectively cycling
/// (modulo 2^32) every approximately 50 days. This provides high locality
/// for items created close in time. The 96 bits of cryptographic randomness
/// ensure global uniqueness, even when multiple IDs are generated simultaneously.
///
/// ## Efficient Garbage Collection
///
/// The 32-bit timestamp allows for efficient identification of older IDs (modulo the rollover).
/// This property is particularly valuable in systems that need to manage large volumes of
/// ephemeral data, such as caches or robotics applications.
/// By leveraging the timestamp's locality, systems can reduce computational overhead
/// and improve memory management when handling high-throughput workloads.
///
/// ## Rollover Handling
///
/// The 32-bit timestamp rolls over approximately every 50 days, meaning that
/// timestamps will reset to zero after reaching their maximum value.
/// To determine the relative distance between two timestamps, you need to provide the
/// current time as a reference point.
/// You can use the function [`timestamp_distance`]
/// to handle the modulo (2^32) space accurately and account for the cyclic nature
/// of these timestamps.
///
/// Rollover scenarios should be anticipated in testing to prevent logical errors,
/// such as treating newer IDs as older ones. This edge case is designed to occur
/// relatively frequently to ensure more resilient system designs.
///
/// ## Usage Example
///
/// ```rust
/// use triblespace_core::id::ufoid::ufoid;
///
/// let id1 = ufoid();
/// let id2 = ufoid();
/// assert_ne!(id1, id2);
/// ```
/// Computes the difference between two UFOID timestamps relative to `now`.
///
/// UFOID timestamps only store the lower 32 bits of the UNIX time in
/// milliseconds. This counter overflows about every 50 days. This helper uses
/// wrapping arithmetic so it still works if `ts1` or `ts2` has overflowed in the
/// integer domain.
///
/// Because the absolute time of that rollover is lost, `ts1` and `ts2` must
/// both be newer than one full rollover period relative to `now` for the result
/// to make sense. In other words, the timestamps should have been created in the
/// last ~50 days; older IDs should have been garbage collected.