1use futures::{Async, Future, Poll};
2use std::{fmt, io, mem, path::Path};
3use tokio_io;
4use {file, File};
5
6pub fn write<P, C: AsRef<[u8]>>(path: P, contents: C) -> WriteFile<P, C>
30where
31 P: AsRef<Path> + Send + 'static,
32{
33 WriteFile {
34 state: State::Create(File::create(path), Some(contents)),
35 }
36}
37
38#[derive(Debug)]
41pub struct WriteFile<P: AsRef<Path> + Send + 'static, C: AsRef<[u8]>> {
42 state: State<P, C>,
43}
44
45#[derive(Debug)]
46enum State<P: AsRef<Path> + Send + 'static, C: AsRef<[u8]>> {
47 Create(file::CreateFuture<P>, Option<C>),
48 Write(tokio_io::io::WriteAll<File, C>),
49}
50
51impl<P: AsRef<Path> + Send + 'static, C: AsRef<[u8]> + fmt::Debug> Future for WriteFile<P, C> {
52 type Item = C;
53 type Error = io::Error;
54
55 fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
56 let new_state = match &mut self.state {
57 State::Create(ref mut create_file, contents) => {
58 let file = try_ready!(create_file.poll());
59 let write = tokio_io::io::write_all(file, contents.take().unwrap());
60 State::Write(write)
61 }
62 State::Write(ref mut write) => {
63 let (_, contents) = try_ready!(write.poll());
64 return Ok(Async::Ready(contents));
65 }
66 };
67
68 mem::replace(&mut self.state, new_state);
69 self.poll()
71 }
72}