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
use lock_api::{MutexGuard, RawMutex};
use std::{fmt, marker::PhantomData, ops::Deref};

/// A mutex guard that has an exclusive lock, but only an immutable reference; useful if you
/// need to map a mutex guard with a function that returns an `&T`. Construct using the
/// [`MapImmutable`] trait.
pub struct ImmutableMappedMutexGuard<'a, R: RawMutex, T: ?Sized> {
    raw: &'a R,
    data: *const T,
    _marker: PhantomData<(&'a T, R::GuardMarker)>,
}

// main constructor for ImmutableMappedMutexGuard
// TODO: patch lock_api to have a MappedMutexGuard::raw method, and have this implementation be for
// MappedMutexGuard
impl<'a, R: RawMutex, T: ?Sized> MapImmutable<'a, R, T> for MutexGuard<'a, R, T> {
    fn map_immutable<U: ?Sized, F>(s: Self, f: F) -> ImmutableMappedMutexGuard<'a, R, U>
    where
        F: FnOnce(&T) -> &U,
    {
        let raw = unsafe { MutexGuard::mutex(&s).raw() };
        let data = f(&s) as *const U;
        std::mem::forget(s);
        ImmutableMappedMutexGuard {
            raw,
            data,
            _marker: PhantomData,
        }
    }
}

impl<'a, R: RawMutex, T: ?Sized> ImmutableMappedMutexGuard<'a, R, T> {
    pub fn map<U: ?Sized, F>(s: Self, f: F) -> ImmutableMappedMutexGuard<'a, R, U>
    where
        F: FnOnce(&T) -> &U,
    {
        let raw = s.raw;
        let data = f(&s) as *const U;
        std::mem::forget(s);
        ImmutableMappedMutexGuard {
            raw,
            data,
            _marker: PhantomData,
        }
    }
}

impl<'a, R: RawMutex, T: ?Sized> Deref for ImmutableMappedMutexGuard<'a, R, T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        // SAFETY: self.data is valid for the lifetime of the guard
        unsafe { &*self.data }
    }
}

impl<'a, R: RawMutex, T: ?Sized> Drop for ImmutableMappedMutexGuard<'a, R, T> {
    fn drop(&mut self) {
        // SAFETY: An ImmutableMappedMutexGuard always holds the lock
        unsafe { self.raw.unlock() }
    }
}

impl<'a, R: RawMutex, T: fmt::Debug + ?Sized> fmt::Debug for ImmutableMappedMutexGuard<'a, R, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&**self, f)
    }
}

impl<'a, R: RawMutex, T: fmt::Display + ?Sized> fmt::Display
    for ImmutableMappedMutexGuard<'a, R, T>
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&**self, f)
    }
}

pub trait MapImmutable<'a, R: RawMutex, T: ?Sized> {
    fn map_immutable<U: ?Sized, F>(s: Self, f: F) -> ImmutableMappedMutexGuard<'a, R, U>
    where
        F: FnOnce(&T) -> &U;
}