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
#![no_std]
use ach_cell::Cell;
pub use ach_cell::Ref;
use core::ops::Index;
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(Some(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 iter(&self, strict: bool) -> ArrayIterator<T, N> {
ArrayIterator {
vec: self,
index: 0,
strict,
}
}
}
impl<T, const N: usize> Index<usize> for Array<T, N> {
type Output = Cell<T>;
fn index(&self, index: usize) -> &Self::Output {
&self.buf[index]
}
}
pub struct ArrayIterator<'a, T, const N: usize> {
vec: &'a Array<T, N>,
index: usize,
strict: 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;
}
let ret = if self.strict {
self.vec[self.index].get()
} else {
self.vec[self.index].try_get()
};
self.index += 1;
if let Ok(ret) = ret {
Some(ret)
} else {
self.next()
}
}
}