Skip to main content

box2d_rs/
b2_growable_stack.rs

1use crate::b2_common::*;
2
3/// This is a growable LIFO stack with an initial capacity of n.
4/// If the stack size exceeds the initial capacity, the heap is used
5/// to increase the size of the stack.
6pub struct B2growableStack<T: Copy + Default, const N: usize> {
7
8	value:B2rsStackOrVec<T,N>
9	
10	//box2d-rs: using enum because problems to have ref to own field
11	// T* m_stack;
12	// T m_array[N];
13	// int32 m_count;
14	// int32 m_capacity;
15}
16
17struct B2rsStaticArrayWithSize<T: Copy + Default, const N: usize>
18{
19	m_array: [T; N],
20	m_count: usize,
21}
22
23enum B2rsStackOrVec<T: Copy + Default, const N: usize>
24{
25	Stack(B2rsStaticArrayWithSize<T,N>),
26	DynVec(Vec<T>)
27}
28
29impl<T: Copy + Default, const N: usize> B2growableStack<T,N> {
30	pub fn new() -> Self {
31		return B2growableStack {
32			value: B2rsStackOrVec::Stack(B2rsStaticArrayWithSize {
33				m_array: [T::default(); N],
34				m_count: 0,
35			})
36		};
37	}
38
39	pub fn push(&mut self, element: &T) {
40		match self.value
41		{
42			B2rsStackOrVec::Stack(ref mut stack)=>{
43				if stack.m_count >= N {
44					let mut v = Vec::<T>::with_capacity(stack.m_count+1);
45					v.extend_from_slice(&stack.m_array);
46					v.push(*element);
47					self.value = B2rsStackOrVec::DynVec(v);
48				}else{
49					stack.m_array[stack.m_count] = *element;
50					stack.m_count += 1;
51				}
52			},
53			B2rsStackOrVec::DynVec(ref mut vec)=>{
54				vec.push(*element);
55			}
56		}
57	}
58
59	pub fn pop(&mut self) -> T {
60		match self.value
61		{
62			B2rsStackOrVec::Stack(ref mut stack)=>{
63				b2_assert(stack.m_count > 0);
64				stack.m_count-=1;
65				return stack.m_array[stack.m_count];
66			},
67			B2rsStackOrVec::DynVec(ref mut vec)=>{
68				b2_assert(vec.len() > 0);
69				return vec.pop().unwrap();
70			}
71		}
72	}
73
74	pub fn get_count(&self) -> usize {
75		match self.value
76		{
77			B2rsStackOrVec::Stack(ref stack)=>{
78				return stack.m_count;
79			},
80			B2rsStackOrVec::DynVec(ref vec)=>{
81				return vec.len();
82			}
83		}
84	}
85}