tokio-rs / bytes

Utilities for working with bytes
MIT License
1.91k stars 286 forks source link

Is there a comparison of `bytes::Bytes` and `std::io::Bytes`/&[u8]`? #640

Closed MaxG87 closed 11 months ago

MaxG87 commented 11 months ago

I am relatively new to Rust but already had to deal with in-memory buffers for binary data. I noticed that one could use &[u8] or Vec<u8> for that. However, I also noticed there is bytes::Bytes, which sounds promising as it bothered to give a name to that concept.

Unfortunately, using it was a bit cumbersome, as I had a hard time to to convince all involved modules to just accept Bytes. That might be totally due to me, as I am still novice, though. Anyhow, I wondered whether the fuzz is worth it.

Is there a resource explaining when one should opt to bytes::Bytes and when there are no benefits compared to Vec<u8>? It might be opinionated, but I would love to learn about when it would provide some benefits.

In case there is no such resource, I would like to suggest that a brief section could be added to the documentation.

Darksonn commented 11 months ago

The primary feature of Bytes is that the .clone() operation is really cheap. A clone on a Bytes just increments a counter for how many clones there are, whereas cloning a Vec<u8> copies all of the data in the vector. It is comparable to an Arc<Vec<u8>>, except that Bytes supports slicing so that you only see part of the buffer.

MaxG87 commented 11 months ago

Thank you very much! This is good to know. With that I understand the description on https://docs.rs/bytes/ better.