What types to use for bytes and buffers?

I was recently hacking on rust-postgres, and it is using bytes::Bytes and BytesMut. But then it's also makes its own buffer type, and it also uses &[u8] some places. And the bytes crate also offers Buf and BufMut.

I'm getting a little lost in what types I should be using for network programming and similar tasks. Are there general rules about when I should be using which types?

&[u8] is the lowest common denominator for exposing bytes. You can't store any data as a slice, only temporarily view data stored elsewhere through a slice.

My understanding is that Bytes is a fancy version of Arc<[u8]>. I've never needed it. Vec<u8> usually is good enough for me.

2 Likes

Tangentially, you may find the bstr crate useful for performing String-like operations on byte buffers which may not be UTF8 (such as various networking protocols).

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.