scsir/command/shortcut/mode/
page_wrapper.rs

1use super::{DescriptorStorage, DescriptorType, HeaderStorage, HeaderType};
2
3#[derive(Clone, Debug)]
4pub struct PageWrapper<Page: ModePage> {
5    pub header: HeaderStorage,
6    pub descriptors: Vec<DescriptorStorage>,
7    pub page: Page,
8}
9
10pub trait ModePage {
11    fn new() -> Self
12    where
13        Self: Sized;
14
15    fn from_bytes(bytes: &[u8]) -> (Self, &[u8])
16    where
17        Self: Sized;
18
19    fn to_bytes(&self) -> Vec<u8>;
20}
21
22impl<Page: ModePage> PageWrapper<Page> {
23    pub fn from_bytes(
24        header_type: HeaderType,
25        descriptor_type: DescriptorType,
26        bytes: &[u8],
27    ) -> Self {
28        let (header, bytes) = HeaderStorage::from_bytes(header_type, bytes);
29
30        let block_descriptor_length = header.block_descriptor_length();
31
32        let mut descriptors = vec![];
33        let (mut descriptor_bytes, bytes) =
34            bytes.split_at(usize::min(block_descriptor_length as usize, bytes.len()));
35
36        while !descriptor_bytes.is_empty() {
37            let descriptor;
38            (descriptor, descriptor_bytes) =
39                DescriptorStorage::from_bytes(descriptor_type, descriptor_bytes);
40            descriptors.push(descriptor);
41        }
42
43        Self {
44            header,
45            descriptors,
46            page: Page::from_bytes(bytes).0,
47        }
48    }
49
50    pub fn to_bytes(&self) -> Vec<u8> {
51        let mut bytes = vec![];
52        bytes.extend_from_slice(&self.header.to_bytes());
53
54        for item in &self.descriptors {
55            bytes.extend_from_slice(&item.to_bytes());
56        }
57
58        bytes.extend_from_slice(&self.page.to_bytes());
59
60        bytes
61    }
62}