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
//! This crate provides the [`PinArcMutex`] type, which offers shared mutable access to pinned
//! state.
//!
//! ### Problem
//!
//! Rust already provides good solutions to the problem of shared mutable state - often, this looks
//! like `Arc<Mutex<T>>`. However, sometimes we additionally need that shared mutable state to be
//! pinned. One example of this is wanting to poll a [`Stream`] from multiple threads.
//!
//! [`Stream`]: https://docs.rs/futures/latest/futures/stream/trait.Stream.html
//!
//! It turns out that there are no great ways to do this. The fundamental problem is that `Mutex`
//! types in std and tokio have no [structural pinning]. Unfortunately, that cannot be solved by
//! designing a better `PinnedMutex` type either - the real limitation is actually in [`Pin`]
//! itself. Specifically, because of methods like [`get_ref`], the `Pin` API makes it impossible to
//! assert pinned-ness of a `T` without creating a `&mut T`, which is prohibitive for cases like
//! mutexes.
//!
//! [`get_ref`]: std::pin::Pin::get_ref
//! [structural pinning]:
//! https://doc.rust-lang.org/std/pin/index.html#projections-and-structural-pinning
//!
//! ### Alternatives
//!
//! If your `T` is `Unpin`, you can use a `Arc<tokio::Mutex<T>>` directly and do not need this
//! crate.
//!
//! If you do not mind an extra allocation, you can also get a similar API without an extra
//! dependency via `Arc<tokio::Mutex<Pin<Box<T>>>>`.
//!
//! ### MSRV
//!
//! This crate has the same MSRV as its only dependency, tokio.
//!
use Pin;
use Arc;
use Mutex;
use MutexGuard as TokioGuard;
/// A type that resembles an `Arc<Mutex<T>>`, expected that the backing data is pinned.
///
/// The API surface of this type is essentially the combined API surface of [`Arc`] and
/// [`tokio::sync::Mutex`]. Specifically, there is an `Arc`-like [`Clone`] impl and a `Mutex`-like
/// [`lock`](PinArcMutex::lock) impl. The only difference is that the backing data is pinned - this
/// means that locking the mutex gets you access to a `Pin<&mut T>` instead of a `&mut T`.
/// The RAII type that is returned from locking a [`PinArcMutex`].
///
/// See the [`PinArcMutex::lock`] method for full details.