You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

116 lines
2.8KB

  1. use std::iter::Extend;
  2. use std::ops::Index;
  3. #[derive(Debug, Default)]
  4. pub struct StackVec<T: Default + Copy + std::fmt::Debug> {
  5. len: usize,
  6. array: [T; 32],
  7. heap_vec: Vec<T>,
  8. }
  9. impl<T: Default + Copy + std::fmt::Debug> StackVec<T> {
  10. pub fn new() -> Self {
  11. StackVec {
  12. len: 0,
  13. array: [T::default(); 32],
  14. heap_vec: Vec::new(),
  15. }
  16. }
  17. pub fn push(&mut self, ind: T) {
  18. if self.len == self.array.len() {
  19. if self.heap_vec.is_empty() {
  20. self.heap_vec.reserve(32);
  21. for _ in 0..8 {
  22. self.heap_vec.push(T::default());
  23. }
  24. }
  25. self.heap_vec[0..8].copy_from_slice(&self.array);
  26. self.heap_vec.push(ind);
  27. } else if self.len > self.array.len() {
  28. self.heap_vec.push(ind);
  29. } else {
  30. self.array[self.len] = ind;
  31. }
  32. self.len += 1;
  33. }
  34. pub fn pop(&mut self) -> Option<T> {
  35. if self.len == 0 {
  36. return None;
  37. }
  38. if self.len >= self.array.len() {
  39. self.len -= 1;
  40. self.heap_vec.pop()
  41. } else {
  42. let ret = self.array[self.len - 1];
  43. self.len -= 1;
  44. Some(ret)
  45. }
  46. }
  47. pub fn len(&self) -> usize {
  48. self.len
  49. }
  50. pub fn is_empty(&self) -> bool {
  51. self.len == 0
  52. }
  53. pub fn iter(&self) -> StackVecIter<T> {
  54. StackVecIter {
  55. stack: &self,
  56. range: 0..self.len,
  57. }
  58. }
  59. }
  60. pub struct StackVecIter<'a, T: Default + Copy + std::fmt::Debug> {
  61. stack: &'a StackVec<T>,
  62. range: std::ops::Range<usize>,
  63. }
  64. impl<'a, T: Default + Copy + std::fmt::Debug> Iterator for StackVecIter<'a, T> {
  65. type Item = &'a T;
  66. fn next(&mut self) -> Option<&'a T> {
  67. if self.range.len() == 0 {
  68. None
  69. } else {
  70. let idx = self.range.start;
  71. self.range.start += 1;
  72. Some(&self.stack[idx])
  73. }
  74. }
  75. }
  76. impl<'a, T: Default + Copy + std::fmt::Debug> std::iter::DoubleEndedIterator
  77. for StackVecIter<'a, T>
  78. {
  79. fn next_back(&mut self) -> Option<&'a T> {
  80. if self.range.len() == 0 {
  81. None
  82. } else {
  83. let idx = self.range.end - 1;
  84. self.range.end -= 1;
  85. Some(&self.stack[idx])
  86. }
  87. }
  88. }
  89. impl<T: Default + Copy + std::fmt::Debug> Index<usize> for StackVec<T> {
  90. type Output = T;
  91. fn index(&self, idx: usize) -> &T {
  92. if self.len >= self.array.len() {
  93. &self.heap_vec[idx]
  94. } else {
  95. &self.array[idx]
  96. }
  97. }
  98. }
  99. impl<T: Default + Copy + std::fmt::Debug> Extend<T> for StackVec<T> {
  100. fn extend<I>(&mut self, iter: I)
  101. where
  102. I: IntoIterator<Item = T>,
  103. {
  104. for elem in iter {
  105. self.push(elem);
  106. }
  107. }
  108. }