tokio-rs / bytes

Utilities for working with bytes
MIT License
1.87k stars 278 forks source link

Passing BytesMut to tokio::UdpSocket always receives 0 bytes #570

Closed ColinAtEinride closed 1 year ago

ColinAtEinride commented 1 year ago

I want to receive bytes from a tokio::UdpSocket. I noticed that the snippet using BytesMut always receives zero bytes, but it does not block. When I swap it for the vec it works as expected. Do I use the library wrong and is this expected behaviour, or should this work?

let mut buf = vec![0; self.buffer_size];
let (bytes, _sender) = self.socket.recv_from(&mut buf).await?; 
let mut buf = BytesMut::with_capacity(self.buffer_size);
let (bytes, _sender) = self.socket.recv_from(&mut buf).await?;

If you folks need additional information, just ask me please. Thank you in advance

Running on Ubuntu22 and rustc 1.63

Darksonn commented 1 year ago

The capacity is not the same as the length! You are passing a slice of length zero to recv_from, so it reads zero bytes.

To fix this, either initialize the BytesMut with zeroes so that its length is no longer zero, or use the try_recv_buf_from method, which will do the right thing. (See its example for how to use it in an async manner together with readable.)