byte_array_ops/security/
vec.rs

1//! Vec-like operations for ByteArray
2//!
3//! Provides explicit access to length, emptiness, and indexed access
4
5use crate::model::ByteArray;
6
7impl ByteArray {
8    /// Returns the number of bytes in the array
9    pub fn len(&self) -> usize {
10        self.bytes.len()
11    }
12
13    /// Returns true if there are no bytes in the array
14    pub fn is_empty(&self) -> bool {
15        self.bytes.is_empty()
16    }
17
18    /// Returns a reference to the byte at the given index, or None if out of bounds
19    pub fn get(&self, index: usize) -> Option<&u8> {
20        self.bytes.get(index)
21    }
22
23    /// Truncate function similar to [`alloc::vec::Vec::truncate`]
24    pub fn truncate(&mut self, _len: usize) {
25        unimplemented!(
26            "truncate is not available yet due to reallocation and data remnance concerns"
27        )
28    }
29}
30
31#[cfg(test)]
32mod tests_hardened_only {
33    use super::*;
34    use alloc::vec;
35
36    #[test]
37    fn test_len() {
38        let arr = ByteArray::from_hex("ffab12345bc").expect("error converting");
39
40        assert_eq!(arr.len(), 6);
41    }
42
43    #[test]
44    fn test_is_empty() {
45        let arr = ByteArray::default();
46        assert_eq!(arr.is_empty(), true);
47
48        let arr = ByteArray::from_hex("bb").expect("error converting");
49
50        assert_eq!(arr.is_empty(), false);
51    }
52
53    #[test]
54    fn test_get() {
55        let arr: ByteArray = vec![0xaa, 0xbb, 0xcc].into();
56
57        assert_eq!(arr.get(0), Some(&0xaa));
58        assert_eq!(arr.get(1), Some(&0xbb));
59        assert_eq!(arr.get(2), Some(&0xcc));
60        assert_eq!(arr.get(3), None);
61    }
62
63    #[test]
64    #[should_panic(
65        expected = "truncate is not available yet due to reallocation and data remnance concerns"
66    )]
67    fn test_truncate_panics() {
68        let mut arr: ByteArray = vec![0x01, 0x02, 0x03, 0x04, 0x05].into();
69        arr.truncate(3);
70    }
71}