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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
use crate::teardown::{Deferred, Teardown};
use std::time::{Duration, Instant};
use crate::compat::{Arc, Ordering};
use crate::ready::LaneSignal;
use super::{
LaneKey, PARK_SPINS, SendError, SendTimeoutError, Shared, TryRegisterError, TrySendError,
};
/// Sending half.
///
/// A `Sender` owns exactly one SPSC ring producer. It is `Send` when `T` is
/// `Send`, but it is not `Sync`. Sender registration has no configured limit.
#[derive(Debug)]
pub struct Sender<T, P: Teardown = Deferred> {
pub(super) shared: Arc<Shared<T, P>>,
pub(super) producer: crate::ring::Producer<T, P>,
pub(super) key: LaneKey,
pub(super) signal: Arc<LaneSignal>,
}
impl<T, P: Teardown> Sender<T, P> {
/// Try to register another sender.
///
/// Returns `None` when the receiver is gone.
#[must_use]
pub fn try_clone(&self) -> Option<Self> {
self.try_register().ok()
}
/// Try to register another sender and report why registration failed.
///
/// Prefer this over [`try_clone`](Self::try_clone) when the caller needs to
/// distinguish a closed receiver from successful registration.
///
/// # Errors
///
/// Returns [`TryRegisterError::Disconnected`] when the receiver is gone.
pub fn try_register(&self) -> Result<Self, TryRegisterError> {
let (key, signal, producer) = self.shared.register_sender()?;
Ok(Self {
shared: self.shared.clone(),
producer,
key,
signal,
})
}
/// Try to send one value.
///
/// A successful send is immediately visible to the receiver. Internally,
/// the value is pushed into this sender's SPSC ring and flushed.
/// Consumed slots remain occupied until the receiver releases them. Use
/// [`Receiver::release_consumed`](super::Receiver::release_consumed) or
/// [`Receiver::recv_batch_into`](super::Receiver::recv_batch_into) when
/// capacity must be reusable before processing received values.
///
/// # Errors
///
/// Returns [`TrySendError::Full`] when this sender's lane is full, or
/// [`TrySendError::Disconnected`] when the receiver is gone.
#[inline]
pub fn try_send(&mut self, value: T) -> Result<(), TrySendError<T>> {
let (result, wake_receiver) = self.try_send_inner(value);
if wake_receiver {
self.shared.data_waiter.notify();
}
result
}
#[inline]
fn try_send_inner(&mut self, value: T) -> (Result<(), TrySendError<T>>, bool) {
if !self.shared.receiver_alive.load(Ordering::Acquire) {
return (Err(TrySendError::Disconnected(value)), false);
}
match self.producer.push_and_flush(value) {
Ok(()) => {
let wake_receiver = self.shared.mark_ready(&self.signal);
(Ok(()), wake_receiver)
}
Err(value) => {
if !self.shared.receiver_alive.load(Ordering::Acquire)
|| self.producer.is_consumer_dropped()
{
(Err(TrySendError::Disconnected(value)), false)
} else {
(Err(TrySendError::Full(value)), false)
}
}
}
}
/// Send one value, blocking while this sender's ring is full.
///
/// # Errors
///
/// Returns [`SendError`] with the unsent value when the receiver disconnects.
#[inline]
pub fn send(&mut self, value: T) -> Result<(), SendError<T>> {
match self.try_send(value) {
Ok(()) => Ok(()),
Err(TrySendError::Disconnected(value)) => Err(SendError(value)),
Err(TrySendError::Full(value)) => self.send_slow(value),
}
}
#[cold]
#[inline(never)]
fn send_slow(&mut self, mut value: T) -> Result<(), SendError<T>> {
for _ in 0..PARK_SPINS {
std::hint::spin_loop();
match self.try_send(value) {
Ok(()) => return Ok(()),
Err(TrySendError::Disconnected(value)) => return Err(SendError(value)),
Err(TrySendError::Full(returned)) => value = returned,
}
}
loop {
match self.try_send(value) {
Ok(()) => return Ok(()),
Err(TrySendError::Disconnected(value)) => return Err(SendError(value)),
Err(TrySendError::Full(returned)) => value = returned,
}
let signal = self.signal.clone();
let wait = signal.prepare_space_wait();
let (result, wake_receiver) = self.try_send_inner(value);
match result {
Ok(()) => {
wait.cancel();
if wake_receiver {
self.shared.data_waiter.notify();
}
return Ok(());
}
Err(TrySendError::Disconnected(value)) => {
wait.cancel();
return Err(SendError(value));
}
Err(TrySendError::Full(returned)) => value = returned,
}
wait.wait();
}
}
/// Send one value, blocking for at most `timeout` while this sender's ring
/// is full.
///
/// # Errors
///
/// Returns [`SendTimeoutError::Timeout`] with the unsent value when the
/// timeout expires, or [`SendTimeoutError::Disconnected`] when the receiver
/// disconnects.
pub fn send_timeout(&mut self, value: T, timeout: Duration) -> Result<(), SendTimeoutError<T>> {
let Some(deadline) = Instant::now().checked_add(timeout) else {
return self
.send(value)
.map_err(|SendError(value)| SendTimeoutError::Disconnected(value));
};
self.send_deadline(value, deadline)
}
/// Send one value, blocking until `deadline` while this sender's ring is
/// full.
///
/// # Errors
///
/// Returns [`SendTimeoutError::Timeout`] with the unsent value at the
/// deadline, or [`SendTimeoutError::Disconnected`] when the receiver
/// disconnects.
pub fn send_deadline(
&mut self,
mut value: T,
deadline: Instant,
) -> Result<(), SendTimeoutError<T>> {
loop {
match self.try_send(value) {
Ok(()) => return Ok(()),
Err(TrySendError::Disconnected(value)) => {
return Err(SendTimeoutError::Disconnected(value));
}
Err(TrySendError::Full(returned)) => value = returned,
}
let signal = self.signal.clone();
let wait = signal.prepare_space_wait();
let (result, wake_receiver) = self.try_send_inner(value);
match result {
Ok(()) => {
wait.cancel();
if wake_receiver {
self.shared.data_waiter.notify();
}
return Ok(());
}
Err(TrySendError::Disconnected(value)) => {
wait.cancel();
return Err(SendTimeoutError::Disconnected(value));
}
Err(TrySendError::Full(returned)) => value = returned,
}
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
wait.cancel();
return Err(SendTimeoutError::Timeout(value));
}
if wait.wait_timeout(remaining) {
match self.try_send(value) {
Ok(()) => return Ok(()),
Err(TrySendError::Disconnected(value)) => {
return Err(SendTimeoutError::Disconnected(value));
}
Err(TrySendError::Full(value)) => {
return Err(SendTimeoutError::Timeout(value));
}
}
}
}
}
/// Return this sender's current lane slot.
#[inline]
#[must_use]
pub const fn lane_id(&self) -> usize {
self.key.slot
}
/// Return this sender's lane capacity after `yring` rounding.
#[inline]
#[must_use]
pub fn capacity(&self) -> usize {
self.producer.capacity()
}
/// Return whether the receiver has been dropped.
#[inline]
#[must_use]
pub fn is_disconnected(&self) -> bool {
!self.shared.receiver_alive.load(Ordering::Acquire)
}
/// Return a snapshot of the number of live senders.
#[inline]
#[must_use]
pub fn sender_count(&self) -> usize {
self.shared.live_senders.load(Ordering::Relaxed)
}
/// Return a snapshot of the number of live receivers.
#[inline]
#[must_use]
pub fn receiver_count(&self) -> usize {
usize::from(self.shared.receiver_alive.load(Ordering::Relaxed))
}
/// Return whether both senders belong to the same channel.
#[inline]
#[must_use]
pub fn same_channel(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.shared, &other.shared)
}
}
impl<T, P: Teardown> Drop for Sender<T, P> {
fn drop(&mut self) {
self.producer.close();
let _ = self.shared.mark_ready(&self.signal);
self.shared.live_senders.fetch_sub(1, Ordering::AcqRel);
self.shared.data_waiter.notify();
}
}