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
use std::sync::mpsc::{channel, Sender, Receiver, RecvError};

/// `Funnel` maintains a collection of
/// [Receiver](https://doc.rust-lang.org/std/sync/mpsc/struct.Receiver.html)s
/// which it collects messages from to output to a single source.
#[derive(Debug)]
pub struct Funnel<T> {
    sources: Vec<Receiver<T>>,
    next_index: usize
}

impl<T> Funnel<T> {
    /// Creates a new `Funnel` that received messages of type `T` with no input sources.
    pub fn new() -> Funnel<T> {
        Funnel {
            sources: Vec::new(),
            next_index: 0
        }
    }

    /// Adds a new input source to the `Funnel`, which it takes ownership over.
    pub fn push(&mut self, receiver: Receiver<T>) {
        self.sources.push(receiver);
    }

    /// Obtains the number of input sources that are being read from.
    pub fn len(&self) -> usize {
        self.sources.len()
    }

    /// Removes a specific input source at a given `index`.
    ///
    /// This method is useful in situations where the owner of the `Funnel` is
    /// keeping track of the indexes of `Receiver`s. It is also useful for
    /// removing `Receiver`s that can no longer be read from, indicated by any
    /// errors returned by a call to `recv()`.
    pub fn remove(&mut self, index: usize) -> Receiver<T> {
        self.sources.remove(index)
    }

    /// Creates a new channel, whose `Receiver` will be managed by the funnel.
    pub fn add_receiver(&mut self) -> Sender<T> {
        let (tx, rx) = channel();
        self.push(rx);
        tx
    }

    /// Attempts to wait for a value on the oldest `Receiver` not already received from.
    ///
    /// Successive calls to `recv()` result in calls to the `recv()` method of successive
    /// `Receiver`s managed by the funnel. In doing so, channels are read from in an even
    /// distribution. As soon as a value is successfully received, it will be returned as
    /// the first element of the tuple returned. `recv()` will accumulate a
    /// [Vec](https://doc.rust-lang.org/std/vec/struct.Vec.html) containing any
    /// [RecvError](https://doc.rust-lang.org/std/sync/mpsc/struct.RecvError.html)s that
    /// may have occurred trying to read from `Receiver`s, as well as the index of those
    /// `Receiver`s, allowing users to `remove()` them if desired.
    ///
    /// # Examples
    /// ```
    /// use self::funnel::Funnel;
    /// use std::thread;
    ///
    /// let mut fun = Funnel::new();
    /// let writer1 = fun.add_receiver();
    /// let writer2 = fun.add_receiver();

    /// thread::spawn(move || {
    ///     let _ = writer1.send(32).unwrap();
    /// });
    /// thread::spawn(move || {
    ///     let _ = writer2.send(64).unwrap();
    /// });

    /// assert!(match fun.recv() {
    ///     (Some(read_value), errors) => read_value == 32 && errors.len() == 0,
    ///     _ => false,
    /// });
    /// assert!(match fun.recv() {
    ///     (Some(read_value), errors) => read_value == 64 && errors.len() == 0,
    ///     _ => false,
    /// });
    /// ```
    pub fn recv(&mut self) -> (Option<T>, Vec<(RecvError, usize)>) {
        let mut errors: Vec<(RecvError, usize)> = Vec::new();
        let mut index: usize = self.next_index;
        loop {
            match self.sources[index].recv() {
                Err(e)    => errors.push((e, index)),
                Ok(value) => {
                    self.next_index = index + 1 % self.sources.len();
                    return (Some(value), errors);
                },
            };
            index = (index + 1) % self.sources.len();
            if index == self.next_index - 1 {
                break;
            }
        }
        (None, errors)
    }
}

#[cfg(test)]
mod tests {
    use super::Funnel;
    use std::sync::mpsc::channel;

    #[test]
    fn single_read() {
        let mut funnel = Funnel::new();
        let (tx, rx) = channel();
        funnel.push(rx);
        let _ = tx.send(1).unwrap();
        let (received, errors) = funnel.recv();
        assert!(received.is_some());
        assert!(match received {
            Some(value) => value == 1,
            _ => false,
        });
        assert_eq!(errors.len(), 0);
    }

    #[test]
    fn multiple_read() {
        let mut funnel: Funnel<i32> = Funnel::new();
        let writer1 = funnel.add_receiver();
        let writer2 = funnel.add_receiver();
        let _ = writer1.send(1).unwrap();
        let _ = writer2.send(2).unwrap();

        let (received, errors) = funnel.recv();
        assert!(received.is_some());
        println!("{:?}", received);
        assert!(match received {
            Some(value) => value == 1,
            _ => false,
        });
        assert_eq!(errors.len(), 0);

        let (received, errors) = funnel.recv();
        assert!(received.is_some());
        println!("{:?}", errors);
        assert!(match received {
            Some(value) => value == 2,
            _ => false,
        });
        assert_eq!(errors.len(), 0);
    }
}