aboutsummaryrefslogtreecommitdiff
path: root/src/primitive/networkid.rs
blob: 6eead7364d7e67ad62afea6744b62f0c632a9f68 (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
#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct NetworkId(pub i32);

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

use crate::serialize::UserType;

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

        res.append(&mut Self::NAME.serialize_utf8()?);
        res.extend(self.0.serialize()?);

        Ok(res)
    }
}

impl Deserialize for NetworkId {
    fn parse(b: &[u8]) -> Result<(usize, Self), ProtocolError> {
        let (size, value) = i32::parse(b)?;
        Ok((size, NetworkId(value)))
    }
}

impl From<i32> for NetworkId {
    fn from(value: i32) -> Self {
        NetworkId(value)
    }
}

impl std::ops::Deref for NetworkId {
    type Target = i32;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl UserType for NetworkId {
    const NAME: &str = "NetworkId";
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    pub fn networkid_parse_test() {
        let test_bytes: &[u8] = &[0, 0, 0, 1];
        let (len, res) = NetworkId::parse(test_bytes).unwrap();
        assert_eq!(len, test_bytes.len());
        assert_eq!(res, NetworkId(1));
    }

    #[test]
    pub fn networkid_serialize_test() {
        let res = NetworkId(1).serialize().unwrap();
        let expected_bytes: &[u8] = &[0, 0, 0, 9, 78, 101, 116, 119, 111, 114, 107, 73, 100, 0, 0, 0, 1];
        assert_eq!(res, expected_bytes);
    }
}