3

I would like to read data from the TcpStream until I encounter a '\0'. The issue is that tokio::io::read_until needs the stream to be BufRead.

fn poll(&mut self) -> Poll<(), Self::Error> {
    match self.listener.poll_accept()? {
        Async::Ready((stream, _addr)) => {
            let task = tokio::io::read_until(stream, 0, vec![0u8; buffer])
                 .map_err(|_| ...)
                 .map(|_| ...);
            tokio::spawn(task);
        }
        Async::NotReady => return Ok(Async::NotReady),
    }
}

How can I read data from the TcpStream this way?

hedgar2017
  • 1,425
  • 3
  • 21
  • 40
  • Please review how to create a [MCVE] and then [edit] your question to include it. We cannot tell what crates, types, traits, fields, etc. are present in the code. Try to produce something that reproduces your error on the [Rust Playground](https://play.rust-lang.org) or you can reproduce it in a brand new Cargo project. There are [Rust-specific MCVE tips](//stackoverflow.com/tags/rust/info) as well. – Shepmaster Nov 18 '18 at 13:42
  • Please include the **exact** error message you are getting. – Shepmaster Nov 18 '18 at 13:52
  • I think my questions are pretty simple for you so it is unnecessary to provide so much data. Today I am a bit in a hurry, but next time I will have more time. – hedgar2017 Nov 18 '18 at 21:13

1 Answers1

4

Reading the documentation for BufRead, you'll see the text:

If you have something that implements Read, you can use the BufReader type to turn it into a BufRead.

fn example(stream: TcpStream) {
    io::read_until(std::io::BufReader::new(stream), 0, vec![]);
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • Thanks, it works. But for some reason `read_exact` writes data to the end of the buffer. Actually, I ended up with implementing a custom future that consumes the stream and returns the stream along with the read data as a tuple - just like `write_all`, but for reading. – hedgar2017 Nov 18 '18 at 21:09