use core::convert::Infallible;
use core::mem::MaybeUninit;
use core::pin::Pin;
#[cfg(doc)]
use {
crate::new,
alloc::{boxed::Box, rc::Rc, sync::Arc},
};
mod copy_new;
mod factories;
mod move_new;
mod impls;
pub use copy_new::*;
pub use factories::*;
pub use move_new::*;
#[must_use = "`New`s do nothing until emplaced into storage"]
pub unsafe trait New: Sized {
type Output;
unsafe fn new(self, this: Pin<&mut MaybeUninit<Self::Output>>);
fn with<F>(self, post: F) -> With<Self, F>
where
F: FnOnce(Pin<&mut Self::Output>),
{
With(self, post)
}
}
#[must_use = "`New`s do nothing until emplaced into storage"]
pub unsafe trait TryNew: Sized {
type Output;
type Error;
unsafe fn try_new(
self,
this: Pin<&mut MaybeUninit<Self::Output>>,
) -> Result<(), Self::Error>;
fn with<F>(self, post: F) -> TryWith<Self, F> {
TryWith(self, post)
}
}
unsafe impl<N: New> TryNew for N {
type Output = N::Output;
type Error = Infallible;
unsafe fn try_new(
self,
this: Pin<&mut MaybeUninit<Self::Output>>,
) -> Result<(), Self::Error> {
self.new(this);
Ok(())
}
}
pub trait EmplaceUnpinned<T>: Sized {
fn emplace<N: New<Output = T>>(n: N) -> Self {
match Self::try_emplace(n) {
Ok(x) => x,
Err(e) => match e {},
}
}
fn try_emplace<N: TryNew<Output = T>>(n: N) -> Result<Self, N::Error>;
}
pub trait Emplace<T>: Sized
where
Pin<Self>: EmplaceUnpinned<T>,
{
fn emplace<N: New<Output = T>>(n: N) -> Pin<Self> {
Pin::<Self>::emplace(n)
}
fn try_emplace<N: TryNew<Output = T>>(n: N) -> Result<Pin<Self>, N::Error> {
Pin::<Self>::try_emplace(n)
}
}
impl<T, P> Emplace<T> for P where Pin<P>: EmplaceUnpinned<T> {}
#[doc(hidden)]
pub struct With<N, F>(N, F);
unsafe impl<N: New, F> New for With<N, F>
where
F: FnOnce(Pin<&mut N::Output>),
{
type Output = N::Output;
#[inline]
unsafe fn new(self, mut this: Pin<&mut MaybeUninit<Self::Output>>) {
self.0.new(this.as_mut());
let this = this.map_unchecked_mut(|x| x.assume_init_mut());
(self.1)(this)
}
}
#[doc(hidden)]
pub struct TryWith<N, F>(N, F);
unsafe impl<N: TryNew, F> TryNew for TryWith<N, F>
where
F: FnOnce(Pin<&mut N::Output>) -> Result<(), N::Error>,
{
type Output = N::Output;
type Error = N::Error;
#[inline]
unsafe fn try_new(
self,
mut this: Pin<&mut MaybeUninit<Self::Output>>,
) -> Result<(), Self::Error> {
self.0.try_new(this.as_mut())?;
let this = this.map_unchecked_mut(|x| x.assume_init_mut());
(self.1)(this)
}
}
pub trait Swap<Rhs = Self> {
fn swap_with(self: Pin<&mut Self>, src: Pin<&mut Rhs>);
}