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
#![doc(html_root_url = "https://docs.rs/singleton-trait/0.1.2")]
#![no_std]


use core::cell::{Cell, UnsafeCell};
use core::marker::PhantomData;
use core::mem::ManuallyDrop;

/*******************/
/* Singleton trait */
/*******************/

/**
 * This trait denotes a type which has at most one logical identity at all times.
 * This is sufficient to make borrowing decisions based only on the type, without
 * regards to value identity.
 *
 * Implementers of the trait must uphold this contract, that any point
 * during the execution of the program, there is at most one accessible
 * logical value of this type. Much like how re-borrowings can
 * make a type inaccessible, it is allowed for there to be more than one
 * such binding, if the others are inaccessible due to unique borrowing.
 *
 * Some examples would include:
 * * A type with exactly one instance constructed during the main method
 * * A type with only one static instance (including one wrapped behind e.g. a Mutex)
 * * An uninhabited type
 * * A type which is constructed with a unique lifetime brand
 *
 * Any type which has a public constructor cannot meet this,
 * Some non-examples include ZSTs like ()
 * and the Exists<T> struct in this crate (when T is not a Singleton itself)
 * Any type which implements Clone
 */
pub unsafe trait Singleton {}

/*****************/
/* Blanket Impls */
/*****************/

// Anything which is backed by at least one T
// can be given an implementation
//
// This can be witnessed by a function
// S -> T where T is a singleton

// SAFETY:
// These types are all backed by exactly one, unique T
unsafe impl<T: Singleton> Singleton for Cell<T> {}
unsafe impl<T: Singleton> Singleton for UnsafeCell<T> {}
unsafe impl<T: Singleton> Singleton for [T; 1] {}
// SAFETY:
// 1. Every mutable reference points to a value of T
// 2. No two mutable references alias
// 3. By the contract of Singleton for T, there is at most one logical value of T
unsafe impl<'a, T: Singleton> Singleton for &'a mut T {}
// SAFETY:
// Exists<T> witnesses strict ownership of a value of type T
unsafe impl<'a, T: Singleton> Singleton for Erased<T> {}

/*********************/
// Phantom existence //
/*********************/

/**
 * The Exists struct witnesses the logical ownership of a value of type T
 * while remaining zero-sized. This can be used for ghost proofs of soundness.
 *
 * Erased<T> should be thought of a zero-sized owner of T.
 *
 * NOTE: drop implementations will never be called, as Exists<T> guarantees the existence
 * of a valid T, which might not be true if they were called. On the other hand, since
 * it does not hold a T, it cannot drop T when it is itself dropped
 *
 * Secondly, keep in mind that while Exists<T> serves as evidence, it does not include
 * sufficient providence for either Stacked Borrows or LLVM, and so it is not sound
 * in general to recover a reference from an `Exists<&T>` and `*mut T` or `&UnsafeCell<T>`
 * even when T is Singleton, but this could be possible if T is zero-sized.
 */
#[derive(Clone, Copy)]
pub struct Erased<T> {
    _phantom: PhantomData<ManuallyDrop<T>>,
}
impl<T> Erased<T> {
    #[inline(always)]
    pub const fn new(t: T) -> Self {
        let _ = ManuallyDrop::new(t);
        // SAFETY: we have taken ownership of a T value above
        unsafe { Self::new_unchecked() }
    }

    /**
     * This function constructs a value of Erased<T> without taking logical ownership of a T.
     *
     * # Safety
     *
     * Constructing this asserts that there is a value of type T which has been leaked, or
     * in which it is guaranteed that the program behaves the same up to observation as if a
     * zero-sized copy of T were being passed.
     *
     */
    #[inline(always)]
    pub const unsafe fn new_unchecked() -> Self {
        Erased {
            _phantom: PhantomData,
        }
    }

    pub fn borrow(&self) -> Erased<&T> {
        // Safety:
        // the identity function is pure
        unsafe { self.map_borrow(|r| r) }
    }

    pub fn borrow_mut(&mut self) -> Erased<&mut T> {
        // Safety:
        // the identity function is pure
        unsafe { self.map_borrow_mut(|r| r) }
    }

    /**
     * Maps a function on the inside of the Erased body (existential induction).
     *
     * # Safety
     *
     * Due to the strictness guarantees, the passed closure must not cause any visible
     * side effects, including side effects caused by owning R
     */
    #[inline(always)]
    pub unsafe fn map<R, F: FnOnce(T) -> R>(self, _: impl Exists<F>) -> Erased<R> {
        // Safety:
        //
        // By the contract for the passed function, this is equivalent to calling it on the value of type T
        Erased::<R>::new_unchecked()
    }

    /**
     * Maps a function on the borrow of the Erased field (existential induction).
     *
     * # Safety
     *
     * Due to the strictness guarantees, the passed closure must not cause any visible
     * side effects, including side effects caused by owning R
     */
    #[inline(always)]
    pub unsafe fn map_borrow<'a, R, F: FnOnce(&'a T) -> R>(
        &'a self,
        _: impl Exists<F>,
    ) -> Erased<R> {
        // Safety:
        //
        // By the contract for the passed function, this is equivalent to calling it on the borrow of T
        Erased::<R>::new_unchecked()
    }
    /**
     * Maps a function on the mutable borrow of the Erased field.
     *
     * # Safety
     *
     * Due to the strictness guarantees, the passed closure must not cause any visible
     * side effects, including side effects caused by owning R
     */
    #[inline(always)]
    pub unsafe fn map_borrow_mut<'a, R, F: FnOnce(&'a mut T) -> R>(
        &'a mut self,
        _: impl Exists<F>,
    ) -> Erased<R> {
        // Safety:
        //
        // By the contract for the passed function, this is equivalent to calling it on the mutable borrow of T
        Erased::<R>::new_unchecked()
    }
}
impl<T> Erased<Erased<T>> {
    /**
     * An erased erased value can be flattened into a single erasure,
     * since Erased<T> is notionally equivalent to T
     */
    pub fn flatten(self) -> Erased<T> {
        // SAFETY:
        //
        // By existential induction since the constructor for Erased is pure
        unsafe { Erased::<T>::new_unchecked() }
    }
}
impl<'a, T> Erased<&'a mut T> {
    pub fn reborrow<'b>(&'b mut self) -> Erased<&'b mut T> {
        // SAFETY
        //
        // Refs and derefs on reference types are pure
        unsafe { self.map_borrow_mut(|r: &'b mut &'a mut T| &mut **r) }
    }
}
impl<T> From<T> for Erased<T> {
    fn from(t: T) -> Self {
        Self::new(t)
    }
}
/**
 * The Exists trait is intended to be used with `impl`, to denote
 * an argument where the existence of a value is sufficient as an argument
 */
pub trait Exists<T>: Into<Erased<T>> {}
impl<T: Into<Erased<T>>> Exists<T> for T {}