From c34a55dcac480092ba44de5ee0f3b482a1b3cf79 Mon Sep 17 00:00:00 2001 From: Manos Pitsidianakis Date: Fri, 21 Jun 2019 10:55:49 +0300 Subject: [PATCH] melib: Correctly use StackVec capacity, add test --- melib/src/structs.rs | 36 +++++++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/melib/src/structs.rs b/melib/src/structs.rs index 8cb029ced..a3d93dc5c 100644 --- a/melib/src/structs.rs +++ b/melib/src/structs.rs @@ -1,10 +1,11 @@ use std::iter::{Extend, FromIterator}; use std::ops::Index; +const STACK_VEC_CAPACITY: usize = 32; #[derive(Debug, Default)] pub struct StackVec { len: usize, - array: [T; 32], + array: [T; STACK_VEC_CAPACITY], heap_vec: Vec, } @@ -12,19 +13,19 @@ impl StackVec { pub fn new() -> Self { StackVec { len: 0, - array: [T::default(); 32], + array: [T::default(); STACK_VEC_CAPACITY], heap_vec: Vec::new(), } } pub fn push(&mut self, ind: T) { if self.len == self.array.len() { if self.heap_vec.is_empty() { - self.heap_vec.reserve(32); - for _ in 0..8 { + self.heap_vec.reserve(STACK_VEC_CAPACITY); + for _ in 0..STACK_VEC_CAPACITY { self.heap_vec.push(T::default()); } } - self.heap_vec[0..8].copy_from_slice(&self.array); + self.heap_vec[0..STACK_VEC_CAPACITY].copy_from_slice(&self.array); self.heap_vec.push(ind); } else if self.len > self.array.len() { self.heap_vec.push(ind); @@ -166,3 +167,28 @@ impl std::iter::DoubleEndedIterator for Sta } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_stackvec() { + let mut stack = StackVec::from_iter(0..4 * STACK_VEC_CAPACITY); + let mut ctr = 0; + assert!(stack.iter().all(|&x| { + let ret = (x == ctr); + ctr += 1; + ret + })); + for _ in 0..(3 * STACK_VEC_CAPACITY) + 1 { + stack.pop(); + } + ctr = 0; + assert!(stack.iter().all(|&x| { + let ret = (x == ctr); + ctr += 1; + ret + })); + } +}