• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use crate::io::AsyncWrite;
2 
3 use std::fmt;
4 use std::io;
5 use std::pin::Pin;
6 use std::task::{Context, Poll};
7 
8 cfg_io_util! {
9     /// An async writer which will move data into the void.
10     ///
11     /// This struct is generally created by calling [`sink`][sink]. Please
12     /// see the documentation of `sink()` for more details.
13     ///
14     /// This is an asynchronous version of [`std::io::Sink`][std].
15     ///
16     /// [sink]: sink()
17     /// [std]: std::io::Sink
18     pub struct Sink {
19         _p: (),
20     }
21 
22     /// Creates an instance of an async writer which will successfully consume all
23     /// data.
24     ///
25     /// All calls to [`poll_write`] on the returned instance will return
26     /// `Poll::Ready(Ok(buf.len()))` and the contents of the buffer will not be
27     /// inspected.
28     ///
29     /// This is an asynchronous version of [`std::io::sink`][std].
30     ///
31     /// [`poll_write`]: crate::io::AsyncWrite::poll_write()
32     /// [std]: std::io::sink
33     ///
34     /// # Examples
35     ///
36     /// ```
37     /// use tokio::io::{self, AsyncWriteExt};
38     ///
39     /// #[tokio::main]
40     /// async fn main() -> io::Result<()> {
41     ///     let buffer = vec![1, 2, 3, 5, 8];
42     ///     let num_bytes = io::sink().write(&buffer).await?;
43     ///     assert_eq!(num_bytes, 5);
44     ///     Ok(())
45     /// }
46     /// ```
47     pub fn sink() -> Sink {
48         Sink { _p: () }
49     }
50 }
51 
52 impl AsyncWrite for Sink {
53     #[inline]
poll_write( self: Pin<&mut Self>, _: &mut Context<'_>, buf: &[u8], ) -> Poll<Result<usize, io::Error>>54     fn poll_write(
55         self: Pin<&mut Self>,
56         _: &mut Context<'_>,
57         buf: &[u8],
58     ) -> Poll<Result<usize, io::Error>> {
59         Poll::Ready(Ok(buf.len()))
60     }
61 
62     #[inline]
poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), io::Error>>63     fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
64         Poll::Ready(Ok(()))
65     }
66 
67     #[inline]
poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), io::Error>>68     fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
69         Poll::Ready(Ok(()))
70     }
71 }
72 
73 impl fmt::Debug for Sink {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result74     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75         f.pad("Sink { .. }")
76     }
77 }
78 
79 #[cfg(test)]
80 mod tests {
81     use super::*;
82 
83     #[test]
assert_unpin()84     fn assert_unpin() {
85         crate::is_unpin::<Sink>();
86     }
87 }
88