Is there a library containing the necessary unsafe code for something like this hypothetical ByteArrayVec
, which owns an inline, fixed-length byte buffer and provides a container for a variable number of T
s?
struct ByteArrayVec<T, const CAP_BYTES: usize> {
len: usize,
storage: [MaybeUninit<u8>; CAP_BYTES],
_phantom: PhantomData<T>,
}
impl ByteArrayVec {
fn try_push(&mut self, value: T) -> Result<(), T> {...}
fn as_slice(&self) -> &[T] {...}
// ...
}
There are plenty of ArrayVec
implementations, but all the ones I recall seeing take a capacity in elements, not bytes. For the application I have in mind, which is a buffer for batching items, I want to specify the capacity in bytes, and let the vector fit as many as possible. This way, the capacity parameter can be specified in terms of “reasonable amount of stack memory for this function to use” instead of in terms of the size of T
.
(This would of course be trivial with const generic expressions — just compute CAP_BYTES / size_of::<T>()
as the array length — but I want something that works in stable Rust.)