aboutsummaryrefslogtreecommitdiff
path: root/src/primitive/string.rs
blob: 0d3e344484d757b4d6465dcfa7e65d03d65d52a2 (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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
extern crate byteorder;

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

use log::trace;

use crate::{error::ProtocolError, primitive, serialize::*, util};

use crate::serialize::VariantType;

impl Deserialize for char {
    fn parse(b: &[u8]) -> Result<(usize, Self), ProtocolError> {
        let (slen, qchar): (usize, u16) = u16::parse(&b[0..2])?;
        let qchar = char::from_u32(qchar as u32).ok_or(ProtocolError::CharError)?;

        Ok((slen, qchar))
    }
}

impl Serialize for char {
    fn serialize(&self) -> Result<Vec<u8>, ProtocolError> {
        let mut b = [0, 0];
        self.encode_utf16(&mut b);

        Ok(b[0].to_be_bytes().to_vec())
    }
}

impl VariantType for char {
    const TYPE: u32 = crate::primitive::QCHAR;
}

/// Strings are serialized as an i32 for the length in bytes, then the chars represented in UTF-16 in bytes.
///
/// Strings can only be serialized as UTF-8 null-terminated ByteArrays with (de)serialize_utf8().
impl Serialize for String {
    fn serialize(&self) -> Result<Vec<u8>, ProtocolError> {
        self.as_str().serialize()
    }
}

impl SerializeUTF8 for String {
    fn serialize_utf8(&self) -> Result<Vec<u8>, ProtocolError> {
        self.as_str().serialize_utf8()
    }
}

impl VariantType for String {
    const TYPE: u32 = primitive::QSTRING;
}

/// Strings are serialized as an i32 for the length in bytes, then the chars represented in UTF-16 in bytes.
///
/// Strings can only be serialized as UTF-8 null-terminated ByteArrays with (de)serialize_utf8().
impl Serialize for &str {
    fn serialize(&self) -> Result<Vec<u8>, ProtocolError> {
        let mut res = Vec::new();

        self.encode_utf16()
            .for_each(|i| res.extend(i.to_be_bytes().iter()));

        util::prepend_byte_len(&mut res);
        Ok(res)
    }
}

impl SerializeUTF8 for &str {
    fn serialize_utf8(&self) -> Result<Vec<u8>, ProtocolError> {
        let mut res: Vec<u8> = Vec::new();
        res.extend(self.bytes());
        util::prepend_byte_len(&mut res);
        Ok(res)
    }
}

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

        if len == -1 {
            return Ok((4, "".to_string()));
        }

        // length as usize
        let ulen = len as usize;
        trace!("parsed bytes: {:x?}", &b[0..ulen]);
        let mut pos: usize = 4;
        let mut chars: Vec<u16> = Vec::new();
        loop {
            // if position is behind the length plus our 4 bytes of the length we already parsed
            if pos >= (ulen + 4) {
                break;
            }
            let (slen, uchar) = u16::parse(&b[pos..(pos + 2)])?;
            chars.push(uchar);
            pos += slen;
        }

        let res: String = String::from_utf16(&chars).unwrap();
        trace!("parsed string: {}", res);
        Ok((pos, res))
    }
}

impl DeserializeUTF8 for String {
    fn parse_utf8(b: &[u8]) -> Result<(usize, Self), ProtocolError> {
        let (_, len) = i32::parse(&b[0..4])?;

        trace!(target: "primitive::String", "Parsing with length: {:?}, from bytes: {:x?}", len, &b[0..4]);

        if len <= 0 {
            return Ok((4, "".to_string()));
        }

        let ulen = len as usize;

        let mut res: String = String::from_utf8(b[4..(ulen + 4)].to_vec())?;
        trace!("parsed string: {}", res);

        // If the last byte is zero remove it
        // Receiving a string as bytearray will sometimes have
        // the string null terminated
        if res.ends_with('\u{0}') {
            let _ = res.pop();
        }

        trace!("parsed string after trunc: {}", res);
        trace!("parsed bytes: {:x?}", &b[0..ulen]);

        Ok((ulen + 4, res))
    }
}

#[test]
pub fn string_serialize() {
    let test_string: String = String::from("Configured");

    assert_eq!(
        test_string.serialize().unwrap(),
        [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_serialize_utf8() {
    let test_string: String = String::from("Configured");

    assert_eq!(
        test_string.serialize_utf8().unwrap(),
        [0, 0, 0, 10, 67, 111, 110, 102, 105, 103, 117, 114, 101, 100]
    );
}

#[test]
pub fn string_deserialize() {
    let test_bytes: &[u8] = &[
        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 (len, res) = String::parse(test_bytes).unwrap();
    assert_eq!(res, "Configured");
    assert_eq!(len, 24);
}

#[test]
pub fn string_deserialize_utf8() {
    let test_bytes: &[u8] = &[
        0, 0, 0, 10, 67, 111, 110, 102, 105, 103, 117, 114, 101, 100, 0, 0, 0, 1,
    ];
    let (len, res) = String::parse_utf8(test_bytes).unwrap();
    assert_eq!(len, 14);
    assert_eq!(res, "Configured");
}

#[test]
pub fn string_deserialize_utf8_null_terminated() {
    let test_bytes: &[u8] = &[
        0, 0, 0, 11, 67, 111, 110, 102, 105, 103, 117, 114, 101, 100, 0, 0, 0, 0, 1,
    ];
    let (len, res) = String::parse_utf8(test_bytes).unwrap();
    assert_eq!(len, 15);
    assert_eq!(res, "Configured");
}