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
use crate::sync::{AtomicBool, ReadGuard, RwLock, WriteGuard};
#[cfg(parallel_compiler)]
use crate::sync::{DynSend, DynSync};
use std::{
    cell::UnsafeCell,
    intrinsics::likely,
    marker::PhantomData,
    ops::{Deref, DerefMut},
    ptr::NonNull,
    sync::atomic::Ordering,
};

/// A type which allows mutation using a lock until
/// the value is frozen and can be accessed lock-free.
///
/// Unlike `RwLock`, it can be used to prevent mutation past a point.
#[derive(Default)]
pub struct FreezeLock<T> {
    data: UnsafeCell<T>,
    frozen: AtomicBool,

    /// This lock protects writes to the `data` and `frozen` fields.
    lock: RwLock<()>,
}

#[cfg(parallel_compiler)]
unsafe impl<T: DynSync + DynSend> DynSync for FreezeLock<T> {}

impl<T> FreezeLock<T> {
    #[inline]
    pub fn new(value: T) -> Self {
        Self::with(value, false)
    }

    #[inline]
    pub fn frozen(value: T) -> Self {
        Self::with(value, true)
    }

    #[inline]
    pub fn with(value: T, frozen: bool) -> Self {
        Self {
            data: UnsafeCell::new(value),
            frozen: AtomicBool::new(frozen),
            lock: RwLock::new(()),
        }
    }

    /// Clones the inner value along with the frozen state.
    #[inline]
    pub fn clone(&self) -> Self
    where
        T: Clone,
    {
        let lock = self.read();
        Self::with(lock.clone(), self.is_frozen())
    }

    #[inline]
    pub fn is_frozen(&self) -> bool {
        self.frozen.load(Ordering::Acquire)
    }

    /// Get the inner value if frozen.
    #[inline]
    pub fn get(&self) -> Option<&T> {
        if likely(self.frozen.load(Ordering::Acquire)) {
            // SAFETY: This is frozen so the data cannot be modified.
            unsafe { Some(&*self.data.get()) }
        } else {
            None
        }
    }

    #[inline]
    pub fn read(&self) -> FreezeReadGuard<'_, T> {
        FreezeReadGuard {
            _lock_guard: if self.frozen.load(Ordering::Acquire) {
                None
            } else {
                Some(self.lock.read())
            },
            data: unsafe { NonNull::new_unchecked(self.data.get()) },
        }
    }

    #[inline]
    pub fn borrow(&self) -> FreezeReadGuard<'_, T> {
        self.read()
    }

    #[inline]
    #[track_caller]
    pub fn write(&self) -> FreezeWriteGuard<'_, T> {
        self.try_write().expect("still mutable")
    }

    #[inline]
    pub fn try_write(&self) -> Option<FreezeWriteGuard<'_, T>> {
        let _lock_guard = self.lock.write();
        // Use relaxed ordering since we're in the write lock.
        if self.frozen.load(Ordering::Relaxed) {
            None
        } else {
            Some(FreezeWriteGuard {
                _lock_guard,
                data: unsafe { NonNull::new_unchecked(self.data.get()) },
                frozen: &self.frozen,
                marker: PhantomData,
            })
        }
    }

    #[inline]
    pub fn freeze(&self) -> &T {
        if !self.frozen.load(Ordering::Acquire) {
            // Get the lock to ensure no concurrent writes and that we release the latest write.
            let _lock = self.lock.write();
            self.frozen.store(true, Ordering::Release);
        }

        // SAFETY: This is frozen so the data cannot be modified and shared access is sound.
        unsafe { &*self.data.get() }
    }
}

/// A guard holding shared access to a `FreezeLock` which is in a locked state or frozen.
#[must_use = "if unused the FreezeLock may immediately unlock"]
pub struct FreezeReadGuard<'a, T: ?Sized> {
    _lock_guard: Option<ReadGuard<'a, ()>>,
    data: NonNull<T>,
}

impl<'a, T: ?Sized + 'a> Deref for FreezeReadGuard<'a, T> {
    type Target = T;
    #[inline]
    fn deref(&self) -> &T {
        // SAFETY: If the lock is not frozen, `_lock_guard` holds the lock to the `UnsafeCell` so
        // this has shared access until the `FreezeReadGuard` is dropped. If the lock is frozen,
        // the data cannot be modified and shared access is sound.
        unsafe { &*self.data.as_ptr() }
    }
}

impl<'a, T: ?Sized> FreezeReadGuard<'a, T> {
    #[inline]
    pub fn map<U: ?Sized>(this: Self, f: impl FnOnce(&T) -> &U) -> FreezeReadGuard<'a, U> {
        FreezeReadGuard { data: NonNull::from(f(&*this)), _lock_guard: this._lock_guard }
    }
}

/// A guard holding mutable access to a `FreezeLock` which is in a locked state or frozen.
#[must_use = "if unused the FreezeLock may immediately unlock"]
pub struct FreezeWriteGuard<'a, T: ?Sized> {
    _lock_guard: WriteGuard<'a, ()>,
    frozen: &'a AtomicBool,
    data: NonNull<T>,
    marker: PhantomData<&'a mut T>,
}

impl<'a, T> FreezeWriteGuard<'a, T> {
    pub fn freeze(self) -> &'a T {
        self.frozen.store(true, Ordering::Release);

        // SAFETY: This is frozen so the data cannot be modified and shared access is sound.
        unsafe { &*self.data.as_ptr() }
    }
}

impl<'a, T: ?Sized> FreezeWriteGuard<'a, T> {
    #[inline]
    pub fn map<U: ?Sized>(
        mut this: Self,
        f: impl FnOnce(&mut T) -> &mut U,
    ) -> FreezeWriteGuard<'a, U> {
        FreezeWriteGuard {
            data: NonNull::from(f(&mut *this)),
            _lock_guard: this._lock_guard,
            frozen: this.frozen,
            marker: PhantomData,
        }
    }
}

impl<'a, T: ?Sized + 'a> Deref for FreezeWriteGuard<'a, T> {
    type Target = T;
    #[inline]
    fn deref(&self) -> &T {
        // SAFETY: `self._lock_guard` holds the lock to the `UnsafeCell` so this has shared access.
        unsafe { &*self.data.as_ptr() }
    }
}

impl<'a, T: ?Sized + 'a> DerefMut for FreezeWriteGuard<'a, T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut T {
        // SAFETY: `self._lock_guard` holds the lock to the `UnsafeCell` so this has mutable access.
        unsafe { &mut *self.data.as_ptr() }
    }
}