futures_util/stream/
forward.rs

1use futures_core::{Async, Future, Poll, Stream};
2use futures_core::task;
3use futures_sink::{Sink};
4
5use stream::{StreamExt, Fuse};
6
7/// Future for the `Stream::forward` combinator, which sends a stream of values
8/// to a sink and then waits until the sink has fully flushed those values.
9#[derive(Debug)]
10#[must_use = "futures do nothing unless polled"]
11pub struct Forward<T: Stream, U> {
12    sink: Option<U>,
13    stream: Option<Fuse<T>>,
14    buffered: Option<T::Item>,
15}
16
17
18pub fn new<T, U>(stream: T, sink: U) -> Forward<T, U>
19    where U: Sink<SinkItem=T::Item>,
20          T: Stream,
21          T::Error: From<U::SinkError>,
22{
23    Forward {
24        sink: Some(sink),
25        stream: Some(stream.fuse()),
26        buffered: None,
27    }
28}
29
30impl<T, U> Forward<T, U>
31    where U: Sink<SinkItem=T::Item>,
32          T: Stream,
33          T::Error: From<U::SinkError>,
34{
35    /// Get a shared reference to the inner sink.
36    /// If this combinator has already been polled to completion, None will be returned.
37    pub fn sink_ref(&self) -> Option<&U> {
38        self.sink.as_ref()
39    }
40
41    /// Get a mutable reference to the inner sink.
42    /// If this combinator has already been polled to completion, None will be returned.
43    pub fn sink_mut(&mut self) -> Option<&mut U> {
44        self.sink.as_mut()
45    }
46
47    /// Get a shared reference to the inner stream.
48    /// If this combinator has already been polled to completion, None will be returned.
49    pub fn stream_ref(&self) -> Option<&T> {
50        self.stream.as_ref().map(|x| x.get_ref())
51    }
52
53    /// Get a mutable reference to the inner stream.
54    /// If this combinator has already been polled to completion, None will be returned.
55    pub fn stream_mut(&mut self) -> Option<&mut T> {
56        self.stream.as_mut().map(|x| x.get_mut())
57    }
58
59    fn take_result(&mut self) -> (T, U) {
60        let sink = self.sink.take()
61            .expect("Attempted to poll Forward after completion");
62        let fuse = self.stream.take()
63            .expect("Attempted to poll Forward after completion");
64        (fuse.into_inner(), sink)
65    }
66
67    fn try_start_send(&mut self, cx: &mut task::Context, item: T::Item) -> Poll<(), U::SinkError> {
68        debug_assert!(self.buffered.is_none());
69        {
70            let sink_mut = self.sink_mut().take().expect("Attempted to poll Forward after completion");
71            if let Async::Ready(()) = sink_mut.poll_ready(cx)? {
72                sink_mut.start_send(item)?;
73                return Ok(Async::Ready(()))
74            }
75        }
76        self.buffered = Some(item);
77        Ok(Async::Pending)
78    }
79}
80
81impl<T, U> Future for Forward<T, U>
82    where U: Sink<SinkItem=T::Item>,
83          T: Stream,
84          T::Error: From<U::SinkError>,
85{
86    type Item = (T, U);
87    type Error = T::Error;
88
89    fn poll(&mut self, cx: &mut task::Context) -> Poll<(T, U), T::Error> {
90        // If we've got an item buffered already, we need to write it to the
91        // sink before we can do anything else
92        if let Some(item) = self.buffered.take() {
93            try_ready!(self.try_start_send(cx, item))
94        }
95
96        loop {
97            match self.stream_mut()
98                .take().expect("Attempted to poll Forward after completion")
99                .poll_next(cx)?
100            {
101                Async::Ready(Some(item)) => try_ready!(self.try_start_send(cx, item)),
102                Async::Ready(None) => {
103                    try_ready!(self.sink_mut().take().expect("Attempted to poll Forward after completion").poll_flush(cx));
104                    return Ok(Async::Ready(self.take_result()))
105                }
106                Async::Pending => {
107                    try_ready!(self.sink_mut().take().expect("Attempted to poll Forward after completion").poll_flush(cx));
108                    return Ok(Async::Pending)
109                }
110            }
111        }
112    }
113}