hacspec_lib/
bytes.rs

1pub trait FunctionalVec {
2    fn concat(&self, other: &[u8]) -> Vec<u8>;
3    fn concat_byte(&self, other: u8) -> Vec<u8>;
4}
5
6impl FunctionalVec for Vec<u8> {
7    fn concat(&self, other: &[u8]) -> Vec<u8> {
8        let mut out = self.clone();
9        out.extend_from_slice(other);
10        out
11    }
12
13    fn concat_byte(&self, other: u8) -> Vec<u8> {
14        let mut out = self.clone();
15        Vec::<u8>::push(&mut out, other);
16        out
17    }
18}
19
20impl FunctionalVec for &[u8] {
21    fn concat(&self, other: &[u8]) -> Vec<u8> {
22        let mut out = self.to_vec();
23        out.extend_from_slice(other);
24        out
25    }
26
27    fn concat_byte(&self, other: u8) -> Vec<u8> {
28        let mut out = self.to_vec();
29        Vec::<u8>::push(&mut out, other);
30        out
31    }
32}
33
34pub trait Conversions {
35    fn to_le_bytes(&self) -> Vec<u8>;
36}
37
38impl<const LEN: usize> Conversions for [u64; LEN] {
39    fn to_le_bytes(&self) -> Vec<u8> {
40        let mut out = Vec::with_capacity(LEN * 8);
41        for item in self {
42            out.extend_from_slice(&item.to_le_bytes());
43        }
44        out
45    }
46}
47
48impl<const LEN: usize> Conversions for [u32; LEN] {
49    fn to_le_bytes(&self) -> Vec<u8> {
50        let mut out = Vec::with_capacity(LEN * 4);
51        for item in self {
52            out.extend_from_slice(&item.to_le_bytes());
53        }
54        out
55    }
56}
57
58pub fn bytes_to_le_u32s(input: &[u8]) -> Vec<u32> {
59    let mut out = Vec::new();
60    for block in input.chunks(4) {
61        out.push(u32::from_le_bytes(block.try_into().unwrap()));
62    }
63    out
64}