Support operations on byte arrays #248
Labels
blocked-on-generic_const_exprs
https://github.com/rust-lang/rust/issues/76560
blocked-on-rust
Blocked on a Rust feature landing or stabilizing
compatibility-nonbreaking
Changes that are (likely to be) non-breaking
Progress
ByteArray
as private typeByteArray
internally to experimentByteArray
Motivation
We want to be able to support operations on byte arrays, especially
[u8; size_of::<T>()]
for some zerocopy-compatible typeT
. E.g.:A lot of code both inside zerocopy and in user code currently has no way to reason about size equality on byte slices, and so ends up re-doing bounds checks. Consider this code from Fuchsia's packet crate:
In this code,
self.take_front
returnsOption<&[u8]>
, and so the type system can't reason about the returned byte slice satisfyingbytes.len() == size_of::<T>()
.As part of #1315, we'd like to support the general pattern of reading or writing objects to byte slices or fancier buffer types. Given support for byte arrays, we could write something like:
Stabilize
size_of::<T>()
One approach we could take to accomplish this would be to stabilize
size_of::<T>()
for use in a type in a generic context (a special case of generic_const_exprs.Polyfill
Another approach - that we can implement on our own without being blocked on Rust - is to add a polyfill type like the following
Using this polyfill, we could write the
Buffer
trait from the motivation section as:If we use a type which supports unsized types (
Unalign
doesn't), we could even make this more powerful than[u8; size_of::<T>()]
. ForT: Sized
,ByteArray<T>
would have the same layout asT
, but forT: !Sized
, it would have a layout closer to[u8]
. It's unclear how an unsized version of this could be constructed, though, since the fat pointer would need to know the number of trailing slice elements inT
, not the number of bytes.Interior mutability
TODO: Explain why Stacked Borrows would require
T: Immutable
, but why we may not need that bound in practice (ie, we can "disable" interior mutability).d a
&ByteArray<T>
to the same memory ifT
contained anUnsafeCell
.*This was originally prototyped (though never merged) here.
TODO: Is it possible to support
T: ?Sized
?MaybeUninit<T>
requiresT: Sized
, and in general, unions don't support unsized types, so it's not possible to just manually implement a standinMaybeUninit
that does supportT: ?Sized
.The text was updated successfully, but these errors were encountered: