tokio-rs / bytes

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

Why not impl `Buf::get_array<const N: usize>(&mut self) -> [u8; N]`? #614

Closed stackinspector closed 1 year ago

stackinspector commented 1 year ago

The implementation of Buf::get_{number_types} could also be based on it, thus avoiding buf_get_impl!. Are there any other considerations such as MSRV? If not I can provide PR. By the way, why not put Buf and BufMut into a separate crate? I had basically reimplemented Buf where there is no need for Bytes and forgot that there is an implementation inside this crate.

stackinspector commented 1 year ago

This is one half of my implementation of a Buf-like thing for &[u8], mainly referencing impl Read::read_exact for &[u8] in std. Then as the other half, I implemented get_{number_types} in another crate based on BytesRead::read_to_array and then map({number_types}::from_be_bytes).

Darksonn commented 1 year ago

The MSRV of the bytes crate is too old for const generics, and I don't think we should bump it just for this.

As for moving Buf to another crate, potentially it could happen, but its complicated. See #479 for more.

stackinspector commented 1 year ago

Seems there is another problem: const generics will let Buf cannot be made into a trait object.

error[E0038]: the trait `Buf` cannot be made into an object
    --> src\buf\buf_impl.rs:1414:30
     |
1414 | fn _assert_trait_object(_b: &dyn Buf) {}
     |                              ^^^^^^^ `Buf` cannot be made into an object
     |
note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety>
    --> src\buf\buf_impl.rs:288:8
     |
76   | pub trait Buf {
     |           --- this trait cannot be made into an object...
...
288  |     fn get_array<const N: usize>(&mut self) -> [u8; N] {
     |        ^^^^^^^^^ ...because method `get_array` has generic type parameters
     = help: consider moving `get_array` to another trait

For more information about this error, try `rustc --explain E0038`.
error: could not compile `bytes` due to previous error