-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathrequest_id.rs
More file actions
52 lines (43 loc) · 1.08 KB
/
request_id.rs
File metadata and controls
52 lines (43 loc) · 1.08 KB
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
use std::sync::{
atomic::{AtomicU64, Ordering},
Arc,
};
/// Unique identifier for correlating requests with responses.
pub type RequestId = u64;
/// Generates monotonically increasing request IDs.
#[derive(Debug, Clone)]
pub struct Generator {
counter: Arc<AtomicU64>,
}
impl Default for Generator {
fn default() -> Self {
Self::new()
}
}
impl Generator {
pub fn new() -> Self {
Self {
counter: Arc::new(AtomicU64::new(1)),
}
}
pub fn next(&self) -> RequestId {
self.counter.fetch_add(1, Ordering::Relaxed)
}
}
#[cfg(test)]
mod tests {
use super::Generator;
#[test]
fn test_request_id_generation() {
let requester = Generator::new();
let id1 = requester.next();
let id2 = requester.next();
let id3 = requester.next();
// Request IDs should be monotonically increasing
assert!(id2 > id1);
assert!(id3 > id2);
// Should be consecutive since we're using a single Requester
assert_eq!(id2, id1 + 1);
assert_eq!(id3, id2 + 1);
}
}