`tokio` and `bincode`: reading from a socket

I have a UnixStream socket in an application using tokio. I also have some structs that use bincode's Encode and Decode traits. I know that bincode handles the length of variable-length fields (like Strings), but I don't think the sockets do. If I don't read a full struct from the socket, I doubt it'll decode() properly. How do I read from a tokio socket, such that I can be sure that I've read a full struct?

Edit:
Does bincode maybe have a way to automatically decode() directly from a tokio socket?

Instead of sending only the encoded struct, you could send:
-the length of the encoded struct
-the encoded struct

So on reception, you could:
-use read_u64_le() to get the size of the encoded struct
-use read_exact() to read exactly the number of bytes you want.

OK. Does tokio guarantee that if I use write_all() to send something on one end, the whole thing will be received at once on the other end?

I don't think so.

It can't. The OS may decide to do a short write or short read.

1 Like

No, that's why you have to write the number of bytes you're sending first. That way, the receiver knows when to stop reading.