gcd_rs/record/
descriptor.rs

1//! Composed of two records, the record descriptor type and descryptor values
2//! are separated in two record, for some reason.
3//!
4//! A descriptor id have the format 0xABBB, A is the kind, B is the id. The
5//! kind could be:
6//! 0..4 => , with "1 >> kind" is the data size.
7//!
8//! 4 => A variable data size, the next 2 bytes after the descritod type is the
9//! size. But this need more investigation.
10//!
11//! 5 => End of the list, possibly only ID 0x003 is valid.
12//!
13//!
14//! The order or descriptors seems to be irrelevant.
15
16//TODO doc this
17
18use crate::{RecordHeader, RECORD_HEADER_LEN};
19use byteorder::ByteOrder;
20use serde::{Deserialize, Serialize};
21use std::fmt::{Display, Formatter};
22use std::io::{Error, ErrorKind, Result};
23
24pub mod descriptor_data;
25pub mod descriptor_type;
26
27use descriptor_data::DescriptorData;
28use descriptor_type::DescriptorType;
29
30#[derive(Debug, PartialEq, Hash, Eq, Clone, Serialize, Deserialize)]
31pub enum DescriptorTypeRecord {
32    Simple(Vec<DescriptorType>),
33}
34
35impl Display for DescriptorTypeRecord {
36    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
37        match self {
38            DescriptorTypeRecord::Simple(x) => {
39                write!(f, "DescriptorTypeRecord:Simple(len : {})", x.len())
40            }
41        }
42    }
43}
44
45impl DescriptorTypeRecord {
46    pub fn new<F, B>(file: &mut F, lenght: u16) -> Result<Self>
47    where
48        F: std::io::Read,
49        B: ByteOrder,
50    {
51        if lenght % 2 != 0 {
52            return Err(Error::new(
53                ErrorKind::InvalidInput,
54                "Record Descriptor type size need to be multiple of 2",
55            ));
56        }
57
58        let mut data = vec![0u8; lenght as usize];
59        file.read_exact(&mut data)?;
60
61        // Obs for each Other sized, we allocate 2 bytes more then necessary.
62        // Is very rare to have a Other sized, so the shrink is realy necessary?
63        let mut descriptors = Vec::with_capacity(lenght as usize / 2);
64
65        let mut current = data.as_slice();
66        while current.len() != 0 {
67            let (next, descriptor_type) =
68                DescriptorType::from_raw::<B>(current)?;
69            descriptors.push(descriptor_type);
70            current = next;
71        }
72        Ok(DescriptorTypeRecord::Simple(descriptors))
73    }
74    pub fn len(&self) -> usize {
75        match self {
76            DescriptorTypeRecord::Simple(descs) => descs.len(),
77        }
78    }
79    pub fn data_len(&self) -> u16 {
80        match self {
81            DescriptorTypeRecord::Simple(descs) => {
82                descs.iter().map(|x| x.data_len()).sum::<u16>()
83            }
84        }
85    }
86    pub fn iter(&self) -> std::slice::Iter<DescriptorType> {
87        match self {
88            DescriptorTypeRecord::Simple(descs) => descs.iter(),
89        }
90    }
91    pub fn iter_mut(&mut self) -> std::slice::IterMut<DescriptorType> {
92        match self {
93            DescriptorTypeRecord::Simple(descs) => descs.iter_mut(),
94        }
95    }
96}
97
98impl Default for DescriptorTypeRecord {
99    fn default() -> Self {
100        Self::Simple(vec![])
101    }
102}
103
104#[derive(Debug, PartialEq, Hash, Eq, Clone, Serialize, Deserialize)]
105pub enum DescriptorRecord {
106    Simple(Vec<DescriptorData>),
107}
108impl Display for DescriptorRecord {
109    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
110        match self {
111            DescriptorRecord::Simple(x) => {
112                write!(f, "DescriptorRecord:Simple(len : {})", x.len())
113            }
114        }
115    }
116}
117
118impl DescriptorRecord {
119    pub fn new<F, B>(
120        file: &mut F,
121        lenght: u16,
122        desc_type: &DescriptorTypeRecord,
123    ) -> Result<Self>
124    where
125        F: std::io::Read,
126        B: ByteOrder,
127    {
128        // Check if Descriptor Type record expect this data size
129        if desc_type.data_len() != lenght {
130            return Err(Error::new(
131                ErrorKind::InvalidInput,
132                "Record Descriptor data is Invalid/Unexpected",
133            ));
134        }
135
136        //read the descriptor data
137        let mut data = vec![0u8; lenght as usize];
138        file.read_exact(&mut data)?;
139
140        let mut current = data.as_slice();
141        let descriptors = desc_type
142            .iter()
143            .map(|x| {
144                let (next, desc_data) =
145                    DescriptorData::from_raw::<B>(x, current)?;
146                current = next;
147                Ok(desc_data)
148            })
149            .collect::<Result<_>>()?;
150
151        if current.len() != 0 {
152            panic!("Programing Error on Descriptor Data parsing");
153        }
154
155        Ok(DescriptorRecord::Simple(descriptors))
156    }
157    pub fn iter(&self) -> std::slice::Iter<DescriptorData> {
158        match self {
159            DescriptorRecord::Simple(descs) => descs.iter(),
160        }
161    }
162    pub fn iter_mut(&mut self) -> std::slice::IterMut<DescriptorData> {
163        match self {
164            DescriptorRecord::Simple(descs) => descs.iter_mut(),
165        }
166    }
167    pub fn record_type_len(&self) -> u16 {
168        match self {
169            DescriptorRecord::Simple(x) => {
170                x.iter().map(|x| x.descriptor_type().len()).sum()
171            }
172        }
173    }
174    pub fn record_data_len(&self) -> u16 {
175        match self {
176            DescriptorRecord::Simple(x) => x.iter().map(|x| x.len()).sum(),
177        }
178    }
179    pub fn record_type_to_raw<'a, B: ByteOrder>(
180        &self,
181        data: &'a mut [u8],
182    ) -> Result<&'a mut [u8]> {
183        //write header
184        RecordHeader::DescriptorType(self.record_type_len())
185            .to_raw::<B>(data)?;
186
187        //write record body
188        let mut current = &mut data[RECORD_HEADER_LEN..];
189        for desc in self.iter() {
190            current = desc.descriptor_type().to_raw::<B>(current)?;
191        }
192
193        Ok(current)
194    }
195
196    pub fn record_data_to_raw<'a, B: ByteOrder>(
197        &self,
198        data: &'a mut [u8],
199    ) -> Result<&'a mut [u8]> {
200        //write header
201        RecordHeader::DescriptorData(self.record_data_len())
202            .to_raw::<B>(data)?;
203
204        //write record body
205        let mut current = &mut data[RECORD_HEADER_LEN..];
206        for desc in self.iter() {
207            current = desc.to_raw::<B>(current).unwrap();
208        }
209
210        Ok(current)
211    }
212}