I'm reading bytes off a TcpStream (smol-rs) and I need to frame[1] and share[2] this data.
I heard about the bytes crate and how it can make this easier to do. But despite pouring over it's docs page, I just can't figure out what it is that it provides me that I can't do just as easy with a mutable array or vec? It appears to have an internal cursor that I can advance, but it seems like the same amount of work as just having a manual cursor in the form of an int.
let mut buf = BytesMut::zeroed(1024);
let n = stream.read(&mut buf).await.unwrap();
// some loop later
let n = stream.read(&mut buf).await.unwrap();
let mut buf = [0; 1024];
let n = stream.read(&mut buf).await.unwrap();
// some loop later
let n = stream.read(&mut buf).await.unwrap();
These do the same thing from a user observation. buf.advance(n)
is just cursor_int += n
. I already get the same bunch of iterators with regular arrays and slice and vecs like joins and concats etc. This is an extremely popular crate, what am I not getting?
-
each line is a header and at the end of the message is a body of x length. A Content-Length header field establishes the len of the body. ↩︎
-
I do this by having the threads compete for a lock on the TcpStream in a select statement that branches to a broadcast channel. If they acquire the lock they get to read first from the stream and then broadcast what they read. ↩︎