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
use super::{Inner, COMPLETE, OPTION_BITS, RX_WAKER_STORED};
use crate::sync::spsc::{SpscInner, SpscInnerErr};
use alloc::sync::Arc;
use core::{
fmt,
sync::atomic::Ordering,
task::{Context, Poll},
};
const IS_TX_HALF: bool = true;
pub struct Sender<E> {
inner: Arc<Inner<E>>,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum SendError {
Canceled,
Overflow,
}
impl<E> Sender<E> {
pub(super) fn new(inner: Arc<Inner<E>>) -> Self {
Self { inner }
}
#[inline]
pub fn send(&mut self, pulses: usize) -> Result<(), SendError> {
self.inner.send(pulses)
}
#[inline]
pub fn send_err(self, err: E) -> Result<(), E> {
self.inner.send_err(err)
}
#[inline]
pub fn poll_canceled(&mut self, cx: &mut Context<'_>) -> Poll<()> {
self.inner.poll_half(
cx,
IS_TX_HALF,
Ordering::Relaxed,
Ordering::Release,
Inner::take_cancel,
)
}
#[inline]
pub fn is_canceled(&self) -> bool {
self.inner.is_canceled(Ordering::Relaxed)
}
}
impl<E> Drop for Sender<E> {
#[inline]
fn drop(&mut self) {
self.inner.close_half(IS_TX_HALF);
}
}
impl<E> Inner<E> {
fn send(&self, pulses: usize) -> Result<(), SendError> {
let state = self.state_load(Ordering::Acquire);
self.transaction(state, Ordering::Acquire, Ordering::Acquire, |state| {
if *state & COMPLETE != 0 {
return Err(SendError::Canceled);
}
let pulses = pulses.checked_shl(OPTION_BITS).ok_or(SendError::Overflow)?;
*state = state.checked_add(pulses).ok_or(SendError::Overflow)?;
Ok(*state)
})
.map(|state| {
if state & RX_WAKER_STORED != 0 {
unsafe { (*self.rx_waker.get()).assume_init_ref().wake_by_ref() };
}
})
}
}
impl fmt::Display for SendError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SendError::Canceled => write!(f, "Receiver is dropped."),
SendError::Overflow => write!(f, "Channel buffer overflow."),
}
}
}