compression_core/unshared.rs
1#![allow(dead_code)] // unused without any features
2
3use core::fmt::{self, Debug};
4
5/// Wraps a type and only allows unique borrowing.
6///
7/// The main use case is to wrap a `!Sync` type and implement `Sync` for it as this type blocks
8/// having multiple shared references to the inner value.
9///
10/// # Safety
11///
12/// We must be careful when accessing `inner`, there must be no way to create a shared reference to
13/// it from a shared reference to an `Unshared`, as that would allow creating shared references on
14/// multiple threads.
15///
16/// As an example deriving or implementing `Clone` is impossible, two threads could attempt to
17/// clone a shared `Unshared<T>` reference which would result in accessing the same inner value
18/// concurrently.
19pub struct Unshared<T> {
20 inner: T,
21}
22
23impl<T> From<T> for Unshared<T> {
24 fn from(inner: T) -> Self {
25 Unshared { inner }
26 }
27}
28
29impl<T> Unshared<T> {
30 /// Constructs a new `Unshared` from `inner`.
31 pub fn new(inner: T) -> Self {
32 Self::from(inner)
33 }
34
35 /// Returns a unique reference to the inner `T`.
36 pub fn get_mut(&mut self) -> &mut T {
37 &mut self.inner
38 }
39}
40
41/// Safety: See comments on main docs for `Unshared`
42unsafe impl<T> Sync for Unshared<T> {}
43
44impl<T> Debug for Unshared<T> {
45 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46 f.debug_struct(core::any::type_name::<T>()).finish()
47 }
48}