tokio_io/io/write_all.rs
1use std::io;
2use std::mem;
3
4use futures::{Future, Poll};
5
6use AsyncWrite;
7
8/// A future used to write the entire contents of some data to a stream.
9///
10/// This is created by the [`write_all`] top-level method.
11///
12/// [`write_all`]: fn.write_all.html
13#[derive(Debug)]
14pub struct WriteAll<A, T> {
15 state: State<A, T>,
16}
17
18#[derive(Debug)]
19enum State<A, T> {
20 Writing { a: A, buf: T, pos: usize },
21 Empty,
22}
23
24/// Creates a future that will write the entire contents of the buffer `buf` to
25/// the stream `a` provided.
26///
27/// The returned future will not return until all the data has been written, and
28/// the future will resolve to the stream as well as the buffer (for reuse if
29/// needed).
30///
31/// Any error which happens during writing will cause both the stream and the
32/// buffer to get destroyed.
33///
34/// The `buf` parameter here only requires the `AsRef<[u8]>` trait, which should
35/// be broadly applicable to accepting data which can be converted to a slice.
36/// The `Window` struct is also available in this crate to provide a different
37/// window into a slice if necessary.
38pub fn write_all<A, T>(a: A, buf: T) -> WriteAll<A, T>
39where
40 A: AsyncWrite,
41 T: AsRef<[u8]>,
42{
43 WriteAll {
44 state: State::Writing {
45 a: a,
46 buf: buf,
47 pos: 0,
48 },
49 }
50}
51
52fn zero_write() -> io::Error {
53 io::Error::new(io::ErrorKind::WriteZero, "zero-length write")
54}
55
56impl<A, T> Future for WriteAll<A, T>
57where
58 A: AsyncWrite,
59 T: AsRef<[u8]>,
60{
61 type Item = (A, T);
62 type Error = io::Error;
63
64 fn poll(&mut self) -> Poll<(A, T), io::Error> {
65 match self.state {
66 State::Writing {
67 ref mut a,
68 ref buf,
69 ref mut pos,
70 } => {
71 let buf = buf.as_ref();
72 while *pos < buf.len() {
73 let n = try_ready!(a.poll_write(&buf[*pos..]));
74 *pos += n;
75 if n == 0 {
76 return Err(zero_write());
77 }
78 }
79 }
80 State::Empty => panic!("poll a WriteAll after it's done"),
81 }
82
83 match mem::replace(&mut self.state, State::Empty) {
84 State::Writing { a, buf, .. } => Ok((a, buf).into()),
85 State::Empty => panic!(),
86 }
87 }
88}