rune/runtime/
access.rs

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
use core::cell::Cell;
use core::fmt;
use core::mem::ManuallyDrop;
use core::ptr::NonNull;

use super::TypeInfo;

/// Test if exclusively held.
const EXCLUSIVE: usize = 1usize.rotate_right(2);
/// Sentinel value to indicate that access is taken.
const MOVED: usize = 1usize.rotate_right(1);
/// Mask indicating if the value is exclusively set or moved.
const MASK: usize = EXCLUSIVE | MOVED;

/// An error raised when failing to access a value.
///
/// Access errors can be raised for various reasons, such as:
/// * The value you are trying to access is an empty placeholder.
/// * The value is already being accessed in an incompatible way, such as trying
///   to access a value exclusively twice.
/// * The value has been taken and is no longer present.
#[derive(Debug)]
#[cfg_attr(test, derive(PartialEq))]
#[non_exhaustive]
pub struct AccessError {
    kind: AccessErrorKind,
}

impl AccessError {
    #[inline]
    pub(crate) const fn not_owned(type_info: TypeInfo) -> Self {
        Self {
            kind: AccessErrorKind::NotAccessibleOwned(type_info),
        }
    }

    #[inline]
    pub(crate) const fn new(kind: AccessErrorKind) -> Self {
        Self { kind }
    }
}

impl fmt::Display for AccessError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match &self.kind {
            AccessErrorKind::NotAccessibleRef(s) => write!(f, "Cannot read, value is {s}"),
            AccessErrorKind::NotAccessibleMut(s) => write!(f, "Cannot write, value is {s}"),
            AccessErrorKind::NotAccessibleTake(s) => write!(f, "Cannot take, value is {s}"),
            AccessErrorKind::NotAccessibleOwned(type_info) => {
                write!(f, "Cannot use owned operations for {type_info}")
            }
        }
    }
}

impl core::error::Error for AccessError {}

impl From<AccessErrorKind> for AccessError {
    #[inline]
    fn from(kind: AccessErrorKind) -> Self {
        AccessError::new(kind)
    }
}

#[derive(Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub(crate) enum AccessErrorKind {
    NotAccessibleRef(Snapshot),
    NotAccessibleMut(Snapshot),
    NotAccessibleTake(Snapshot),
    NotAccessibleOwned(TypeInfo),
}

/// Snapshot that can be used to indicate how the value was being accessed at
/// the time of an error.
#[derive(PartialEq)]
#[repr(transparent)]
pub(crate) struct Snapshot(usize);

impl Snapshot {
    /// Test if the snapshot indicates that the value is readable.
    pub(crate) fn is_readable(&self) -> bool {
        self.0 & MASK == 0
    }

    /// Test if the snapshot indicates that the value is writable.
    pub(crate) fn is_writable(&self) -> bool {
        self.0 & MASK == 0
    }

    /// Test if access is exclusively held.
    pub(crate) fn is_exclusive(&self) -> bool {
        self.0 & MASK != 0
    }

    /// The number of times a value is shared.
    pub(crate) fn shared(&self) -> usize {
        self.0 & !MASK
    }
}

impl fmt::Display for Snapshot {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.0 & MOVED != 0 {
            write!(f, "M")?;
        } else {
            write!(f, "-")?;
        }

        if self.0 & EXCLUSIVE != 0 {
            write!(f, "X")?;
        } else {
            write!(f, "-")?;
        }

        write!(f, "{:06}", self.shared())?;
        Ok(())
    }
}

impl fmt::Debug for Snapshot {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Snapshot({self})")
    }
}

/// Access flags.
///
/// These accomplish the following things:
/// * Indicates if a value is exclusively held.
/// * Indicates if a value is taken .
/// * Indicates if a value is shared, and if so by how many.
#[repr(transparent)]
pub(crate) struct Access(Cell<usize>);

impl Access {
    /// Construct a new default access.
    pub(crate) const fn new() -> Self {
        Self(Cell::new(0))
    }

    /// Test if we can have shared access without modifying the internal count.
    #[inline(always)]
    pub(crate) fn is_shared(&self) -> bool {
        self.0.get() & MASK == 0
    }

    /// Test if we can have exclusive access without modifying the internal
    /// count.
    #[inline(always)]
    pub(crate) fn is_exclusive(&self) -> bool {
        self.0.get() == 0
    }

    /// Test if the data has been taken.
    #[inline(always)]
    pub(crate) fn is_taken(&self) -> bool {
        self.0.get() & MOVED != 0
    }

    /// Mark that we want shared access to the given access token.
    pub(crate) fn shared(&self) -> Result<AccessGuard<'_>, AccessError> {
        self.try_shared()?;
        Ok(AccessGuard(self))
    }

    #[inline(always)]
    pub(crate) fn try_shared(&self) -> Result<(), AccessError> {
        let state = self.0.get();

        if state & MASK != 0 {
            debug_assert_eq!(
                state & !MASK,
                0,
                "count should be zero, but was {}",
                Snapshot(state)
            );
            return Err(AccessError::new(AccessErrorKind::NotAccessibleRef(
                Snapshot(state),
            )));
        }

        // NB: Max number of shared.
        if state == !MASK {
            crate::alloc::abort();
        }

        self.0.set(state + 1);
        Ok(())
    }

    /// Mark that we want exclusive access to the given access token.
    #[inline(always)]
    pub(crate) fn exclusive(&self) -> Result<AccessGuard<'_>, AccessError> {
        self.try_exclusive()?;
        Ok(AccessGuard(self))
    }

    #[inline(always)]
    pub(crate) fn try_exclusive(&self) -> Result<(), AccessError> {
        let state = self.0.get();

        if state != 0 {
            return Err(AccessError::new(AccessErrorKind::NotAccessibleMut(
                Snapshot(state),
            )));
        }

        self.0.set(state | EXCLUSIVE);
        Ok(())
    }

    /// Mark that we want to mark the given access as "taken".
    ///
    /// I.e. whatever guarded data is no longer available.
    #[inline(always)]
    pub(crate) fn try_take(&self) -> Result<(), AccessError> {
        let state = self.0.get();

        if state != 0 {
            return Err(AccessError::new(AccessErrorKind::NotAccessibleTake(
                Snapshot(state),
            )));
        }

        self.0.set(state | MOVED);
        Ok(())
    }

    /// Unconditionally mark the given access as "taken".
    #[inline(always)]
    pub(crate) fn take(&self) {
        let state = self.0.get();
        self.0.set(state | MOVED);
    }

    /// Release the current access, unless it's moved.
    #[inline(always)]
    pub(super) fn release(&self) {
        let b = self.0.get();

        let b = if b & EXCLUSIVE != 0 {
            b & !EXCLUSIVE
        } else {
            debug_assert_ne!(b & !MASK, 0, "count should be zero but was {}", Snapshot(b));
            b - 1
        };

        self.0.set(b);
    }

    /// Get a snapshot of current access.
    #[inline(always)]
    pub(super) fn snapshot(&self) -> Snapshot {
        Snapshot(self.0.get())
    }
}

impl fmt::Debug for Access {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", Snapshot(self.0.get()))
    }
}

/// A guard around some specific access access.
#[repr(transparent)]
pub(crate) struct AccessGuard<'a>(&'a Access);

impl AccessGuard<'_> {
    /// Convert into a raw guard which does not have a lifetime associated with
    /// it. Droping the raw guard will release the resource.
    ///
    /// # Safety
    ///
    /// Since we're losing track of the lifetime, caller must ensure that the
    /// access outlives the guard.
    pub(crate) unsafe fn into_raw(self) -> RawAccessGuard {
        RawAccessGuard(NonNull::from(ManuallyDrop::new(self).0))
    }
}

impl Drop for AccessGuard<'_> {
    fn drop(&mut self) {
        self.0.release();
    }
}

/// A raw guard around some level of access which will be released once the guard is dropped.
#[repr(transparent)]
pub(crate) struct RawAccessGuard(NonNull<Access>);

impl Drop for RawAccessGuard {
    fn drop(&mut self) {
        unsafe { self.0.as_ref().release() }
    }
}