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
//
// Copyright 2023, Colias Group, LLC
//
// SPDX-License-Identifier: BSD-2-Clause
//

#![no_std]

use core::cell::UnsafeCell;

// NOTE(rustc_wishlist) use SyncUnsafeCell once #![feature(sync_unsafe_cell)] stabilizes
#[repr(transparent)]
pub struct ImmutableCell<T: ?Sized> {
    value: UnsafeCell<T>,
}

unsafe impl<T> Sync for ImmutableCell<T> {}

impl<T: Default> Default for ImmutableCell<T> {
    fn default() -> Self {
        Self::new(Default::default())
    }
}

impl<T> From<T> for ImmutableCell<T> {
    fn from(t: T) -> Self {
        Self::new(t)
    }
}

impl<T> ImmutableCell<T> {
    pub const fn new(value: T) -> Self {
        Self {
            value: UnsafeCell::new(value),
        }
    }
}

impl<T: ?Sized> ImmutableCell<T> {
    pub fn get(&self) -> &T {
        unsafe { self.value.get().as_ref().unwrap() }
    }
}