use alloc::alloc::Layout;
use alloc::boxed::Box;
use core::fmt;
use core::future::Future;
use core::mem::ManuallyDrop;
use core::pin::Pin;
use core::ptr::{self, NonNull};
use core::task::{Context, Poll};
pub struct ReusableLocalBoxFuture<T> {
boxed: NonNull<dyn Future<Output = T>>,
}
impl<T> ReusableLocalBoxFuture<T> {
pub fn new<F>(future: F) -> Self
where
F: Future<Output = T> + 'static,
{
let boxed: Box<dyn Future<Output = T>> = Box::new(future);
let boxed = Box::into_raw(boxed);
let boxed = unsafe { NonNull::new_unchecked(boxed) };
Self { boxed }
}
pub fn set<F>(&mut self, future: F)
where
F: Future<Output = T> + 'static,
{
if let Err(future) = self.try_set(future) {
*self = Self::new(future);
}
}
pub fn try_set<F>(&mut self, future: F) -> Result<(), F>
where
F: Future<Output = T> + 'static,
{
let self_layout = {
let dyn_future: &(dyn Future<Output = T>) = unsafe { self.boxed.as_ref() };
Layout::for_value(dyn_future)
};
if Layout::new::<F>() == self_layout {
unsafe {
self.set_same_layout(future);
}
Ok(())
} else {
Err(future)
}
}
unsafe fn set_same_layout<F>(&mut self, future: F)
where
F: Future<Output = T> + 'static,
{
struct SetLayout<'a, F, T>
where
F: Future<Output = T> + 'static,
{
rbf: &'a mut ReusableLocalBoxFuture<T>,
new_future: ManuallyDrop<F>,
}
impl<'a, F, T> Drop for SetLayout<'a, F, T>
where
F: Future<Output = T> + 'static,
{
fn drop(&mut self) {
unsafe {
let fut_ptr: *mut F = self.rbf.boxed.as_ptr() as *mut F;
ptr::write(fut_ptr, ManuallyDrop::take(&mut self.new_future));
self.rbf.boxed = NonNull::new_unchecked(fut_ptr);
}
}
}
let set_layout = SetLayout {
rbf: self,
new_future: ManuallyDrop::new(future),
};
ptr::drop_in_place(set_layout.rbf.boxed.as_ptr());
}
pub fn get_pin(&mut self) -> Pin<&mut (dyn Future<Output = T>)> {
unsafe { Pin::new_unchecked(self.boxed.as_mut()) }
}
pub fn poll(&mut self, cx: &mut Context<'_>) -> Poll<T> {
self.get_pin().poll(cx)
}
}
impl<T> Future for ReusableLocalBoxFuture<T> {
type Output = T;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
Pin::into_inner(self).get_pin().poll(cx)
}
}
impl<T> Unpin for ReusableLocalBoxFuture<T> {}
impl<T> Drop for ReusableLocalBoxFuture<T> {
fn drop(&mut self) {
unsafe {
drop(Box::from_raw(self.boxed.as_ptr()));
}
}
}
impl<T> fmt::Debug for ReusableLocalBoxFuture<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ReusableLocalBoxFuture").finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
use static_assertions::{assert_impl_all, assert_not_impl_all};
#[test]
fn static_assertion() {
assert_impl_all!(ReusableLocalBoxFuture<()>: Unpin);
assert_not_impl_all!(ReusableLocalBoxFuture<()>: Sync, Send);
}
}