1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
use ach_cell::Cell;
pub use ach_cell::Ref;
use util::Error;
#[derive(Debug)]
pub struct Array<T, const N: usize> {
buf: [Cell<T>; N],
}
impl<T, const N: usize> Array<T, N> {
const CAPACITY: usize = N;
const INIT_ITEM: Cell<T> = Cell::new();
pub const fn new() -> Self {
Array {
buf: [Self::INIT_ITEM; N],
}
}
pub const fn capacity(&self) -> usize {
Self::CAPACITY
}
pub fn is_empty(&self) -> bool {
self.buf.iter().all(|x| !x.is_initialized())
}
pub fn is_full(&self) -> bool {
self.buf.iter().all(|x| x.is_initialized())
}
pub fn clear(&mut self) {
self.buf = [Self::INIT_ITEM; N];
}
pub fn pop(&self) -> Option<T> {
for index in 0..self.capacity() {
if let Ok(x) = self.buf[index].try_take() {
return Some(x);
}
}
None
}
pub fn push(&self, mut value: T) -> Result<usize, T> {
for index in 0..self.capacity() {
if let Err(v) = self.buf[index].try_set(value) {
value = v.input;
} else {
return Ok(index);
}
}
Err(value)
}
pub fn try_get(&self, index: usize) -> Result<Ref<T>, Error<()>> {
self.buf[index].try_get()
}
pub fn get(&self, index: usize) -> Option<Ref<T>> {
self.buf[index].get()
}
pub fn try_take(&self, index: usize) -> Result<T, Error<()>> {
self.buf[index].try_take()
}
pub fn take(&self, index: usize) -> Option<T> {
self.buf[index].take()
}
pub fn try_swap(&self, index: usize, value: T) -> Result<Option<T>, Error<T>> {
self.buf[index].try_swap(value)
}
pub fn swap(&self, index: usize, value: T) -> Result<Option<T>, T> {
self.buf[index].swap(value)
}
pub fn iter(&self, spin: bool) -> ArrayIterator<T, N> {
ArrayIterator {
vec: self,
index: 0,
spin,
}
}
}
impl<T, const N: usize> Drop for Array<T, N> {
fn drop(&mut self) {
self.clear()
}
}
pub struct ArrayIterator<'a, T, const N: usize> {
vec: &'a Array<T, N>,
index: usize,
spin: bool,
}
impl<'a, T, const N: usize> Iterator for ArrayIterator<'a, T, N> {
type Item = Ref<'a, T>;
fn next(&mut self) -> Option<Self::Item> {
if self.index >= self.vec.capacity() {
return None;
}
if self.spin {
let ret = self.vec.get(self.index);
self.index += 1;
if let Some(ret) = ret {
Some(ret)
} else {
self.next()
}
} else {
let ret = self.vec.try_get(self.index);
self.index += 1;
if let Ok(ret) = ret {
Some(ret)
} else {
self.next()
}
}
}
}