You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

258 lines
5.6 KiB

//! Sync utils
use super::*;
use std::{
ptr::NonNull,
sync::atomic::{AtomicBool, Ordering},
};
use std::ops::Drop;
use crossbeam_utils::atomic::AtomicCell;
struct InitData<T>
{
data: AtomicCell<Option<T>>,
drop: AtomicBool,
}
#[derive(Debug)]
struct InitInner<T>
{
boxed: NonNull<InitData<T>>,
}
impl<T> InitInner<T>
{
#[inline] pub fn new() -> Self
{
let from = Box::new(InitData {
data: AtomicCell::new(None),
drop: false.into(),
});
Self {
boxed: unsafe{NonNull::new_unchecked(Box::into_raw(from))},
}
}
}
impl<T> Clone for InitInner<T>
{
fn clone(&self) -> Self {
Self {
boxed: unsafe{NonNull::new_unchecked(self.boxed.as_ptr())}
}
}
}
impl<T> InitInner<T>
{
#[inline(always)] fn should_drop(&self) -> &AtomicBool
{
&unsafe {&*self.boxed.as_ptr()}.drop
}
#[inline(always)] fn data_ref(&self) -> &InitData<T>
{
unsafe{&*self.boxed.as_ptr()}
}
}
unsafe impl<T> Send for InitInner<T>{}
unsafe impl<T> Sync for InitInner<T>{}
impl<T> Drop for InitInner<T>
{
fn drop(&mut self) {
if let Err(true) = self.should_drop().compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) {
unsafe {
drop(Box::from_raw(self.boxed.as_ptr()))
}
}
}
}
#[derive(Debug)]
pub struct InitHalf<T>(InitInner<T>);
#[derive(Debug)]
pub struct UninitHalf<T>(InitInner<T>);
impl<T> InitHalf<T>
{
/// Set the value
pub fn set(&mut self, value: T)
{
self.0.data_ref().data.store(Some(value));
}
/// Set the value, returning the previous one if it was set
pub fn swap(&mut self, value: T) -> Option<T>
{
self.0.data_ref().data.swap(Some(value))
}
}
impl<T> UninitHalf<T>
{
/// Take the initialised value
///
/// # Panics
/// If the value hasn't yet been initialised.
pub fn take(&mut self) -> T
{
self.0.data_ref().data.take().unwrap()
}
/// Take the value if it is set, if not, returns `None`.
pub fn try_take(&mut self) -> Option<T>
{
self.0.data_ref().data.take()
}
}
/// Create a pair of atomic initialser-receivers.
pub fn shared_uninit<T>() -> (InitHalf<T>, UninitHalf<T>)
{
let inner = InitInner::<T>::new();
(InitHalf(inner.clone()),
UninitHalf(inner))
}
/*
/// Type to allow for a seperate thread or task to initialise a value.
#[derive(Debug)]
pub struct SharedUninit<T>(oneshot::Receiver<T>);
/// Type to initialise a value for a `SharedUninit`.
#[derive(Debug)]
pub struct SharedInitialiser<T>(oneshot::Sender<T>);
impl<'a, T> SharedUninit<T>
where T: 'a
{
/// Create an uninit/initialiser pair.
pub fn pair() -> (SharedInitialiser<T>, Self)
{
let (tx, rx) = oneshot::channel();
(SharedInitialiser(tx), Self(rx))
}
/// Try to receive the initialised value.
///
/// Returns `None` if the initialiser was dropped before setting a value.
#[inline] pub fn try_get(self) -> impl Future<Output = Option<T>> + 'a
{
self.0.map(|x| x.ok())
}
/// Receive the initialised value.
///
/// # Panics
/// If the initialiser was dropped without setting a value.
#[inline] pub fn get(self) -> impl Future<Output = T> + 'a
{
self.try_get().map(|x| x.unwrap())
}
}
impl<'a, T> SharedInitialiser<T>
where T: 'a
{
/// Set the value for the `SharedUninit`.
#[inline] pub fn init(self, value: T)
{
let _ = self.0.send(value);
}
}
*/
// This was a failure. Just use `tokio::sync::oneshot`...
/*
#[derive(Debug)]
struct SharedInitialiser<T>
{
data: Arc<(UnsafeCell<MaybeUninit<T>>, AtomicBool)>,
}
impl<T> Clone for SharedInitialiser<T>
{
#[inline] fn clone(&self) -> Self {
Self { data: Arc::clone(&self.data) }
}
}
#[derive(Debug)]
pub struct SharedInitRx<T>(SharedInitialiser<T>);
/// Permits initialising across a thread.
// Do we even need this? No.. We can just use `tokio::sync::oneshot`....
#[derive(Debug)]
pub struct SharedInitTx<T>(SharedInitialiser<T>);
impl<T> SharedInitTx<T>
{
/// Consume this instance and initialise it.
///
/// # Panics
/// If there is already a value set (this should never happen).
pub fn initialise(self, value: T)
{
todo!()
}
}
impl<T> SharedInitRx<T>
{
/// Create a sender and receiver pair
pub fn pair() -> (SharedInitTx<T>, Self)
{
let this = Self::new();
(this.create_tx(), this)
}
/// Create a new, uninitialised receiver.
#[inline] fn new() -> Self
{
Self(SharedInitialiser{data: Arc::new((UnsafeCell::new(MaybeUninit::uninit()), false.into()))})
}
/// Create an initialiser
///
/// # Panics (debug)
/// If an initialiser already exists
#[inline] fn create_tx(&self) -> SharedInitTx<T>
{
debug_assert_eq!(Arc::strong_count(&self.0.data), 1, "Sender already exists");
SharedInitTx(self.0.clone())
}
/// Checks if there is a value present, or if it is possible for a value to be present.
pub fn is_pending(&self) -> bool
{
todo!("Either self.0.data.1 == true, OR, strong_count() == 2")
}
/// Has a value already been set
pub fn has_value(&self) -> bool
{
todo!("self.0.data.1 == true")
}
/// Try to consume into the initialised value.
pub fn try_into_value(self) -> Result<T, Self>
{
todo!()
}
/// Consume into the initialised value
///
/// # Panics
/// If the value hasn't been initialised
#[inline] pub fn into_value(self) -> T
{
self.try_into_value().map_err(|_| "No initialised value present").unwrap()
}
/// Does this receiver have an initialser that hasn't yet produced a value?
pub fn has_initialiser(&self) -> bool
{
Arc::strong_count(&self.0.data) == 2
}
}
*/