1use crate::error::DmapError;
8use crate::record::Record;
9use crate::types::{DmapField, DmapType};
10use indexmap::IndexMap;
11
12#[derive(Debug, PartialEq, Clone)]
13pub struct DmapRecord {
14 pub data: IndexMap<String, DmapField>,
15}
16
17impl Record<'_> for DmapRecord {
18 fn inner(self) -> IndexMap<String, DmapField> {
19 self.data
20 }
21 fn get(&self, key: &str) -> Option<&DmapField> {
22 self.data.get(key)
23 }
24 fn keys(&self) -> Vec<&String> {
25 self.data.keys().collect()
26 }
27 fn new(fields: &mut IndexMap<String, DmapField>) -> Result<DmapRecord, DmapError> {
28 Ok(DmapRecord {
29 data: fields.to_owned(),
30 })
31 }
32 fn is_metadata_field(_name: &str) -> bool {
33 true
34 }
35 fn to_bytes(&self) -> Result<Vec<u8>, DmapError> {
36 let mut data_bytes: Vec<u8> = vec![];
37 let mut num_scalars: i32 = 0;
38 let mut num_vectors: i32 = 0;
39
40 for (name, val) in self.data.iter() {
42 if let x @ DmapField::Scalar(_) = val {
43 data_bytes.extend(name.as_bytes());
44 data_bytes.extend([0]); data_bytes.append(&mut x.as_bytes());
46 num_scalars += 1;
47 }
48 }
49 for (name, val) in self.data.iter() {
51 if let x @ DmapField::Vector(_) = val {
52 data_bytes.extend(name.as_bytes());
53 data_bytes.extend([0]); data_bytes.append(&mut x.as_bytes());
55 num_vectors += 1;
56 }
57 }
58 let mut bytes: Vec<u8> = vec![];
59 bytes.extend((65537_i32).as_bytes()); bytes.extend((data_bytes.len() as i32 + 16).as_bytes()); bytes.extend(num_scalars.as_bytes());
62 bytes.extend(num_vectors.as_bytes());
63 bytes.append(&mut data_bytes); Ok(bytes)
65 }
66}
67
68impl TryFrom<&mut IndexMap<String, DmapField>> for DmapRecord {
69 type Error = DmapError;
70
71 fn try_from(value: &mut IndexMap<String, DmapField>) -> Result<Self, Self::Error> {
72 DmapRecord::new(value)
73 }
74}
75
76impl TryFrom<IndexMap<String, DmapField>> for DmapRecord {
77 type Error = DmapError;
78
79 fn try_from(mut value: IndexMap<String, DmapField>) -> Result<Self, Self::Error> {
80 DmapRecord::new(&mut value)
81 }
82}