Description
What are the projects thoughts on adding from_const_and_len
version of from_const
to be able to create a SmallVec
in a const context that does not logically occupy the full inline stack space? Like:
#[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
#[inline]
pub const fn from_const_and_len(items: [T; N], len: usize) -> Self {
if len >= N {
panic!("Expected len to be less than or equal to array size");
}
SmallVec {
capacity: len,
data: SmallVecData::from_const(MaybeUninit::new(items)),
}
}
Example Application
The reason this came up is that I'm working on a MIDI library. MIDI uses a variable length quantity (VLQ) type for integers. I'm using a SmallVec<[u8; 4]>
as the backing storage so that a VLQ can store 4 bytes inline before spilling onto the heap. I wanted to be able to create a VLQ::ZERO
constant to represent 0
stored as a VLQ, which means the backing SmallVec
needs to be logically [0]
(capacity = 1). But my only option (as far as I am aware) was SmallVec::from_const([0; 4])
which would logically be [0, 0, 0, 0]
, which is not a valid representation of 0
as a VLQ.
Issues
Unfortunately, panic!
in const contexts was only stabilized in Rust 1.57, which as far as I am aware would cause an issue since currently the const_new
feature only requires Rust 1.51. I'm not sure how (if at all) this can be mitigated to keep from_const_and_len
safe while not changing the version requirements for the const_new
feature.