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
#![forbid(unsafe_code)]
use std::{
fmt::Debug,
sync::atomic::{AtomicU32, AtomicU64, Ordering},
};
pub trait IdGenerator<Id: Copy + Debug> {
fn next(&self) -> Id;
}
#[derive(Debug)]
pub struct U32IdGenerator {
inner: AtomicU32,
}
impl U32IdGenerator {
pub const fn new() -> Self {
Self::new_with_value(0)
}
pub const fn new_with_value(initial_value: u32) -> Self {
Self {
inner: AtomicU32::new(initial_value),
}
}
}
impl IdGenerator<u32> for U32IdGenerator {
#[inline]
fn next(&self) -> u32 {
self.inner.fetch_add(1, Ordering::Relaxed)
}
}
#[derive(Debug)]
pub struct U64IdGenerator {
inner: AtomicU64,
}
impl U64IdGenerator {
pub const fn new() -> Self {
Self::new_with_value(0)
}
pub const fn new_with_value(initial_value: u64) -> Self {
Self {
inner: AtomicU64::new(initial_value),
}
}
}
impl IdGenerator<u64> for U64IdGenerator {
#[inline]
fn next(&self) -> u64 {
self.inner.fetch_add(1, Ordering::Relaxed)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn check_generation() {
let id_generator = U64IdGenerator::new();
for i in 0..10 {
assert_eq!(i, id_generator.next())
}
}
#[test]
fn check_overflow() {
let id_generator = U64IdGenerator::new_with_value(u64::MAX);
assert_eq!(u64::MAX, id_generator.next());
assert_eq!(0, id_generator.next());
}
}