inside_baseball/utils/
byte_array.rs1use std::{fmt, iter::Copied, ops::Deref, slice};
2
3#[derive(Clone)]
4pub struct ByteArray<const CAPACITY: usize> {
5 len: u8,
6 data: [u8; CAPACITY],
7}
8
9impl<const CAPACITY: usize> Default for ByteArray<CAPACITY> {
10 fn default() -> Self {
11 Self {
12 len: 0,
13 data: [0; CAPACITY],
14 }
15 }
16}
17
18impl<const CAPACITY: usize> ByteArray<CAPACITY> {
19 pub fn new() -> Self {
20 Self::default()
21 }
22
23 pub fn as_slice(&self) -> &[u8] {
24 self
25 }
26
27 pub fn push(&mut self, item: u8) {
28 self.data[usize::from(self.len)] = item;
29 self.len += 1;
30 }
31}
32
33impl<const CAPACITY: usize> PartialEq for ByteArray<CAPACITY> {
34 fn eq(&self, other: &Self) -> bool {
35 self.as_slice() == other.as_slice()
36 }
37}
38
39impl<const CAPACITY: usize> Deref for ByteArray<CAPACITY> {
40 type Target = [u8];
41
42 fn deref(&self) -> &Self::Target {
43 &self.data[..usize::from(self.len)]
44 }
45}
46
47impl<const CAPACITY: usize> fmt::Debug for ByteArray<CAPACITY> {
48 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
49 self.as_slice().fmt(f)
50 }
51}
52
53impl<'a, const CAPACITY: usize> IntoIterator for &'a ByteArray<CAPACITY> {
54 type Item = u8;
55 type IntoIter = Copied<slice::Iter<'a, u8>>;
56
57 fn into_iter(self) -> Self::IntoIter {
58 self.data[..self.len.into()].iter().copied()
59 }
60}