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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
pub struct Counter(Arc<AtomicUsize>);
#[derive(Clone)]
pub struct WeakCounter(Arc<AtomicUsize>);
impl Counter {
pub fn new() -> Counter {
Counter(Arc::new(AtomicUsize::new(1)))
}
pub fn downgrade(self) -> WeakCounter {
WeakCounter(self.0.clone())
}
#[inline]
pub fn count(&self) -> usize {
self.0.load(Ordering::Acquire)
}
}
impl Clone for Counter {
fn clone(&self) -> Self {
self.0.fetch_add(1, Ordering::AcqRel);
Counter(self.0.clone())
}
}
impl Drop for Counter {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::AcqRel);
}
}
impl WeakCounter {
pub fn new() -> WeakCounter {
WeakCounter(Arc::new(AtomicUsize::new(0)))
}
#[inline]
pub fn count(&self) -> usize {
self.0.load(Ordering::Acquire)
}
pub fn upgrade(self) -> Counter {
self.spawn_upgrade()
}
pub fn spawn_upgrade(&self) -> Counter {
self.0.fetch_add(1, Ordering::AcqRel);
Counter(self.0.clone())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let counter = Counter::new();
assert_eq!(counter.count(), 1);
let weak = counter.downgrade();
assert_eq!(weak.count(), 0);
{
let _counter1 = weak.spawn_upgrade();
assert_eq!(weak.count(), 1);
let _counter2 = weak.spawn_upgrade();
assert_eq!(weak.count(), 2);
}
assert_eq!(weak.count(), 0);
}
}