polachok / fahrenheit

toy futures executor 🚒📖🔥
Other
233 stars 23 forks source link

AsyncRead with Vec::with_capacity() #18

Open goriunov opened 5 years ago

goriunov commented 5 years ago

Hi i am playing around with async/await and i have got some issue with reading bytes into vec with with_capacity or just new.

This is my code for just read scenario where it always return empty return 0 read bytes for some reason:

async fn process(mut stream: AsyncTcpStream) {
    let mut buf = Vec::with_capacity(100);
    await!(stream.read(&mut buf)); 
    println!("{}", String::from_utf8_lossy(&buf));
}

the same applies for read_exact:

async fn process(mut stream: AsyncTcpStream) {
    let mut buf = Vec::with_capacity(100);
    await!(stream.read_exact(&mut buf)); 
    println!("{}", String::from_utf8_lossy(&buf));
}

However read_to_end works alright (unfortunately i can needs to wait till connection ended)

Can some one explain me if i do something wrong if not then why does it behave like that. Thanks :)

goriunov commented 5 years ago

Actually how do you read from the socket till it hits would block ? I am not sure that await! allows it

SteelCrow commented 5 years ago

Hi, methods: read & read_exact have diffrenet implementation from read_to_end, the first two do not initialize vector, so when you try to use Vec::with_capacity(n) your vector length is zero, and you can't read anything to zero length vector. Change Vec::with_capacity(n) to vec![0u8;100] and I think it will work.