1 use std::io::{self, Read, BufRead};
2 use std::mem;
3
4 use futures::{Poll, Future};
5
6 /// A future which can be used to easily read the contents of a stream into a
7 /// vector until the delimiter is reached.
8 ///
9 /// Created by the [`read_until`] function.
10 ///
11 /// [`read_until`]: fn.read_until.html
12 #[must_use = "futures do nothing unless polled"]
13 pub struct ReadUntil<A> {
14 state: State<A>,
15 }
16
17 enum State<A> {
18 Reading {
19 a: A,
20 byte: u8,
21 buf: Vec<u8>,
22 },
23 Empty,
24 }
25
26 /// Creates a future which will read all the bytes associated with the I/O
27 /// object `A` into the buffer provided until the delimiter `byte` is reached.
28 /// This method is the async equivalent to [`BufRead::read_until`].
29 ///
30 /// In case of an error the buffer and the object will be discarded, with
31 /// the error yielded. In the case of success the object will be destroyed and
32 /// the buffer will be returned, with all bytes up to, and including, the delimiter
33 /// (if found).
34 ///
35 /// [`BufRead::read_until`]: https://doc.rust-lang.org/std/io/trait.BufRead.html#method.read_until
read_until<A>(a: A, byte: u8, buf: Vec<u8>) -> ReadUntil<A> where A: BufRead36 pub fn read_until<A>(a: A, byte: u8, buf: Vec<u8>) -> ReadUntil<A>
37 where A: BufRead
38 {
39 ReadUntil {
40 state: State::Reading {
41 a: a,
42 byte: byte,
43 buf: buf,
44 }
45 }
46 }
47
48 impl<A> Future for ReadUntil<A>
49 where A: Read + BufRead
50 {
51 type Item = (A, Vec<u8>);
52 type Error = io::Error;
53
poll(&mut self) -> Poll<(A, Vec<u8>), io::Error>54 fn poll(&mut self) -> Poll<(A, Vec<u8>), io::Error> {
55 match self.state {
56 State::Reading { ref mut a, byte, ref mut buf } => {
57 // If we get `Ok(n)`, then we know the stream hit EOF or the delimiter.
58 // and just return it, as we are finished.
59 // If we hit "would block" then all the read data so far
60 // is in our buffer, and otherwise we propagate errors.
61 try_nb!(a.read_until(byte, buf));
62 },
63 State::Empty => panic!("poll ReadUntil after it's done"),
64 }
65
66 match mem::replace(&mut self.state, State::Empty) {
67 State::Reading { a, byte: _, buf } => Ok((a, buf).into()),
68 State::Empty => unreachable!(),
69 }
70 }
71 }
72