forked from feather-rs/feather
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread_pinned.rs
More file actions
45 lines (39 loc) · 1.05 KB
/
thread_pinned.rs
File metadata and controls
45 lines (39 loc) · 1.05 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
use std::{
cell::{Ref, RefCell, RefMut},
thread::{self, ThreadId},
};
/// Wraps a [`RefCell`] but implements `Send` and `Sync`.
///
/// The value can only be borrowed on the thread it was created
/// on; this is enforced at runtime. In other words, access to
/// the value is pinned to the main thread.
pub struct ThreadPinned<T> {
cell: RefCell<T>,
pinned_to: ThreadId,
}
impl<T> ThreadPinned<T> {
pub fn new(value: T) -> Self {
Self {
cell: RefCell::new(value),
pinned_to: thread::current().id(),
}
}
#[allow(unused)]
pub fn borrow(&self) -> Ref<T> {
self.assert_thread();
self.cell.borrow()
}
pub fn borrow_mut(&self) -> RefMut<T> {
self.assert_thread();
self.cell.borrow_mut()
}
fn assert_thread(&self) {
assert_eq!(
thread::current().id(),
self.pinned_to,
"can only borrow value on the main thread"
);
}
}
unsafe impl<T> Send for ThreadPinned<T> {}
unsafe impl<T> Sync for ThreadPinned<T> {}