futures_util/sink/
send.rs

1use futures_core::{Poll, Async, Future};
2use futures_core::task;
3use futures_sink::{Sink};
4
5/// Future for the `Sink::send` combinator, which sends a value to a sink and
6/// then waits until the sink has fully flushed.
7#[derive(Debug)]
8#[must_use = "futures do nothing unless polled"]
9pub struct Send<S: Sink> {
10    sink: Option<S>,
11    item: Option<S::SinkItem>,
12}
13
14pub fn new<S: Sink>(sink: S, item: S::SinkItem) -> Send<S> {
15    Send {
16        sink: Some(sink),
17        item: Some(item),
18    }
19}
20
21impl<S: Sink> Send<S> {
22    /// Get a shared reference to the inner sink.
23    ///
24    /// Returns `None` if the future has completed already.
25    pub fn get_ref(&self) -> Option<&S> {
26        self.sink.as_ref()
27    }
28
29    /// Get a mutable reference to the inner sink.
30    ///
31    /// Returns `None` if the future has completed already.
32    pub fn get_mut(&mut self) -> Option<&mut S> {
33        self.sink.as_mut()
34    }
35
36    fn sink_mut(&mut self) -> &mut S {
37        self.sink.as_mut().take().expect("Attempted to poll Send after completion")
38    }
39
40    fn take_sink(&mut self) -> S {
41        self.sink.take().expect("Attempted to poll Send after completion")
42    }
43}
44
45impl<S: Sink> Future for Send<S> {
46    type Item = S;
47    type Error = S::SinkError;
48
49    fn poll(&mut self, cx: &mut task::Context) -> Poll<S, S::SinkError> {
50        if let Some(item) = self.item.take() {
51            match self.sink_mut().poll_ready(cx)? {
52                Async::Ready(()) => {
53                    self.sink_mut().start_send(item)?;
54                }
55                Async::Pending => {
56                    self.item = Some(item);
57                    return Ok(Async::Pending);
58                }
59            }
60        }
61
62        // we're done sending the item, but want to block on flushing the
63        // sink
64        try_ready!(self.sink_mut().poll_flush(cx));
65
66        // now everything's emptied, so return the sink for further use
67        Ok(Async::Ready(self.take_sink()))
68    }
69}