aboutsummaryrefslogtreecommitdiff
path: root/src/primitive/stringlist.rs
blob: 872f5be452a35e8e0a29a41e8368b1925b79c56e (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
extern crate byteorder;

use std::result::Result;
use std::vec::Vec;

use log::trace;

use crate::{deserialize::*, error::ProtocolError, serialize::*};

/// StringList are represented as a Vec of Strings
///
/// StringLists are serialized as an i32 of the amount of elements and then each element as a String
pub type StringList = Vec<String>;

impl Serialize for StringList {
    fn serialize(&self) -> Result<Vec<u8>, ProtocolError> {
        let len: i32 = self.len().try_into()?;
        let mut res: Vec<u8> = Vec::new();

        res.extend(len.to_be_bytes().iter());
        for x in self {
            res.extend(x.serialize()?);
        }

        return Ok(res);
    }
}

impl Deserialize for StringList {
    fn parse(b: &[u8]) -> Result<(usize, Self), ProtocolError> {
        let (_, len) = i32::parse(&b[0..4])?;
        trace!(target: "primitive::StringList", "Parsing with length: {:?}, from bytes: {:x?}", len, &b[0..4]);
        let mut res: StringList = StringList::new();

        let mut pos = 4;
        if len > 0 {
            for _ in 0..len {
                let (lpos, val) = String::parse(&b[pos..])?;
                pos += lpos;
                res.push(val);
            }
        }

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

#[test]
pub fn string_list_serialize() {
    let mut test_list = StringList::new();
    test_list.push("Configured".to_string());
    assert_eq!(
        test_list.serialize().unwrap(),
        [
            0, 0, 0, 1, 0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, 117, 0, 114, 0, 101,
            0, 100
        ]
    )
}

#[test]
pub fn string_list_deserialize() {
    let test_bytes: &[u8] = &[
        0, 0, 0, 1, 0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, 117, 0, 114, 0, 101, 0,
        100, 0, 0, 0, 1,
    ];
    let mut test_list = StringList::new();
    test_list.push("Configured".to_string());
    let (len, res) = StringList::parse(test_bytes).unwrap();
    assert_eq!(len, 28);
    assert_eq!(test_list, res);
}