-
Notifications
You must be signed in to change notification settings - Fork 32
/
future.rs
212 lines (201 loc) · 7.76 KB
/
future.rs
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
use std::{
future::Future,
mem::{needs_drop, MaybeUninit},
pin::Pin,
task::Poll,
};
use crate::{
internal::{acquire_internal, Internal},
signal::AsyncSignal,
state, ReceiveError, SendError,
};
use pin_project_lite::pin_project;
#[repr(u8)]
#[derive(PartialEq, Clone, Copy)]
pub(crate) enum FutureState {
Zero,
Waiting,
Done,
}
impl FutureState {
#[inline(always)]
fn is_waiting(&self) -> bool {
*self == FutureState::Waiting
}
#[inline(always)]
fn is_done(&self) -> bool {
*self == FutureState::Done
}
}
pin_project! {
/// Send future to send an object to the channel asynchronously
/// It must be polled to perform send action
#[must_use = "futures do nothing unless you .await or poll them"]
pub struct SendFuture<'a, T> {
pub(crate) state: FutureState,
pub(crate) internal: &'a Internal<T>,
#[pin]
pub(crate) sig: AsyncSignal<T>,
pub(crate) data: MaybeUninit<T>,
}
impl<'a,T> PinnedDrop for SendFuture<'a,T> {
fn drop(mut this: Pin<&mut Self>) {
if !this.state.is_done() && this.state.is_waiting() {
let mut internal = acquire_internal(this.internal);
if !internal.cancel_send_signal(this.sig.as_signal()){
// a receiver got signal ownership, should wait until the response
this.sig.wait_indefinitely();
}else if needs_drop::<T>(){
unsafe{this.data.assume_init_drop()};
}
}
}
}
}
impl<'a, T> Future for SendFuture<'a, T> {
type Output = Result<(), SendError>;
#[inline(always)]
fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
let mut this = self.project();
match *this.state {
FutureState::Zero => {
let mut internal = acquire_internal(this.internal);
if internal.send_count == 0 {
*this.state = FutureState::Done;
return Poll::Ready(Err(SendError::Closed));
}
if let Some(first) = internal.next_recv() {
drop(internal);
unsafe { first.send(std::ptr::read(this.data.as_mut_ptr())) }
*this.state = FutureState::Done;
Poll::Ready(Ok(()))
} else if internal.queue.len() < internal.capacity {
internal
.queue
.push_back(unsafe { std::ptr::read(this.data.as_mut_ptr()) });
drop(internal);
*this.state = FutureState::Done;
Poll::Ready(Ok(()))
} else {
if internal.recv_count == 0 {
*this.state = FutureState::Done;
return Poll::Ready(Err(SendError::ReceiveClosed));
}
*this.state = FutureState::Waiting;
this.sig.set_ptr(this.data.as_mut_ptr());
this.sig.register(cx.waker());
// send directly to the waitlist
internal.push_send(this.sig.as_signal());
drop(internal);
Poll::Pending
}
}
FutureState::Waiting => {
let r = this.sig.poll(cx);
match r {
Poll::Ready(v) => {
*this.state = FutureState::Done;
if v == state::UNLOCKED {
return Poll::Ready(Ok(()));
}
Poll::Ready(Err(SendError::Closed))
}
Poll::Pending => Poll::Pending,
}
}
_ => {
panic!("polled after result is already returned")
}
}
}
}
pin_project! {
/// Receive future to receive an object from the channel asynchronously
/// It must be polled to perform receive action
#[must_use = "futures do nothing unless you .await or poll them"]
pub struct ReceiveFuture<'a, T> {
pub(crate) state: FutureState,
pub(crate) internal: &'a Internal<T>,
#[pin]
pub(crate) sig: AsyncSignal<T>,
pub(crate) data: MaybeUninit<T>,
}
impl<'a,T> PinnedDrop for ReceiveFuture<'a,T> {
fn drop(mut this: Pin<&mut Self>) {
if !this.state.is_done() && this.state.is_waiting() {
let mut internal = acquire_internal(this.internal);
if !internal.cancel_recv_signal(this.sig.as_signal()){
// someone got signal ownership, should wait until the response
this.sig.wait_indefinitely();
// got ownership of data that is not going to be used ever again, so drop it
if needs_drop::<T>(){
unsafe { std::ptr::drop_in_place(this.data.as_mut_ptr()) }
}
}
}
}
}
}
impl<'a, T> Future for ReceiveFuture<'a, T> {
type Output = Result<T, ReceiveError>;
#[inline(always)]
fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
let mut this = self.project();
match this.state {
FutureState::Zero => {
let mut internal = acquire_internal(this.internal);
if internal.recv_count == 0 {
*this.state = FutureState::Done;
return Poll::Ready(Err(ReceiveError::Closed));
}
if let Some(v) = internal.queue.pop_front() {
if let Some(p) = internal.next_send() {
// if there is a sender take its data and push it into the queue
unsafe { internal.queue.push_back(p.recv()) }
}
drop(internal);
*this.state = FutureState::Done;
Poll::Ready(Ok(v))
} else if let Some(p) = internal.next_send() {
drop(internal);
*this.state = FutureState::Done;
unsafe { Poll::Ready(Ok(p.recv())) }
} else {
if internal.send_count == 0 {
*this.state = FutureState::Done;
return Poll::Ready(Err(ReceiveError::SendClosed));
}
*this.state = FutureState::Waiting;
this.sig.set_ptr(this.data.as_mut_ptr());
this.sig.register(cx.waker());
// no active waiter so push to the queue
internal.push_recv(this.sig.as_signal());
drop(internal);
Poll::Pending
}
}
FutureState::Waiting => {
let r = this.sig.poll(cx);
match r {
Poll::Ready(v) => {
*this.state = FutureState::Done;
if v == state::UNLOCKED {
if std::mem::size_of::<T>() == 0 {
return Poll::Ready(Ok(unsafe { std::mem::zeroed() }));
} else {
return Poll::Ready(Ok(unsafe {
std::ptr::read(this.data.as_mut_ptr())
}));
}
}
Poll::Ready(Err(ReceiveError::Closed))
}
Poll::Pending => Poll::Pending,
}
}
_ => {
panic!("polled after result is already returned")
}
}
}
}