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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
use crate::atomic_once_cell_array::AtomicOnceCellArray;
use std::sync::atomic::{AtomicUsize, Ordering};
pub struct AtomicOnceCellStack<T> {
data: AtomicOnceCellArray<T>,
last_index: AtomicUsize,
}
impl<T> AtomicOnceCellStack<T> {
pub fn with_capacity(capacity: usize) -> Self {
Self {
data: AtomicOnceCellArray::with_capacity(capacity),
last_index: AtomicUsize::new(0),
}
}
pub fn push(
&self,
val: T,
) -> usize {
let last_len = self.last_index.fetch_add(1, Ordering::Relaxed);
self.data.set(last_len, val);
last_len
}
pub fn reserve_uninit(
&self,
num_to_reserve: usize,
) -> usize {
let last_len = self.last_index.fetch_add(num_to_reserve, Ordering::Relaxed);
if last_len + num_to_reserve > self.capacity() {
panic!(
"len {} + num_to_reserve {} must be <= capacity {}",
last_len,
num_to_reserve,
self.capacity()
);
}
last_len
}
pub fn set(
&self,
index: usize,
val: T,
) {
if index < self.len() {
self.data.set(index, val);
} else {
panic!(
"index {} must be < len {} (did you forget to `reserve_uninit` first?)",
index,
self.capacity()
);
}
}
pub fn get(
&self,
index: usize,
) -> &T {
self.data.get(index)
}
pub fn capacity(&self) -> usize {
self.data.capacity()
}
pub fn len(&self) -> usize {
self.last_index.load(Ordering::Acquire)
}
pub fn iter(&self) -> Iter<T> {
self.into_iter()
}
}
impl<'a, T> IntoIterator for &'a AtomicOnceCellStack<T> {
type Item = &'a T;
type IntoIter = Iter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
Iter::new(self)
}
}
pub struct Iter<'a, T> {
source: &'a AtomicOnceCellStack<T>,
next_index: usize,
}
impl<'a, T> Iter<'a, T> {
#[inline]
pub fn new(source: &'a AtomicOnceCellStack<T>) -> Self {
Self {
source,
next_index: 0,
}
}
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.next_index < self.source.len() {
let index = self.next_index;
self.next_index += 1;
Some(self.source.get(index))
} else {
None
}
}
}