commonware_sync/net/
request_id.rs

1use std::sync::{
2    atomic::{AtomicU64, Ordering},
3    Arc,
4};
5
6/// Unique identifier for correlating requests with responses.
7pub type RequestId = u64;
8
9/// Generates monotonically increasing request IDs.
10#[derive(Debug, Clone)]
11pub struct Generator {
12    counter: Arc<AtomicU64>,
13}
14
15impl Default for Generator {
16    fn default() -> Self {
17        Self::new()
18    }
19}
20
21impl Generator {
22    pub fn new() -> Self {
23        Generator {
24            counter: Arc::new(AtomicU64::new(1)),
25        }
26    }
27
28    pub fn next(&self) -> RequestId {
29        self.counter.fetch_add(1, Ordering::Relaxed)
30    }
31}
32
33#[cfg(test)]
34mod tests {
35    use super::Generator;
36
37    #[test]
38    fn test_request_id_generation() {
39        let requester = Generator::new();
40        let id1 = requester.next();
41        let id2 = requester.next();
42        let id3 = requester.next();
43
44        // Request IDs should be monotonically increasing
45        assert!(id2 > id1);
46        assert!(id3 > id2);
47
48        // Should be consecutive since we're using a single Requester
49        assert_eq!(id2, id1 + 1);
50        assert_eq!(id3, id2 + 1);
51    }
52}