Merge pull request #261 from haata/zero_capacity_vec

Relax Vec bounds to allow for zero-length Vecs
This commit is contained in:
Emil Fresk 2022-01-10 08:26:03 +01:00 committed by GitHub
commit 180db255c7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 33 additions and 2 deletions

View File

@ -52,6 +52,12 @@ pub(crate) const fn smaller_than<const N: usize, const MAX: usize>() {
Assert::<N, MAX>::LESS;
}
#[allow(dead_code)]
#[allow(path_statements)]
pub(crate) const fn greater_than_eq_0<const N: usize>() {
Assert::<N, 0>::GREATER_EQ;
}
#[allow(dead_code)]
#[allow(path_statements)]
pub(crate) const fn greater_than_0<const N: usize>() {

View File

@ -56,8 +56,8 @@ impl<T, const N: usize> Vec<T, N> {
/// ```
/// `Vec` `const` constructor; wrap the returned value in [`Vec`](../struct.Vec.html)
pub const fn new() -> Self {
// Const assert N > 0
crate::sealed::greater_than_0::<N>();
// Const assert N >= 0
crate::sealed::greater_than_eq_0::<N>();
Self {
buffer: [Self::INIT; N],
@ -1233,4 +1233,29 @@ mod tests {
assert!(!v.ends_with(b"ba"));
assert!(!v.ends_with(b"a"));
}
#[test]
fn zero_capacity() {
let mut v: Vec<u8, 0> = Vec::new();
// Validate capacity
assert_eq!(v.capacity(), 0);
// Make sure there is no capacity
assert!(v.push(1).is_err());
// Validate length
assert_eq!(v.len(), 0);
// Validate pop
assert_eq!(v.pop(), None);
// Validate slice
assert_eq!(v.as_slice(), &[]);
// Validate empty
assert!(v.is_empty());
// Validate full
assert!(v.is_full());
}
}