Closed Evian-Zhang closed 12 months ago
Unfortunately, it's a breaking change to add new trait requirements. A 3rd-party crate could have a ToBytes
or FromBytes
implementation where they use a type Bytes
that doesn't implement IntoIterator
, or any other use of NumBytes
that would now be more constrained.
Your example function could add where I::Bytes: IntoIterator<Item = u8>
, but I know it's inconvenient to propagate extra bounds on associated types like that, especially because of rust-lang/rust#20671. (And BTW, flatten
can handle the into_iter()
call for you.)
There's also an issue that arrays didn't implement IntoIterator
until Rust 1.53, so we would have to raise MSRV. That's possible, but the breaking change above is the bigger problem.
FWIW, since you're keeping native-endian bytes -- if you're only concerned with primitive types, your particular example could also be written with bytemuck::cast_slice
.
Ok, I understood. Thank you for your kind explanation.
This PR implements
IntoIterator<Item = u8>
forNumBytes
, since theAsRef
andBorrow
traits forNumBytes
will have trouble with lifetime as it borrows the array.An actual usage of this trait is when I want to convert a list of integers into bytes (i.e. flatten the generated bytes array for each integer):
However, if I replace the
into_iter
withas_ref()
, the borrow checker will deny the compilation since the lifetime of the array generated into_ne_bytes()
cannot live long enough. The workaround here is justas_ref().to_vec()
, which involves additional heap allocations.