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
277
278
279
280
281
282
//! Async broadcast channels

//!

//! # Examples

//!

//! ```

//! // tbi

//! ```


#![forbid(unsafe_code, future_incompatible, rust_2018_idioms)]
#![deny(missing_debug_implementations, nonstandard_style)]
#![warn(missing_docs, missing_doc_code_examples, unreachable_pub)]

use std::collections::VecDeque;
use std::error;
use std::fmt;
use std::sync::{Arc, Mutex};

/// Create a new broadcast channel.

pub fn broadcast<T>(cap: usize) -> (Sender<T>, Receiver<T>) {
    let inner = Arc::new(Mutex::new(Inner {
        queue: VecDeque::with_capacity(cap),
        receiver_count: 1,
        send_count: 0,
    }));
    let s = Sender {
        inner: inner.clone(),
        capacity: cap,
    };
    let r = Receiver {
        inner: inner,
        capacity: cap,
        recv_count: 0,
    };
    (s, r)
}

#[derive(Debug)]
struct Inner<T> {
    queue: VecDeque<(T, usize)>,
    receiver_count: usize,
    send_count: usize,
}

// The sending side of a channel.

#[derive(Debug, Clone)]
pub struct Sender<T> {
    inner: Arc<Mutex<Inner<T>>>,
    capacity: usize,
}

impl<T> Sender<T> {
    pub fn capacity(&self) -> usize {
        self.capacity
    }
}

impl<T: Clone> Sender<T> {
    pub async fn broadcast(&self, msg: T) -> Result<(), SendError<T>> {
        todo!();
    }

    pub fn try_broadcast(&self, msg: T) -> Result<(), TrySendError<T>> {
        let mut inner = self.inner.lock().unwrap();
        if inner.queue.len() == self.capacity {
            return Err(TrySendError::Full(msg));
        }
        let receiver_count = inner.receiver_count;
        inner.queue.push_back((msg, receiver_count));
        inner.send_count += 1;
        Ok(())
    }
}

/// The receiving side of a channel.

#[derive(Debug)]
pub struct Receiver<T> {
    inner: Arc<Mutex<Inner<T>>>,
    capacity: usize,
    recv_count: usize,
}

impl<T: Clone> Receiver<T> {
    pub async fn recv(&self) -> Result<T, RecvError> {
        todo!();
    }

    pub fn try_recv(&mut self) -> Result<T, TryRecvError> {
        let mut inner = self.inner.lock().unwrap();
        let msg_count = inner.send_count - self.recv_count;
        if msg_count == 0 {
            return Err(TryRecvError::Empty);
        }
        let len = dbg!(inner.queue.len());
        let msg = inner.queue[len - msg_count].0.clone();
        inner.queue[len - msg_count].1 -= 1;
        if dbg!(inner.queue[len - msg_count].1) == 0 {
            inner.queue.pop_front();
        }
        self.recv_count += 1;
        Ok(msg)
    }
}

impl<T> Drop for Receiver<T> {
    fn drop(&mut self) {
        let mut inner = self.inner.lock().unwrap();
        let msg_count = dbg!(inner.send_count) - dbg!(self.recv_count);
        let len = inner.queue.len();

        for i in dbg!(len) - dbg!(msg_count)..len {
            inner.queue[i].1 -= 1;
        }
        while let Some((_, 0)) = inner.queue.front() {
            inner.queue.pop_front();
        }
        inner.receiver_count -= 1;
    }
}

impl<T> Clone for Receiver<T> {
    fn clone(&self) -> Self {
        let mut inner = self.inner.lock().unwrap();
        inner.receiver_count += 1;
        Receiver {
            inner: self.inner.clone(),
            capacity: self.capacity,
            recv_count: inner.send_count,
        }
    }
}

/// An error returned from [`Sender::send()`].

///

/// Received because the channel is closed.

#[derive(PartialEq, Eq, Clone, Copy)]
pub struct SendError<T>(pub T);

impl<T> SendError<T> {
    /// Unwraps the message that couldn't be sent.

    pub fn into_inner(self) -> T {
        self.0
    }
}

impl<T> error::Error for SendError<T> {}

impl<T> fmt::Debug for SendError<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "SendError(..)")
    }
}

impl<T> fmt::Display for SendError<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "sending into a closed channel")
    }
}

/// An error returned from [`Sender::try_send()`].

#[derive(PartialEq, Eq, Clone, Copy)]
pub enum TrySendError<T> {
    /// The channel is full but not closed.

    Full(T),

    /// The channel is closed.

    Closed(T),
}

impl<T> TrySendError<T> {
    /// Unwraps the message that couldn't be sent.

    pub fn into_inner(self) -> T {
        match self {
            TrySendError::Full(t) => t,
            TrySendError::Closed(t) => t,
        }
    }

    /// Returns `true` if the channel is full but not closed.

    pub fn is_full(&self) -> bool {
        match self {
            TrySendError::Full(_) => true,
            TrySendError::Closed(_) => false,
        }
    }

    /// Returns `true` if the channel is closed.

    pub fn is_closed(&self) -> bool {
        match self {
            TrySendError::Full(_) => false,
            TrySendError::Closed(_) => true,
        }
    }
}

impl<T> error::Error for TrySendError<T> {}

impl<T> fmt::Debug for TrySendError<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            TrySendError::Full(..) => write!(f, "Full(..)"),
            TrySendError::Closed(..) => write!(f, "Closed(..)"),
        }
    }
}

impl<T> fmt::Display for TrySendError<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            TrySendError::Full(..) => write!(f, "sending into a full channel"),
            TrySendError::Closed(..) => write!(f, "sending into a closed channel"),
        }
    }
}

/// An error returned from [`Receiver::recv()`].

///

/// Received because the channel is empty and closed.

#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub struct RecvError;

impl error::Error for RecvError {}

impl fmt::Display for RecvError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "receiving from an empty and closed channel")
    }
}

/// An error returned from [`Receiver::try_recv()`].

#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub enum TryRecvError {
    /// The channel is empty but not closed.

    Empty,

    /// The channel is empty and closed.

    Closed,
}

impl TryRecvError {
    /// Returns `true` if the channel is empty but not closed.

    pub fn is_empty(&self) -> bool {
        match self {
            TryRecvError::Empty => true,
            TryRecvError::Closed => false,
        }
    }

    /// Returns `true` if the channel is empty and closed.

    pub fn is_closed(&self) -> bool {
        match self {
            TryRecvError::Empty => false,
            TryRecvError::Closed => true,
        }
    }
}

impl error::Error for TryRecvError {}

impl fmt::Display for TryRecvError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            TryRecvError::Empty => write!(f, "receiving from an empty channel"),
            TryRecvError::Closed => write!(f, "receiving from an empty and closed channel"),
        }
    }
}

#[test]
fn smoke() {
    let (s, mut r1) = broadcast(10);
    let mut r2 = r1.clone();

    s.try_broadcast(7).unwrap();
    assert_eq!(r1.try_recv().unwrap(), 7);
    assert_eq!(r2.try_recv().unwrap(), 7);

    let mut r3 = r1.clone();
    s.try_broadcast(8).unwrap();
    assert_eq!(r1.try_recv().unwrap(), 8);
    assert_eq!(r2.try_recv().unwrap(), 8);
    assert_eq!(r3.try_recv().unwrap(), 8);
}