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
use ach_cell::Cell;
pub use ach_cell::Peek;

#[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];
    }
    /// pop a value from random position
    pub fn pop(&self) -> Option<T> {
        for index in 0..self.capacity() {
            if let Some(x) = self.buf[index].take() {
                return Some(x);
            }
        }
        None
    }
    /// push a value to random position, return index
    pub fn push(&self, mut value: T) -> Result<usize, T> {
        for index in 0..self.capacity() {
            if let Err(v) = self.buf[index].set(value) {
                value = v;
            } else {
                return Ok(index);
            }
        }
        Err(value)
    }
    pub fn get(&self, index: usize) -> Option<Peek<T>> {
        self.buf[index].get()
    }
    pub fn iter(&self) -> ArrayIterator<T, N> {
        ArrayIterator {
            vec: self,
            index: 0,
        }
    }
}
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,
}
impl<'a, T, const N: usize> Iterator for ArrayIterator<'a, T, N> {
    type Item = Option<Peek<'a, T>>;
    fn next(&mut self) -> Option<Self::Item> {
        if self.index >= self.vec.capacity() {
            return None;
        }
        let ret = self.vec.get(self.index);
        self.index += 1;
        Some(ret)
    }
}