aboutsummaryrefslogtreecommitdiff
path: root/src/primitive/variantmap.rs
blob: d43028c659d107dd650bc37af2decf755457804d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
use std::collections::HashMap;
use std::{convert::TryInto, vec::Vec};

use failure::Error;

use log::trace;

use crate::Deserialize;
use crate::Serialize;

use crate::primitive::Variant;
use crate::util;

/// VariantMaps are represented as a HashMap with String as key and Variant as value
///
/// They are serialized as the amount of keys as an i32 then for each entry a String and a Variant.
pub type VariantMap = HashMap<String, Variant>;

impl Serialize for VariantMap {
    fn serialize<'a>(&'a self) -> Result<Vec<u8>, Error> {
        let mut res: Vec<u8> = Vec::new();

        for (k, v) in self {
            res.extend(k.serialize()?);
            res.extend(v.serialize()?);
        }

        let len: i32 = self.len().try_into()?;
        util::insert_bytes(0, &mut res, &mut len.to_be_bytes());

        return Ok(res);
    }
}

impl Deserialize for VariantMap {
    fn parse(b: &[u8]) -> Result<(usize, Self), Error> {
        let (_, len) = i32::parse(&b[0..4])?;
        trace!(target: "primitive::VariantMap", "Parsing VariantMap with {:?} elements", len);

        let mut pos: usize = 4;
        let mut map = VariantMap::new();
        for _ in 0..len {
            trace!(target: "primitive::VariantMap", "Parsing entry name");
            let (nlen, name) = String::parse(&b[pos..])?;
            pos += nlen;

            trace!(target: "primitive::VariantMap", "Parsing entry: {:?} with len {:?}", name, &b[(pos)..(pos + 4)]);
            let (vlen, value) = Variant::parse(&b[(pos)..])?;
            pos += vlen;

            map.insert(name, value);
        }

        return Ok((pos, map));
    }
}