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
use futures::{Stream, Poll, Async};

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


pub type LeftFork<S, F> = Fork<S, F>;
pub type RightFork<S, F> = Fork<S, F>;



/// Fork given stream into two stream. Please have a look at document of `StreamExt` trait.
pub fn fork<S, F, T>(stream: S, router: F) -> (LeftFork<S, F>, RightFork<S, F>)
where
    S: Stream,
    F: FnMut(&S::Item) -> T,
    Side: From<T>,
{
    let shared = Shared {
        router: router,
        stream: stream,
    };

    let shared = Arc::new(Mutex::new(shared));

    let queues = Arc::new(Mutex::new(Queues::new()));

    let left = Fork {
        route: Side::Left,
        shared: shared.clone(),
        queues: queues.clone(),
    };

    let right = Fork {
        route: Side::Right,
        shared: shared,
        queues: queues.clone(),
    };

    (left, right)
}


#[derive(Clone, Debug)]
pub enum Side {
    Left,
    Right,
}

impl From<bool> for Side {
    fn from(b: bool) -> Side {
        if b { Side::Left } else { Side::Right }
    }
}


#[derive(Debug, Clone)]
struct Queues<T, E> {
    left: VecDeque<Result<Option<T>, E>>,
    right: VecDeque<Result<Option<T>, E>>,
}


impl<T, E> Queues<T, E> {
    fn new() -> Queues<T, E> {
        Queues {
            left: VecDeque::new(),
            right: VecDeque::new(),
        }
    }

    fn get_queue_mut(&mut self, route: Side) -> &mut VecDeque<Result<Option<T>, E>> {
        match route {
            Side::Left => &mut self.left,
            Side::Right => &mut self.right,
        }
    }

    fn push_none(&mut self) {
        self.left.push_back(Ok(None));
        self.right.push_back(Ok(None));
    }

    fn push_err(&mut self, err: E)
    where
        E: Clone,
    {
        self.left.push_back(Err(err.clone()));
        self.right.push_back(Err(err));
    }
}


#[derive(Debug)]
struct Shared<S: Stream, F> {
    router: F,
    stream: S,
}



/// Fork any kind of stream into two stream like that the river branches.
/// The closure being passed this function is called "router". Each item of original stream is
/// passed to branch following to "router" decision.
/// "Router" can return not only `Side` which is `Left` or `Right` but also
/// `bool` (`true` is considered as `Left`).
///
/// # Examples
///
/// ```
/// # extern crate futures;
/// # extern crate ex_futures;
/// use ex_futures::StreamExt;
///
/// # fn main() {
/// let (tx, rx) = ::futures::sync::mpsc::channel::<usize>(42);
///
/// let (even, odd) = rx.unsync_fork(|i| i % 2 == 0);
/// # }
/// ```
///
/// # Notice
///
/// The value being returned by this function is not `Sync`. We will provide `Sync` version later.
pub struct Fork<S: Stream, F> {
    route: Side,
    queues: Arc<Mutex<Queues<S::Item, S::Error>>>,
    shared: Arc<Mutex<Shared<S, F>>>,
}


impl<S, F, T> Stream for Fork<S, F>
where
    S: Stream,
    S::Error: Clone,
    F: FnMut(&S::Item) -> T,
    T: Into<Side>,
{
    type Item = S::Item;
    type Error = S::Error;

    fn poll(&mut self) -> Poll<Option<S::Item>, S::Error> {

        // Check self queue
        match self.queues
            .lock()
            .unwrap()
            .get_queue_mut(self.route.clone())
            .pop_front() {
            Some(Ok(Some(msg))) => return Ok(Async::Ready(Some(msg))),
            Some(Ok(None)) => return Ok(Async::Ready(None)),
            Some(Err(e)) => return Err(e),
            None => {
                // Since queue is empty, we need to call poll at original future.
            }
        };

        match self.shared.try_lock() {
            Err(TryLockError::WouldBlock) => {
                // Loop again
            }
            Err(TryLockError::Poisoned(_poisoned)) => {
                // Currently we just panic thread if mutex get poisoned.
                panic!("Other thread seemd to panic during processing cloned stream.");
            }
            Ok(mut shared) => {
                // Now we got shared value.

                match shared.stream.poll() {
                    Err(e) => self.queues.lock().unwrap().push_err(e),
                    Ok(Async::Ready(Some(msg))) => {
                        let route = (&mut shared.router)(&msg).into();
                        self.queues.lock().unwrap().get_queue_mut(route).push_back(
                            Ok(
                                Some(msg),
                            ),
                        );
                    }
                    Ok(Async::Ready(None)) => self.queues.lock().unwrap().push_none(),
                    Ok(Async::NotReady) => {
                        return Ok(Async::NotReady);
                    }
                }
            }
        }

        // Loop if
        // - queue is empty and could not get shared
        // - queue is empty and get shared and new item is arrived
        self.poll()
    }
}



impl<S: Stream, F> ::std::fmt::Debug for Fork<S, F> {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> {
        match self.route {
            Side::Left => write!(f, "LeftRoute"),
            Side::Right => write!(f, "RightRoute"),
        }
    }
}