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
use core::{
cell::Cell,
fmt::{self, Debug, Formatter},
future::Future,
marker::PhantomData,
ops::{Deref, DerefMut},
pin::Pin,
ptr::NonNull,
task::{Context, Poll},
};
use futures_core::{FusedFuture, FusedStream, Stream};
#[cfg(debug_assertions)]
pub use maybe_cell::checked::{Maybe, MaybeCopy};
#[cfg(not(debug_assertions))]
pub use maybe_cell::unchecked::{Maybe, MaybeCopy};
#[repr(transparent)]
pub struct BoxPtr<T: ?Sized>(NonNull<T>, PhantomData<Cell<T>>);
impl<T: ?Sized> BoxPtr<T> {
#[inline]
pub fn new(value: Box<T>) -> Self {
unsafe { Self::new_unchecked(Box::into_raw(value)) }
}
#[inline]
pub unsafe fn new_unchecked(ptr: *mut T) -> Self {
debug_assert!(!ptr.is_null());
Self(NonNull::new_unchecked(ptr), PhantomData)
}
pub fn into_box(self) -> Box<T> {
unsafe { Box::from_raw(self.0.as_ptr()) }
}
}
impl<T> Clone for BoxPtr<T> {
fn clone(&self) -> Self {
Self(self.0, PhantomData)
}
}
impl<T> Copy for BoxPtr<T> {}
impl<T> Deref for BoxPtr<T> {
type Target = T;
#[inline]
fn deref(&self) -> &Self::Target {
unsafe { self.0.as_ref() }
}
}
impl<T> DerefMut for BoxPtr<T> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { self.0.as_mut() }
}
}
impl<T: Debug> Debug for BoxPtr<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_tuple("BoxPtr").field(&self.0).finish()
}
}
pub trait StreamNext: Stream + Unpin {
fn next(&mut self) -> NextFuture<'_, Self> {
NextFuture(Some(self))
}
}
impl<S: Stream + Unpin + ?Sized> StreamNext for S {}
#[derive(Debug)]
pub struct NextFuture<'n, S: ?Sized>(Option<&'n mut S>);
impl<S: Unpin + ?Sized> Unpin for NextFuture<'_, S> {}
impl<S: Stream + Unpin + ?Sized> Future for NextFuture<'_, S> {
type Output = Option<S::Item>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let slf = Pin::get_mut(self);
if let Some(stream) = slf.0.as_mut() {
let result = Pin::new(stream).poll_next(cx);
if result.is_ready() {
slf.0.take();
}
result
} else {
Poll::Ready(None)
}
}
}
impl<S> FusedFuture for NextFuture<'_, S>
where
S: Stream + FusedStream + Unpin,
{
fn is_terminated(&self) -> bool {
if let Some(slf) = self.0.as_ref() {
slf.is_terminated()
} else {
true
}
}
}