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
use array_init::array_init;
use core::default::Default;
use core::fmt::{self, Debug};
use core::ops::Deref;
const STATIC_COLLECTION_SIZE: usize = 128;
pub struct StaticCollection<T: Default> {
entries: [T; STATIC_COLLECTION_SIZE],
next_entry: usize,
}
impl<T: Default> StaticCollection<T> {
pub const MAX_SIZE: usize = STATIC_COLLECTION_SIZE;
pub fn new() -> Self {
Self {
entries: array_init(|_| Default::default()),
next_entry: 0,
}
}
pub fn len(&self) -> usize {
self.next_entry
}
pub fn push(&mut self, entry: T) {
assert!(self.next_entry < Self::MAX_SIZE);
self.entries[self.next_entry] = entry;
self.next_entry += 1;
}
pub fn as_slice(&self) -> &[T] {
&self.entries[0..self.next_entry]
}
pub fn as_mut_slice(&mut self) -> &mut [T] {
&mut self.entries[0..self.next_entry]
}
}
impl<T: Default> Deref for StaticCollection<T> {
type Target = [T];
fn deref<'a>(&'a self) -> &'a [T] {
self.as_slice()
}
}
impl<T: Default> Default for StaticCollection<T> {
fn default() -> StaticCollection<T> {
Self::new()
}
}
impl<T: Default> FromIterator<T> for StaticCollection<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let mut c = Self::new();
for i in iter {
c.push(i);
}
c
}
}
impl<T: Default> Debug for StaticCollection<T>
where
T: Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("StaticCollection")
.field(&self.as_slice())
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[allow(unused_imports)]
use alloc::prelude::v1::*;
#[test]
fn test_as_slice() {
let mut container: StaticCollection<&'static str> = StaticCollection::new();
container.push("test one");
container.push("test two");
assert_eq!(container.as_slice(), &["test one", "test two"]);
}
#[test]
fn test_deref() {
let mut container: StaticCollection<&'static str> = StaticCollection::new();
container.push("test one");
container.push("test two");
assert_eq!(container.deref(), &["test one", "test two"]);
}
#[test]
fn test_from_iterator() {
let mut container: Vec<&'static str> = Vec::new();
container.push("test one");
container.push("test two");
let c = container
.iter()
.map(|x| *x)
.collect::<StaticCollection<&'static str>>();
assert_eq!(c.as_slice(), &["test one", "test two"]);
}
}