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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
use core::cell::{Ref, RefCell, RefMut};
use crate::{GetMock, Guard, SetMock};
#[derive(Debug)]
pub struct ThreadLocal<T: Send> {
tls: thread_local::ThreadLocal<ThreadLocalInner<T>>,
}
impl<T: Send> Default for ThreadLocal<T> {
fn default() -> Self {
Self {
tls: thread_local::ThreadLocal::new(),
}
}
}
#[derive(Debug)]
struct ThreadLocalInner<T> {
inner: RefCell<Option<T>>,
write_lock: RefCell<()>,
}
impl<T> Default for ThreadLocalInner<T> {
fn default() -> Self {
Self {
inner: RefCell::new(None),
write_lock: RefCell::new(()),
}
}
}
impl<'a, T: Send + 'static> GetMock<'a, T> for ThreadLocal<T> {
type Ref = Ref<'a, T>;
fn get(&'a self) -> Option<Ref<'a, T>> {
let cell = self.tls.get_or_default();
let borrow = cell.inner.borrow();
if borrow.is_some() {
Some(Ref::map(borrow, |option| option.as_ref().unwrap()))
} else {
None
}
}
}
impl<'a, T: Send + 'static> SetMock<'a, T> for ThreadLocal<T> {
type Guard = ThreadLocalGuard<'a, T>;
fn set(&self, state: T) -> ThreadLocalGuard<'_, T> {
let cell = self.tls.get_or_default();
let guard = cell.write_lock.try_borrow_mut().unwrap_or_else(|_| {
panic!("cannot set mock state while the previous state is active");
});
*cell.inner.borrow_mut() = Some(state);
ThreadLocalGuard {
mock: &cell.inner,
_guard: guard,
}
}
}
#[derive(Debug)]
pub struct ThreadLocalGuard<'a, T> {
mock: &'a RefCell<Option<T>>,
_guard: RefMut<'a, ()>,
}
impl<T> Drop for ThreadLocalGuard<'_, T> {
fn drop(&mut self) {
self.mock.borrow_mut().take();
}
}
impl<T> Guard<T> for ThreadLocalGuard<'_, T> {
fn with<R>(&mut self, action: impl FnOnce(&mut T) -> R) -> R {
action(self.mock.borrow_mut().as_mut().unwrap())
}
fn into_inner(self) -> T {
self.mock.borrow_mut().take().unwrap()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Static;
use static_assertions::assert_impl_all;
use std::cell::Cell;
assert_impl_all!(ThreadLocal<Cell<u8>>: Send, Sync);
assert_impl_all!(Static<ThreadLocal<Cell<u8>>>: Send, Sync);
}