fairly_unsafe_cell 0.1.0

A hybrid between an UnsafeCell and a RefCell
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
use core::{
    cell::RefCell,
    fmt,
    ops::{Deref, DerefMut},
};

/// A cell that unsafely grants mutable access to its wrapped value. In test builds (`#[cfg(test)]`), it performs runtime checks to panic when mutable access is not exclusive. In non-test builds, it has no runtime overhead and silently allows for undefined behaviour.
#[derive(Debug)]
pub struct FairlyUnsafeCell<T: ?Sized>(RefCell<T>);

impl<T> FairlyUnsafeCell<T> {
    /// Creates a new `FairlyUnsafeCell` containing `value`.
    ///
    /// ```
    /// use fairly_unsafe_cell::*;
    ///
    /// let c = FairlyUnsafeCell::new(5);
    /// ```
    #[inline]
    pub const fn new(value: T) -> Self {
        Self(RefCell::new(value))
    }

    /// Consumes the `FairlyUnsafeCell`, returning the wrapped value.
    ///
    /// ```
    /// use fairly_unsafe_cell::*;
    ///
    /// let c = FairlyUnsafeCell::new(5);
    /// assert_eq!(c.into_inner(), 5);
    /// ```
    #[inline]
    pub fn into_inner(self) -> T {
        self.0.into_inner()
    }

    /// Replaces the wrapped value with a new one, returning the old value,
    /// without deinitializing either one.
    ///
    /// This function corresponds to [`core::mem::replace`].
    ///
    /// # Safety
    ///
    /// UB if the value is currently borrowed. Will panic instead of causing UB if `#[cfg(test)]`.
    ///
    /// # Examples
    ///
    /// ```
    /// use fairly_unsafe_cell::*;
    ///
    /// let cell = FairlyUnsafeCell::new(5);
    /// let old_value = unsafe { cell.replace(6) };
    /// assert_eq!(old_value, 5);
    /// assert_eq!(cell.into_inner(), 6);
    /// ```
    #[inline]
    pub unsafe fn replace(&self, t: T) -> T {
        self.0.replace(t)
    }

    /// Replaces the wrapped value with a new one computed from `f`, returning
    /// the old value, without deinitializing either one.
    ///
    /// # Safety
    ///
    /// UB if the value is currently borrowed. Will panic instead of causing UB if `#[cfg(test)]`.
    ///
    /// # Examples
    ///
    /// ```
    /// use fairly_unsafe_cell::*;
    ///
    /// let cell = FairlyUnsafeCell::new(5);
    /// let old_value = unsafe { cell.replace_with(|&mut old| old + 1) };
    /// assert_eq!(old_value, 5);
    /// assert_eq!(cell.into_inner(), 6);
    /// ```
    #[inline]
    pub unsafe fn replace_with<F: FnOnce(&mut T) -> T>(&self, f: F) -> T {
        self.0.replace_with(f)
    }

    /// Swaps the wrapped value of `self` with the wrapped value of `other`,
    /// without deinitializing either one.
    ///
    /// This function corresponds to [`core::mem::swap`].
    ///
    /// # Safety
    ///
    /// UB if the value in either `FairlyUnsafeCell` is currently borrowed, or
    /// if `self` and `other` point to the same `FairlyUnsafeCell`.
    /// Will panic instead of causing UB if `#[cfg(test)]`.
    ///
    /// # Examples
    ///
    /// ```
    /// use fairly_unsafe_cell::*;
    ///
    /// let c = FairlyUnsafeCell::new(5);
    /// let d = FairlyUnsafeCell::new(6);
    /// unsafe { c.swap(&d) };
    /// assert_eq!(c.into_inner(), 6);
    /// assert_eq!(d.into_inner(), 5);
    /// ```
    #[inline]
    pub unsafe fn swap(&self, other: &Self) {
        self.0.swap(&other.0)
    }
}

impl<T: ?Sized> FairlyUnsafeCell<T> {
    /// Immutably borrows the wrapped value.
    ///
    /// The borrow lasts until the returned `Ref` exits scope. Multiple
    /// immutable borrows can be taken out at the same time.
    ///
    /// # Safety
    ///
    /// UB if the value is currently mutably borrowed.
    /// Will panic instead of causing UB if `#[cfg(test)]`.
    ///
    /// # Examples
    ///
    /// ```
    /// use fairly_unsafe_cell::*;
    ///
    /// let c = FairlyUnsafeCell::new(5);
    ///
    /// unsafe {
    ///     let borrowed_five = c.borrow();
    ///     let borrowed_five2 = c.borrow();
    /// }
    /// ```
    ///
    /// An example of UB (and a panic if `#[cfg(test)]`):
    ///
    /// ```should_panic
    /// use fairly_unsafe_cell::*;
    ///
    /// let c = FairlyUnsafeCell::new(5);
    ///
    /// unsafe {
    ///     let m = c.borrow_mut();
    ///     let b = c.borrow(); // this causes UB in non-test code, and a panic in test code
    /// }
    /// ```
    #[inline]
    pub unsafe fn borrow(&self) -> Ref<'_, T> {
        Ref(self.0.borrow())
    }

    /// Mutably borrows the wrapped value.
    ///
    /// The borrow lasts until the returned `RefMut` or all `RefMut`s derived
    /// from it exit scope. The value cannot be borrowed while this borrow is
    /// active.
    ///
    /// # Safety
    ///
    /// UB if the value is currently borrowed.
    /// Will panic instead of causing UB if `#[cfg(test)]`.
    ///
    /// # Examples
    ///
    /// ```
    /// use fairly_unsafe_cell::*;
    ///
    /// let c = FairlyUnsafeCell::new("hello".to_owned());
    ///
    /// unsafe {
    ///     *c.borrow_mut() = "bonjour".to_owned();
    /// }
    ///
    /// assert_eq!(unsafe { &*c.borrow() }, "bonjour");
    /// ```
    ///
    /// An example of UB (and a panic if `#[cfg(test)]`):
    ///
    /// ```should_panic
    /// use fairly_unsafe_cell::*;
    ///
    /// let c = FairlyUnsafeCell::new(5);
    /// unsafe {
    ///     let m = c.borrow();    ///
    ///     let b = c.borrow_mut(); // this causes UB in non-test code, and a panic in test code
    /// }
    /// ```
    #[inline]
    pub unsafe fn borrow_mut(&self) -> RefMut<'_, T> {
        RefMut(self.0.borrow_mut())
    }

    /// Returns a raw pointer to the underlying data in this cell.
    ///
    /// # Examples
    ///
    /// ```
    /// use fairly_unsafe_cell::*;
    ///
    /// let c = FairlyUnsafeCell::new(5);
    ///
    /// let ptr = c.as_ptr();
    /// ```
    #[inline]
    pub fn as_ptr(&self) -> *mut T {
        self.0.as_ptr()
    }

    /// Returns a mutable reference to the underlying data.
    ///
    /// This call borrows the `UnsafeCell` mutably (at compile-time) which
    /// guarantees that we possess the only reference.
    ///
    /// # Examples
    ///
    /// ```
    /// use fairly_unsafe_cell::*;
    ///
    /// let mut c = FairlyUnsafeCell::new(5);
    /// *c.get_mut() += 1;
    ///
    /// assert_eq!(unsafe { *c.borrow() }, 6);
    /// ```
    #[inline(always)]
    pub fn get_mut(&mut self) -> &mut T {
        self.0.get_mut()
    }
}

impl<T: Default> Default for FairlyUnsafeCell<T> {
    /// Creates a `FairlyUnsafeCell<T>`, with the `Default` value for T.
    #[inline]
    fn default() -> FairlyUnsafeCell<T> {
        Self(RefCell::default())
    }
}

impl<T> From<T> for FairlyUnsafeCell<T> {
    /// Creates a new `FairlyUnsafeCell<T>` containing the given value.
    fn from(t: T) -> FairlyUnsafeCell<T> {
        Self(RefCell::from(t))
    }
}

/// A wrapper type for an immutably borrowed value from a `FairlyUnsafeCell<T>`.
///
/// See the [module-level documentation](crate) for more.
#[derive(Debug)]
pub struct Ref<'b, T>(core::cell::Ref<'b, T>)
where
    T: 'b + ?Sized;

impl<'b, T: ?Sized> Ref<'b, T> {
    /// Copies a `Ref`.
    ///
    /// The `FairlyUnsafeCell` is already immutably borrowed, so this cannot introduce UB where there was none before.
    ///
    /// This is an associated function that needs to be used as
    /// `Ref::clone(...)`. A `Clone` implementation or a method would interfere
    /// with the widespread use of `r.borrow().clone()` to clone the contents of
    /// a `FairlyUnsafeCell`.
    #[must_use]
    #[inline]
    pub fn clone(orig: &Ref<'b, T>) -> Ref<'b, T> {
        Ref(core::cell::Ref::clone(&orig.0))
    }

    /// Makes a new `Ref` for a component of the borrowed data.
    ///
    /// The `FairlyUnsafeCell` is already immutably borrowed, so this cannot introduce UB where there was none before.
    ///
    /// This is an associated function that needs to be used as `Ref::map(...)`.
    /// A method would interfere with methods of the same name on the contents
    /// of a `FairlyUnsafeCell` used through `Deref`.
    ///
    /// # Examples
    ///
    /// ```
    /// use fairly_unsafe_cell::*;
    ///
    /// let c = FairlyUnsafeCell::new((5, 'b'));
    /// let b1: Ref<'_, (u32, char)> = unsafe { c.borrow() };
    /// let b2: Ref<'_, u32> = Ref::map(b1, |t| &t.0);
    /// assert_eq!(*b2, 5)
    /// ```
    #[inline]
    pub fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, U>
    where
        F: FnOnce(&T) -> &U,
    {
        Ref(core::cell::Ref::map(orig.0, f))
    }

    /// Makes a new `Ref` for an optional component of the borrowed data. The
    /// original guard is returned as an `Err(..)` if the closure returns
    /// `None`.
    ///
    /// The `FairlyUnsafeCell` is already immutably borrowed, so this cannot introduce UB where there was none before.
    ///
    /// This is an associated function that needs to be used as
    /// `Ref::filter_map(...)`. A method would interfere with methods of the same
    /// name on the contents of a `FairlyUnsafeCell` used through `Deref`.
    ///
    /// # Examples
    ///
    /// ```
    /// use fairly_unsafe_cell::*;
    ///
    /// let c = FairlyUnsafeCell::new(vec![1, 2, 3]);
    /// let b1: Ref<'_, Vec<u32>> = unsafe { c.borrow() };
    /// let b2: Result<Ref<'_, u32>, _> = Ref::filter_map(b1, |v| v.get(1));
    /// assert_eq!(*b2.unwrap(), 2);
    /// ```
    #[inline]
    pub fn filter_map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Result<Ref<'b, U>, Self>
    where
        F: FnOnce(&T) -> Option<&U>,
    {
        match core::cell::Ref::filter_map(orig.0, f) {
            Ok(yay) => Ok(Ref(yay)),
            Err(nay) => Err(Ref(nay)),
        }
    }

    /// Splits a `Ref` into multiple `Ref`s for different components of the
    /// borrowed data.
    ///
    /// The `FairlyUnsafeCell` is already immutably borrowed, so this cannot introduce UB where there was none before.
    ///
    /// This is an associated function that needs to be used as
    /// `Ref::map_split(...)`. A method would interfere with methods of the same
    /// name on the contents of a `FairlyUnsafeCell` used through `Deref`.
    ///
    /// # Examples
    ///
    /// ```
    /// use fairly_unsafe_cell::*;
    ///
    /// let cell = FairlyUnsafeCell::new([1, 2, 3, 4]);
    /// let borrow = unsafe { cell.borrow() };
    /// let (begin, end) = Ref::map_split(borrow, |slice| slice.split_at(2));
    /// assert_eq!(*begin, [1, 2]);
    /// assert_eq!(*end, [3, 4]);
    /// ```
    #[inline]
    pub fn map_split<U: ?Sized, V: ?Sized, F>(orig: Ref<'b, T>, f: F) -> (Ref<'b, U>, Ref<'b, V>)
    where
        F: FnOnce(&T) -> (&U, &V),
    {
        let (a, b) = core::cell::Ref::map_split(orig.0, f);
        (Ref(a), Ref(b))
    }
}

impl<T: ?Sized> Deref for Ref<'_, T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &T {
        self.0.deref()
    }
}

impl<T: ?Sized + fmt::Display> fmt::Display for Ref<'_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// A wrapper type for a mutably borrowed value from a `FairlyUnsafeCell<T>`.
///
/// See the [module-level documentation](crate) for more.
#[derive(Debug)]
pub struct RefMut<'b, T>(core::cell::RefMut<'b, T>)
where
    T: 'b + ?Sized;

impl<'b, T: ?Sized> RefMut<'b, T> {
    /// Makes a new `RefMut` for a component of the borrowed data, e.g., an enum
    /// variant.
    ///
    /// The `FairlyUnsafeCell` is already mutably borrowed, so this cannot fail.
    ///
    /// This is an associated function that needs to be used as
    /// `RefMut::map(...)`. A method would interfere with methods of the same
    /// name on the contents of a `FairlyUnsafeCell` used through `Deref`.
    ///
    /// # Examples
    ///
    /// ```
    /// use fairly_unsafe_cell::*;
    ///
    /// let c = FairlyUnsafeCell::new((5, 'b'));
    /// {
    ///     let b1: RefMut<'_, (u32, char)> = unsafe { c.borrow_mut() };
    ///     let mut b2: RefMut<'_, u32> = RefMut::map(b1, |t| &mut t.0);
    ///     assert_eq!(*b2, 5);
    ///     *b2 = 42;
    /// }
    /// assert_eq!(unsafe { *c.borrow() }, (42, 'b'));
    /// ```
    #[inline]
    pub fn map<U: ?Sized, F>(orig: RefMut<'b, T>, f: F) -> RefMut<'b, U>
    where
        F: FnOnce(&mut T) -> &mut U,
    {
        RefMut(core::cell::RefMut::map(orig.0, f))
    }

    // /// Makes a new `RefMut` for an optional component of the borrowed data. The
    // /// original guard is returned as an `Err(..)` if the closure returns
    // /// `None`.
    // ///
    // /// The `FairlyUnsafeCell` is already mutably borrowed, so this cannot fail.
    // ///
    // /// This is an associated function that needs to be used as
    // /// `RefMut::filter_map(...)`. A method would interfere with methods of the
    // /// same name on the contents of a `FairlyUnsafeCell` used through `Deref`.
    // ///
    // /// # Examples
    // ///
    // /// ```
    // /// use fairly_unsafe_cell::*;
    // ///
    // /// let c = FairlyUnsafeCell::new(vec![1, 2, 3]);
    // ///
    // /// {
    // ///     let b1: RefMut<'_, Vec<u32>> = unsafe { c.borrow_mut() };
    // ///     let mut b2: Result<RefMut<'_, u32>, _> = RefMut::filter_map(b1, |v| v.get_mut(1));
    // ///
    // ///     if let Ok(mut b2) = b2 {
    // ///         *b2 += 2;
    // ///     }
    // /// }
    // ///
    // /// assert_eq!(* unsafe { c.borrow() }, vec![1, 4, 3]);
    // /// ```
    // #[inline]
    // pub fn filter_map<U: ?Sized, F>(orig: RefMut<'b, T>, f: F) -> Result<RefMut<'b, U>, Self>
    // where
    //     F: FnOnce(&mut T) -> Option<&mut U>,
    // {
    //     match core::cell::RefMut::filter_map(orig.0, f) {
    //         Ok(yay) => Ok(RefMut(yay)),
    //         Err(nay) => Err(RefMut(nay)),
    //     }
    // }

    /// Splits a `RefMut` into multiple `RefMut`s for different components of the
    /// borrowed data.
    ///
    /// The underlying `FairlyUnsafeCell` will remain mutably borrowed until both
    /// returned `RefMut`s go out of scope.
    ///
    /// The `FairlyUnsafeCell` is already mutably borrowed, so this cannot fail.
    ///
    /// This is an associated function that needs to be used as
    /// `RefMut::map_split(...)`. A method would interfere with methods of the
    /// same name on the contents of a `FairlyUnsafeCell` used through `Deref`.
    ///
    /// # Examples
    ///
    /// ```
    /// use fairly_unsafe_cell::*;
    ///
    /// let cell = FairlyUnsafeCell::new([1, 2, 3, 4]);
    /// let borrow = unsafe { cell.borrow_mut() };
    /// let (mut begin, mut end) = RefMut::map_split(borrow, |slice| slice.split_at_mut(2));
    /// assert_eq!(*begin, [1, 2]);
    /// assert_eq!(*end, [3, 4]);
    /// begin.copy_from_slice(&[4, 3]);
    /// end.copy_from_slice(&[2, 1]);
    /// ```
    #[inline]
    pub fn map_split<U: ?Sized, V: ?Sized, F>(
        orig: RefMut<'b, T>,
        f: F,
    ) -> (RefMut<'b, U>, RefMut<'b, V>)
    where
        F: FnOnce(&mut T) -> (&mut U, &mut V),
    {
        let (a, b) = core::cell::RefMut::map_split(orig.0, f);
        (RefMut(a), RefMut(b))
    }
}

impl<T: ?Sized> Deref for RefMut<'_, T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &T {
        self.0.deref()
    }
}

impl<T: ?Sized> DerefMut for RefMut<'_, T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut T {
        self.0.deref_mut()
    }
}

impl<T: ?Sized + fmt::Display> fmt::Display for RefMut<'_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}