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

/// `FunnelError` contains information about errors that can occur using a `Funnel`.
///
/// In particular, it contains information about `recv()`ing from particular `Receiver`s
/// as well as the error which occurs if a user attempts to `recv()` from a funnel which
/// has not had any `Receiver`s added to it.
#[derive(Debug)]
pub enum FunnelError {
    RecvError(RecvError),
    NoSourcesError,
}

impl fmt::Display for FunnelError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            FunnelError::RecvError(ref contained) => contained.fmt(f),
            FunnelError::NoSourcesError           => write!(f, "Funnel has no input sources."),
        }
    }
}

impl Error for FunnelError {
    fn description(&self) -> &str {
        match *self {
            FunnelError::RecvError(ref contained) => contained.description(),
            FunnelError::NoSourcesError           => "Cannot read from a funnel before adding receivers.",
        }
    }

    fn cause(&self) -> Option<&Error> {
        match *self {
            FunnelError::RecvError(ref contained) => Some(contained),
            FunnelError::NoSourcesError           => None,
        }
    }
}

/// `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 errors 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. Note that the returned
    /// error type is `FunnelError`, which may take on the `NoSourcesError` variant. In such
    /// cases, the index accompanying the error will be 0, however this error is returned to
    /// signify that the length of the sources container is 0 and thus `remove()`ing index 0
    /// would cause an error.
    ///
    /// # 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<(FunnelError, usize)>) {
        let mut errors: Vec<(FunnelError, usize)> = Vec::new();
        let mut index: usize = self.next_index;
        if self.sources.len() == 0 {
            errors.push((FunnelError::NoSourcesError, 0));
            return (None, errors);
        }
        loop {
            match self.sources[index].recv() {
                Err(e)    => errors.push((FunnelError::RecvError(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 {
                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);
    }
}