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
#![cfg_attr(not(feature = "std"), no_std)]
#![doc = include_str!("../README.md")]

#[cfg(test)]
mod tests;

mod cell;
use cell::*;
pub use cell::{map_ref, map_ref_mut, SinglytonRef, SinglytonRefMut};

#[cfg(debug_assertions)]
use core::cell::UnsafeCell;
use core::mem::MaybeUninit;

/// A **thread-unsafe** global singleton.
///
/// Using this across threads is undefined behaviour.
///
/// # Panics
///
/// In debug builds, usage of this abstraction is checked for safety at runtime.
///
/// * Using this struct across threads will panic.
/// * Mixing mutabilty of borrows will panic (this is bypassed if you are using the pointer getters)
pub struct Singleton<T>(SinglytonCell<T>);
unsafe impl<T> Sync for Singleton<T> {}

impl<T> Singleton<T> {
	pub const fn new(val: T) -> Self {
		Self(SinglytonCell::new(val))
	}

	/// Acquires an **immutable reference** to the singleton.
	///
	/// In debug builds, this will panic if the singleton is mutably accessed from a different thread or if a mutable reference is currently held.
	pub fn get(&'static self) -> SinglytonRef<T> {
		self.0.get()
	}

	/// Acquires a **mutable reference** to the singleton.
	///
	/// In debug builds, this will panic if the singleton is mutably accessed from a different thread or an existing mutable or immutable reference is currently held.
	pub fn get_mut(&'static self) -> SinglytonRefMut<T> {
		self.0.get_mut()
	}

	/// Acquires an **immutable pointer** to the singleton.
	///
	/// In debug builds, this will panic if the singleton is mutably accessed from a different thread or if a mutable reference is currently held.
	///
	/// This is unsafe because the returned pointer bypasses any future borrow checking.
	pub unsafe fn as_ptr(&'static self) -> *const T {
		&*self.0.get() as *const T
	}

	/// Acquires a **mutable pointer** to the singleton.
	///
	/// In debug builds, this will panic if the singleton is mutably accessed from a different thread or an existing mutable or immutable reference is currently held.
	///
	/// This is unsafe because the returned pointer bypasses any future borrow checking.
	pub unsafe fn as_mut_ptr(&'static self) -> *mut T {
		&mut *self.0.get_mut() as *mut T
	}

	/// Replaces the value in the singleton with anew.
	///
	/// In debug builds, this will panic if the singleton is mutably accessed from a different thread or an existing mutable or immutable reference is currently held.
	pub fn replace(&'static self, val: T) {
		*self.0.get_mut() = val;
	}
}

/// A **thread-unsafe** global singleton which is initially uninitialized memory.
///
/// Using this across threads is undefined behaviour.
///
/// # Panics
///
/// In debug builds, usage of this abstraction is checked for safety at runtime.
///
/// * Using this struct across threads will panic.
/// * Mixing mutabilty of borrows will panic (this is bypassed if you are using the pointer getters)
/// * Using this struct before initializing it will panic.
/// * Initializing the value more than once will panic. Use `replace`
pub struct SingletonUninit<T> {
	inner: SinglytonCell<MaybeUninit<T>>,

	#[cfg(debug_assertions)]
	initialized: UnsafeCell<bool>
}
unsafe impl<T> Sync for SingletonUninit<T> {}

impl<T> SingletonUninit<T> {
	pub const fn uninit() -> Self {
		Self {
			inner: SinglytonCell::new(MaybeUninit::uninit()),

			#[cfg(debug_assertions)]
			initialized: UnsafeCell::new(false)
		}
	}

	pub const fn new(val: T) -> Self {
		Self {
			inner: SinglytonCell::new(MaybeUninit::new(val)),

			#[cfg(debug_assertions)]
			initialized: UnsafeCell::new(true)
		}
	}

	#[cfg(debug_assertions)]
	fn uninit_check(&'static self) {
		if !unsafe { *self.initialized.get() } {
			panic!("This SingletonUninit has not been initialized yet");
		}
	}

	#[cfg(not(debug_assertions))]
	fn uninit_check(&'static self) {}

	/// Assumes the memory is **initialized** and acquires an **immutable reference** to the singleton.
	///
	/// In debug builds, this will panic if the memory is not initialized, the singleton is mutably accessed from a different thread, or a mutable reference is currently held.
	pub fn get(&'static self) -> SinglytonRef<T> {
		self.uninit_check();
		map_ref(self.inner.get(), |maybe_uninit| unsafe {
			maybe_uninit.assume_init_ref()
		})
	}

	/// Acquires a **mutable reference** to the singleton.
	///
	/// In debug builds, this will panic if the memory is not initialized, the singleton is mutably accessed from a different thread, or an existing mutable or immutable reference is currently held.
	pub fn get_mut(&'static self) -> SinglytonRefMut<T> {
		self.uninit_check();
		map_ref_mut(self.inner.get_mut(), |maybe_uninit| unsafe {
			maybe_uninit.assume_init_mut()
		})
	}

	/// Acquires an **immutable pointer** to the singleton.
	///
	/// In debug builds, this will panic if the memory is not initialized, the singleton is mutably accessed from a different thread, or a mutable reference is currently held.
	///
	/// This is unsafe because the returned pointer bypasses any future borrow checking.
	pub fn as_ptr(&'static self) -> *const T {
		self.uninit_check();
		self.inner.get_mut().as_ptr()
	}

	/// Acquires a **mutable pointer** to the singleton.
	///
	/// In debug builds, this will panic if the memory is not initialized, the singleton is mutably accessed from a different thread, or an existing mutable or immutable reference is currently held.
	///
	/// This is unsafe because the returned pointer bypasses any future borrow checking.
	pub fn as_mut_ptr(&'static self) -> *mut T {
		self.uninit_check();
		self.inner.get_mut().as_mut_ptr()
	}

	/// Replaces the value in the singleton with anew.
	///
	/// In debug builds, this will panic if the memory is not initialized, the singleton is mutably accessed from a different thread, or an existing mutable or immutable reference is currently held.
	pub fn replace(&'static self, val: T) {
		self.uninit_check();
		unsafe {
			#[cfg(debug_assertions)]
			let mut maybe_uninit = self.inner.get_mut();

			#[cfg(not(debug_assertions))]
			let maybe_uninit = self.inner.get_mut();

			core::ptr::drop_in_place(maybe_uninit.as_mut_ptr());
			maybe_uninit.write(val);
		}
	}

	#[cfg(debug_assertions)]
	/// Initializes the memory in the singleton.
	///
	/// In debug builds, this will panic if the memory is **already initialized**, the singleton is mutably accessed from a different thread, or an existing mutable or immutable reference is currently held.
	pub fn init(&'static self, val: T) {
		unsafe {
			let ref mut initialized = *self.initialized.get();
			if *initialized {
				panic!("This SingletonUninit has already been initialized");
			}

			self.inner.get_mut().write(val);

			*initialized = true;
		}
	}

	#[cfg(not(debug_assertions))]
	/// Initializes the memory in the singleton.
	///
	/// In debug builds, this will panic if the memory is **already initialized**, the singleton is mutably accessed from a different thread, or an existing mutable or immutable reference is currently held.
	pub fn init(&'static self, val: T) {
		self.inner.get_mut().write(val);
	}
}

/// A **thread-unsafe** global singleton containg an `Option<T>`.
///
/// All operations (except `as_option` and `as_option_mut`) automatically unwrap and assume the `Option<T>` is `Some(T)` and will panic otherwise.
///
/// Using this across threads is undefined behaviour.
///
/// # Panics
///
/// In debug builds, usage of this abstraction is checked for safety at runtime.
///
/// * Using this struct across threads will panic.
/// * Mixing mutabilty of borrows will panic (this is bypassed if you are using the pointer getters)
pub struct SingletonOption<T>(SinglytonCell<Option<T>>);
unsafe impl<T> Sync for SingletonOption<T> {}

impl<T> SingletonOption<T> {
	pub const fn new() -> Self {
		Self(SinglytonCell::new(None))
	}

	pub const fn new_some(val: T) -> Self {
		Self(SinglytonCell::new(Some(val)))
	}

	/// Acquires an **immutable reference** to the inner `Option<T>`.
	///
	/// In debug builds, this will panic if the singleton is mutably accessed from a different thread or if a mutable reference is currently held.
	pub fn as_option(&'static self) -> SinglytonRef<Option<T>> {
		self.0.get()
	}

	/// Acquires a **mutable reference** to the inner `Option<T>`.
	///
	/// In debug builds, this will panic if the singleton is mutably accessed from a different thread or an existing mutable or immutable reference is currently held.
	pub fn as_option_mut(&'static self) -> SinglytonRefMut<Option<T>> {
		self.0.get_mut()
	}

	/// Acquires an **immutable reference** to the singleton.
	///
	/// Panics if the singleton is `None`.
	///
	/// In debug builds, this will panic if the singleton is mutably accessed from a different thread or if a mutable reference is currently held.
	pub fn get(&'static self) -> SinglytonRef<T> {
		map_ref(self.0.get(), |opt| opt.as_ref().unwrap())
	}

	/// Acquires a **mutable reference** to the singleton.
	///
	/// Panics if the singleton is `None`.
	///
	/// In debug builds, this will panic if the singleton is mutably accessed from a different thread or an existing mutable or immutable reference is currently held.
	pub fn get_mut(&'static self) -> SinglytonRefMut<T> {
		map_ref_mut(self.0.get_mut(), |opt| opt.as_mut().unwrap())
	}

	/// Replaces the value in the singleton with anew.
	///
	/// In debug builds, this will panic if the singleton is mutably accessed from a different thread or an existing mutable or immutable reference is currently held.
	pub fn replace(&'static self, val: T) {
		self.0.get_mut().replace(val);
	}

	/// Takes the value out of the singleton.
	///
	/// In debug builds, this will panic if the singleton is mutably accessed from a different thread or an existing mutable or immutable reference is currently held.
	pub fn take(&'static self) -> Option<T> {
		self.0.get_mut().take()
	}

	/// Tests if the singleton is `Some(T)`.
	///
	/// In debug builds, this will panic if the singleton is mutably accessed from a different thread or if a mutable reference is currently held.
	pub fn is_some(&'static self) -> bool {
		self.0.get().is_some()
	}

	/// Tests if the singleton is `None`.
	///
	/// In debug builds, this will panic if the singleton is mutably accessed from a different thread or if a mutable reference is currently held.
	pub fn is_none(&'static self) -> bool {
		self.0.get().is_none()
	}
}