My intention is to access to a TcpStream and perform two read operations in two different methods of a struct that holds the TcpStream as attribute.
The first operation performs fine but when I try to load the remaining bytes on the second method, the buffer cannot be filled.
I have tried to create a very simple recreation. This is how it works:
- Some data is sent to a socket (8 bytes)
- 1 byte is read using
readand a buffer of 1 byte size. Everything is fine. - 1 byte is read using
read_exactand a buffer of 1 byte size. Everything is fine. - 1 byte should be read using
read_exactover the underlyingreadobject (streamobject). The buffer cannot be filled. I get an error if I unwrap, or the buffer with the initial values.
#[cfg(test)]
mod tests {
use std::net::{TcpListener, TcpStream};
use std::io::{BufReader, Read, Write};
#[test]
fn test_read_twice() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let local_addr = listener.local_addr().unwrap();
let mut stream = TcpStream::connect(local_addr).unwrap();
match listener.accept() {
Ok((mut socket, _)) => {
let _ = socket.write_all(&[0, 1, 2, 4, 5, 7]);
}
Err(e) => println!("couldn't get client: {:?}", e),
}
{
let mut reader = BufReader::new(&mut stream);
let mut buff = vec![0u8; 1];
let _ = reader.read(&mut buff[..]).unwrap();
assert_eq!(buff, vec![0]);
let mut buff = vec![0u8; 1];
let _ = reader.read_exact(&mut buff[..]).unwrap();
assert_eq!(buff, vec![1]);
}
let mut buff = vec![88u8; 1];
let _ = stream.read_exact(&mut buff[..]);
assert_eq!(buff, vec![2]);
}
}