Debian Codegraph @

third_party/rust/threadbound/src/lib.rs

raw
1 //! [![github]](https://github.com/dtolnay/threadbound) [![crates-io]](https://crates.io/crates/threadbound) [![docs-rs]](https://docs.rs/threadbound)
2 //!
3 //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
4 //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
5 //! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
6 //!
7 //! <br>
8 //!
9 //! [`ThreadBound<T>`] is a wrapper that binds a value to its original thread.
10 //! The wrapper gets to be [`Sync`] and [`Send`] but only the original thread on
11 //! which the ThreadBound was constructed can retrieve the underlying value.
12 //!
13 //! [`ThreadBound<T>`]: struct.ThreadBound.html
14 //! [`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html
15 //! [`Send`]: https://doc.rust-lang.org/std/marker/trait.Send.html
16 //!
17 //! # Example
18 //!
19 //! ```
20 //! use std::marker::PhantomData;
21 //! use std::rc::Rc;
22 //! use std::sync::Arc;
23 //! use threadbound::ThreadBound;
24 //!
25 //! // Neither Send nor Sync. Maybe the index points into a
26 //! // thread-local interner.
27 //! #[derive(Copy, Clone)]
28 //! struct Span {
29 //! index: u32,
30 //! marker: PhantomData<Rc<()>>,
31 //! }
32 //!
33 //! // Error types are always supposed to be Send and Sync.
34 //! // We can use ThreadBound to make it so.
35 //! struct Error {
36 //! span: ThreadBound<Span>,
37 //! message: String,
38 //! }
39 //!
40 //! fn main() {
41 //! let err = Error {
42 //! span: ThreadBound::new(Span {
43 //! index: 99,
44 //! marker: PhantomData,
45 //! }),
46 //! message: "fearless concurrency".to_owned(),
47 //! };
48 //!
49 //! // Original thread can see the contents.
50 //! assert_eq!(err.span.get_ref().unwrap().index, 99);
51 //!
52 //! let err = Arc::new(err);
53 //! let err2 = err.clone();
54 //! std::thread::spawn(move || {
55 //! // Other threads cannot get access. Maybe they use
56 //! // a default value or a different codepath.
57 //! assert!(err2.span.get_ref().is_none());
58 //! });
59 //!
60 //! // Original thread can still see the contents.
61 //! assert_eq!(err.span.get_ref().unwrap().index, 99);
62 //! }
63 //! ```
64
65 #![doc(html_root_url = "https://docs.rs/threadbound/0.1.5")]
66 #![allow(clippy::doc_markdown)]
67
68 use std::fmt::{self, Debug};
69 use std::thread::{self, ThreadId};
70
71 /// ThreadBound is a Sync-maker and Send-maker that allows accessing a value
72 /// of type T only from the original thread on which the ThreadBound was
73 /// constructed.
74 ///
75 /// Refer to the [crate-level documentation] for a usage example.
76 ///
77 /// [crate-level documentation]: index.html
78 pub struct ThreadBound<T> {
79 value: T,
80 thread_id: ThreadId,
81 }
82
83 unsafe impl<T> Sync for ThreadBound<T> {}
84
85 // Send bound requires Copy, as otherwise Drop could run in the wrong place.
86 unsafe impl<T: Copy> Send for ThreadBound<T> {}
87
88 impl<T> ThreadBound<T> {
89 /// Binds a value to the current thread. The wrapper can be sent around to
90 /// other threads, but no other threads will be able to access the
91 /// underlying value.
92 pub fn new(value: T) -> Self {
93 ThreadBound {
94 value,
95 thread_id: thread::current().id(),
96 }
97 }
98
99 /// Accesses a reference to the underlying value if this is its original
100 /// thread, otherwise `None`.
101 pub fn get_ref(&self) -> Option<&T> {
102 if thread::current().id() == self.thread_id {
103 Some(&self.value)
104 } else {
105 None
106 }
107 }
108
109 /// Accesses a mutable reference to the underlying value if this is its
110 /// original thread, otherwise `None`.
111 pub fn get_mut(&mut self) -> Option<&mut T> {
112 if thread::current().id() == self.thread_id {
113 Some(&mut self.value)
114 } else {
115 None
116 }
117 }
118
119 /// Extracts ownership of the underlying value if this is its original
120 /// thread, otherwise `None`.
121 pub fn into_inner(self) -> Option<T> {
122 if thread::current().id() == self.thread_id {
123 Some(self.value)
124 } else {
125 None
126 }
127 }
128 }
129
130 impl<T: Default> Default for ThreadBound<T> {
131 fn default() -> Self {
132 ThreadBound::new(Default::default())
133 }
134 }
135
136 impl<T: Debug> Debug for ThreadBound<T> {
137 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
138 match self.get_ref() {
139 Some(value) => Debug::fmt(value, formatter),
140 None => formatter.write_str("unknown"),
141 }
142 }
143 }