futures_util/sink/
flush.rs

1use futures_core::{Poll, Async, Future};
2use futures_core::task;
3use futures_sink::Sink;
4
5/// Future for the `flush` combinator, which polls the sink until all data
6/// has been flushed.
7#[derive(Debug)]
8#[must_use = "futures do nothing unless polled"]
9pub struct Flush<S> {
10    sink: Option<S>,
11}
12
13/// A future that completes when the sink has finished processing all
14/// pending requests.
15///
16/// The sink itself is returned after flushing is complete; this adapter is
17/// intended to be used when you want to stop sending to the sink until
18/// all current requests are processed.
19pub fn new<S: Sink>(sink: S) -> Flush<S> {
20    Flush { sink: Some(sink) }
21}
22
23impl<S: Sink> Flush<S> {
24    /// Get a shared reference to the inner sink.
25    /// Returns `None` if the sink has already been flushed.
26    pub fn get_ref(&self) -> Option<&S> {
27        self.sink.as_ref()
28    }
29
30    /// Get a mutable reference to the inner sink.
31    /// Returns `None` if the sink has already been flushed.
32    pub fn get_mut(&mut self) -> Option<&mut S> {
33        self.sink.as_mut()
34    }
35
36    /// Consume the `Flush` and return the inner sink.
37    /// Returns `None` if the sink has already been flushed.
38    pub fn into_inner(self) -> Option<S> {
39        self.sink
40    }
41}
42
43impl<S: Sink> Future for Flush<S> {
44    type Item = S;
45    type Error = S::SinkError;
46
47    fn poll(&mut self, cx: &mut task::Context) -> Poll<S, S::SinkError> {
48        let mut sink = self.sink.take().expect("Attempted to poll Flush after it completed");
49        if sink.poll_flush(cx)?.is_ready() {
50            Ok(Async::Ready(sink))
51        } else {
52            self.sink = Some(sink);
53            Ok(Async::Pending)
54        }
55    }
56}