From d11c853346dada6cb924bee6dccad189f663440a Mon Sep 17 00:00:00 2001 From: Thomas de Zeeuw Date: Tue, 17 Jul 2018 14:46:53 +0200 Subject: [PATCH] FEAT: Add ArrayVec.capacity_left --- src/lib.rs | 13 +++++++++++++ tests/tests.rs | 14 ++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index e40b0a5..5116f48 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -172,6 +172,19 @@ impl ArrayVec { /// ``` pub fn is_full(&self) -> bool { self.len() == self.capacity() } + /// Returns the capacity left in the `ArrayVec`. + /// + /// ``` + /// use arrayvec::ArrayVec; + /// + /// let mut array = ArrayVec::from([1, 2, 3]); + /// array.pop(); + /// assert_eq!(array.capacity_left(), 1); + /// ``` + pub fn capacity_left(&self) -> usize { + self.capacity() - self.len() + } + /// Push `element` to the end of the vector. /// /// ***Panics*** if the vector is already full. diff --git a/tests/tests.rs b/tests/tests.rs index bb7fe8a..ed98241 100644 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -27,6 +27,20 @@ fn test_simple() { assert_eq!(sum_len, 8); } +#[test] +fn test_capacity_left() { + let mut vec: ArrayVec<[usize; 4]> = ArrayVec::new(); + assert_eq!(vec.capacity_left(), 4); + vec.push(1); + assert_eq!(vec.capacity_left(), 3); + vec.push(2); + assert_eq!(vec.capacity_left(), 2); + vec.push(3); + assert_eq!(vec.capacity_left(), 1); + vec.push(4); + assert_eq!(vec.capacity_left(), 0); +} + #[test] fn test_u16_index() { const N: usize = 4096;