keepcalm 0.5.0

Simple shared types for multi-threaded programs
Documentation
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use crate::rcu::{RcuLock, RcuReadGuard, RcuWriteGuard};
use parking_lot::{Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::{fmt::Debug, sync::Arc};

/// Virtual dispatch.
macro_rules! with_ops {
    ($self:ident: $( $pat:pat ),+ => $expr:expr ) => {
        match $self {
            Self::Arc($($pat),+) => $expr,
            Self::ReadCopyUpdate($($pat),+) => $expr,
            Self::RwLock($($pat),+) => $expr,
            Self::Mutex($($pat),+) => $expr,
        }
    };
}

/// UNSAFETY: We can implement this for all types, as T must always be Send unless it is a projection, in which case the
/// projection functions must be Send.
unsafe impl<'a, M: Send + Sync, T> Send for SynchronizerReadLock<'a, M, T> {}
unsafe impl<'a, M: Send + Sync, T> Send for SynchronizerWriteLock<'a, M, T> {}

#[derive(Clone, Copy)]
pub enum SynchronizerType {
    Arc,
    Rcu,
    RwLock,
    Mutex,
}

pub trait SynchronizerMetadata<M> {
    fn metadata(&self) -> &M;
}

pub enum SynchronizerReadLock<'a, M, T: ?Sized> {
    /// A read "lock" that's just a plain reference.
    Arc(&'a M, &'a T),
    /// A read "lock" that's an arc, used for RCU mode.
    ReadCopyUpdate(&'a M, RcuReadGuard<T>),
    /// RwLock's read lock.
    RwLock(&'a M, RwLockReadGuard<'a, T>),
    /// Mutex's read lock.
    Mutex(&'a M, MutexGuard<'a, T>),
}

impl<'a, M, T: ?Sized> std::ops::Deref for SynchronizerReadLock<'a, M, T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        with_ops!(self: _, x => x)
    }
}

impl<'a, M, T: ?Sized> SynchronizerMetadata<M> for SynchronizerReadLock<'a, M, T> {
    fn metadata(&self) -> &M {
        with_ops!(self: x, _ => x)
    }
}

pub enum SynchronizerWriteLock<'a, M, T: ?Sized> {
    Arc(&'a M, &'a mut T),
    ReadCopyUpdate(&'a M, RcuWriteGuard<'a, T>),
    RwLock(&'a M, RwLockWriteGuard<'a, T>),
    Mutex(&'a M, MutexGuard<'a, T>),
}

impl<'a, M, T: ?Sized> std::ops::Deref for SynchronizerWriteLock<'a, M, T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        with_ops!(self: _, x => x.deref())
    }
}

impl<'a, M, T: ?Sized> std::ops::DerefMut for SynchronizerWriteLock<'a, M, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        with_ops!(self: _, x => x.deref_mut())
    }
}

impl<'a, M, T: ?Sized> SynchronizerMetadata<M> for SynchronizerWriteLock<'a, M, T> {
    fn metadata(&self) -> &M {
        with_ops!(self: x, _ => x)
    }
}

/// Raw implementations.
pub enum SynchronizerSized<M, T> {
    /// Only usable by non-mutable shares.
    Arc(SynchronizerImpl<M, T>),
    /// RCU-mode, which requires us to bring a cloning function along for the ride.
    ReadCopyUpdate(SynchronizerImpl<M, RcuLock<T>>),
    /// R/W lock.
    RwLock(SynchronizerImpl<M, RwLock<T>>),
    /// Mutex.
    Mutex(SynchronizerImpl<M, Mutex<T>>),
}

impl<M, T> SynchronizerSized<M, T> {
    #[cfg(feature = "deadlock_detection")]
    pub fn sync_type(&self) -> SynchronizerType {
        match self {
            Self::Arc(_) => SynchronizerType::Arc,
            Self::ReadCopyUpdate(_) => SynchronizerType::Rcu,
            Self::RwLock(_) => SynchronizerType::RwLock,
            Self::Mutex(_) => SynchronizerType::Mutex,
        }
    }
    #[cfg(feature = "deadlock_detection")]
    pub fn metadata(&self) -> &M {
        with_ops!(self: x => &x.metadata)
    }
    pub fn lock_read(&self) -> SynchronizerReadLock<M, T> {
        with_ops!(self: x => x.lock_read())
    }
    pub fn try_lock_read(&self) -> Option<SynchronizerReadLock<M, T>> {
        with_ops!(self: x => x.try_lock_read())
    }
    pub fn lock_write(&self) -> SynchronizerWriteLock<M, T> {
        with_ops!(self: x => x.lock_write())
    }
    pub fn try_lock_write(&self) -> Option<SynchronizerWriteLock<M, T>> {
        with_ops!(self: x => x.try_lock_write())
    }
}

impl<M, T> SynchronizerSized<M, T> {
    pub const fn new(metadata: M, sync_type: SynchronizerType, value: T) -> Self {
        match sync_type {
            SynchronizerType::Arc => Self::Arc(SynchronizerImpl {
                metadata,
                container: value,
            }),
            SynchronizerType::Rcu => panic!("RCU must be called with new_cloneable"),
            SynchronizerType::Mutex => Self::Mutex(SynchronizerImpl {
                metadata,
                container: Mutex::new(value),
            }),
            SynchronizerType::RwLock => Self::RwLock(SynchronizerImpl {
                metadata,
                container: RwLock::new(value),
            }),
        }
    }

    pub fn new_cloneable(metadata: M, sync_type: SynchronizerType, value: T) -> Self
    where
        T: Clone,
    {
        match sync_type {
            SynchronizerType::Rcu => Self::ReadCopyUpdate(SynchronizerImpl {
                metadata,
                container: RcuLock::new(value),
            }),
            _ => Self::new(metadata, sync_type, value),
        }
    }
}

/// Raw implementations. Note that because Rust doesn't support unsized enums, the [`std::sync::Arc`] lives inside
/// of the enum.
pub enum SynchronizerUnsized<M, T: ?Sized> {
    /// Only usable by non-mutable shares.
    Arc(Arc<SynchronizerImpl<M, T>>),
    /// RCU-mode, which requires us to bring a cloning function along for the ride.
    ReadCopyUpdate(Arc<SynchronizerImpl<M, RcuLock<T>>>),
    /// R/W lock.
    RwLock(Arc<SynchronizerImpl<M, RwLock<T>>>),
    /// Mutex.
    Mutex(Arc<SynchronizerImpl<M, Mutex<T>>>),
}

impl<M, T: ?Sized> SynchronizerMetadata<M> for SynchronizerUnsized<M, T> {
    fn metadata(&self) -> &M {
        with_ops!(self: x => &x.metadata)
    }
}

impl<M, T: ?Sized> Clone for SynchronizerUnsized<M, T> {
    fn clone(&self) -> Self {
        match self {
            Self::Arc(x) => Self::Arc(x.clone()),
            Self::ReadCopyUpdate(x) => Self::ReadCopyUpdate(x.clone()),
            Self::RwLock(x) => Self::RwLock(x.clone()),
            Self::Mutex(x) => Self::Mutex(x.clone()),
        }
    }
}

impl<M, T: ?Sized> Debug for SynchronizerUnsized<M, T>
where
    T: Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        with_ops!(self: x => x.fmt(f))
    }
}

impl<M, T> SynchronizerUnsized<M, T> {
    pub fn new(metadata: M, sync_type: SynchronizerType, value: T) -> Self {
        match sync_type {
            SynchronizerType::Arc => Self::Arc(Arc::new(SynchronizerImpl {
                metadata,
                container: value,
            })),
            SynchronizerType::Rcu => unimplemented!("RCU must be called with new_cloneable"),
            SynchronizerType::Mutex => Self::Mutex(Arc::new(SynchronizerImpl {
                metadata,
                container: Mutex::new(value),
            })),
            SynchronizerType::RwLock => Self::RwLock(Arc::new(SynchronizerImpl {
                metadata,
                container: RwLock::new(value),
            })),
        }
    }

    pub fn new_cloneable(metadata: M, sync_type: SynchronizerType, value: T) -> Self
    where
        T: Clone,
    {
        match sync_type {
            SynchronizerType::Rcu => Self::ReadCopyUpdate(Arc::new(SynchronizerImpl {
                metadata,
                container: RcuLock::new(value),
            })),
            _ => Self::new(metadata, sync_type, value),
        }
    }

    pub fn try_unwrap(self) -> Result<T, Self> {
        macro_rules! match_arm {
            ($x:ident, $id:ident) => {
                Arc::try_unwrap($x)
                    .map_err(Self::$id)
                    .and_then(|x| x.try_unwrap_or_sync(Self::$id))
            };
        }
        match self {
            Self::Arc(x) => match_arm!(x, Arc),
            Self::ReadCopyUpdate(x) => match_arm!(x, ReadCopyUpdate),
            Self::RwLock(x) => match_arm!(x, RwLock),
            Self::Mutex(x) => match_arm!(x, Mutex),
        }
    }
}

impl<M, T: ?Sized> SynchronizerUnsized<M, T> {
    #[cfg(feature = "deadlock_detection")]
    pub fn sync_type(&self) -> SynchronizerType {
        match self {
            Self::Arc(_) => SynchronizerType::Arc,
            Self::ReadCopyUpdate(_) => SynchronizerType::Rcu,
            Self::RwLock(_) => SynchronizerType::RwLock,
            Self::Mutex(_) => SynchronizerType::Mutex,
        }
    }
    pub fn lock_read(&self) -> SynchronizerReadLock<M, T> {
        with_ops!(self: x => x.lock_read())
    }
    pub fn try_lock_read(&self) -> Option<SynchronizerReadLock<M, T>> {
        with_ops!(self: x => x.try_lock_read())
    }
    pub fn lock_write(&self) -> SynchronizerWriteLock<M, T> {
        with_ops!(self: x => x.lock_write())
    }
    pub fn try_lock_write(&self) -> Option<SynchronizerWriteLock<M, T>> {
        with_ops!(self: x => x.try_lock_write())
    }
}

pub trait SynchronizerOps<M, T: ?Sized> {
    fn try_unwrap(self) -> Result<T, Self>
    where
        Self: Sized,
        T: Sized;
    fn try_unwrap_or_sync(
        self,
        f: impl Fn(Arc<Self>) -> SynchronizerUnsized<M, T>,
    ) -> Result<T, SynchronizerUnsized<M, T>>
    where
        Self: Sized,
        T: Sized,
    {
        self.try_unwrap().map_err(|x| f(Arc::new(x)))
    }
    fn lock_read(&self) -> SynchronizerReadLock<M, T>;
    fn try_lock_read(&self) -> Option<SynchronizerReadLock<M, T>>;
    fn lock_write(&self) -> SynchronizerWriteLock<M, T>;
    fn try_lock_write(&self) -> Option<SynchronizerWriteLock<M, T>>;
}

pub struct SynchronizerImpl<M, C: ?Sized> {
    metadata: M,
    container: C,
}

impl<M, C: ?Sized> Debug for SynchronizerImpl<M, C>
where
    C: Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.container.fmt(f)
    }
}

impl<M, T: ?Sized> SynchronizerOps<M, T> for SynchronizerImpl<M, RwLock<T>> {
    fn try_unwrap(self) -> Result<T, Self>
    where
        Self: Sized,
        T: Sized,
    {
        Ok(self.container.into_inner())
    }

    fn lock_read(&self) -> SynchronizerReadLock<M, T> {
        SynchronizerReadLock::RwLock(&self.metadata, self.container.read())
    }

    fn try_lock_read(&self) -> Option<SynchronizerReadLock<M, T>> {
        self.container
            .try_read()
            .map(|x| SynchronizerReadLock::RwLock(&self.metadata, x))
    }

    fn lock_write(&self) -> SynchronizerWriteLock<M, T> {
        SynchronizerWriteLock::RwLock(&self.metadata, self.container.write())
    }

    fn try_lock_write(&self) -> Option<SynchronizerWriteLock<M, T>> {
        self.container
            .try_write()
            .map(|x| SynchronizerWriteLock::RwLock(&self.metadata, x))
    }
}

impl<M, T: ?Sized> SynchronizerOps<M, T> for SynchronizerImpl<M, Mutex<T>> {
    fn try_unwrap(self) -> Result<T, Self>
    where
        Self: Sized,
        T: Sized,
    {
        Ok(self.container.into_inner())
    }

    fn lock_read(&self) -> SynchronizerReadLock<M, T> {
        SynchronizerReadLock::Mutex(&self.metadata, self.container.lock())
    }

    fn try_lock_read(&self) -> Option<SynchronizerReadLock<M, T>> {
        self.container
            .try_lock()
            .map(|x| SynchronizerReadLock::Mutex(&self.metadata, x))
    }

    fn lock_write(&self) -> SynchronizerWriteLock<M, T> {
        SynchronizerWriteLock::Mutex(&self.metadata, self.container.lock())
    }

    fn try_lock_write(&self) -> Option<SynchronizerWriteLock<M, T>> {
        self.container
            .try_lock()
            .map(|x| SynchronizerWriteLock::Mutex(&self.metadata, x))
    }
}

impl<M, T: ?Sized> SynchronizerOps<M, T> for SynchronizerImpl<M, RcuLock<T>> {
    fn try_unwrap(self) -> Result<T, Self>
    where
        Self: Sized,
        T: Sized,
    {
        let metadata = self.metadata;
        self.container.try_unwrap().map_err(|container| Self {
            metadata,
            container,
        })
    }

    fn lock_read(&self) -> SynchronizerReadLock<M, T> {
        SynchronizerReadLock::ReadCopyUpdate(&self.metadata, self.container.read())
    }

    fn try_lock_read(&self) -> Option<SynchronizerReadLock<M, T>> {
        Some(self.lock_read())
    }

    fn lock_write(&self) -> SynchronizerWriteLock<M, T> {
        SynchronizerWriteLock::ReadCopyUpdate(&self.metadata, self.container.write())
    }

    fn try_lock_write(&self) -> Option<SynchronizerWriteLock<M, T>> {
        Some(self.lock_write())
    }
}

impl<M, T: ?Sized> SynchronizerOps<M, T> for SynchronizerImpl<M, T> {
    fn try_unwrap(self) -> Result<T, Self>
    where
        Self: Sized,
        T: Sized,
    {
        Ok(self.container)
    }

    fn lock_read(&self) -> SynchronizerReadLock<M, T> {
        SynchronizerReadLock::Arc(&self.metadata, &self.container)
    }

    fn try_lock_read(&self) -> Option<SynchronizerReadLock<M, T>> {
        Some(self.lock_read())
    }

    fn lock_write(&self) -> SynchronizerWriteLock<M, T> {
        unreachable!()
    }

    fn try_lock_write(&self) -> Option<SynchronizerWriteLock<M, T>> {
        unreachable!()
    }
}