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

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

use crate::serialize::UserType;

impl Serialize for IdentityId {
    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 IdentityId {
    fn parse(b: &[u8]) -> Result<(usize, Self), ProtocolError> {
        let (size, value) = i32::parse(b)?;
        Ok((size, IdentityId(value)))
    }
}

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

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

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

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

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

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

    #[test]
    pub fn identityid_serialize_test() {
        let res = IdentityId(1).serialize().unwrap();
        let expected_bytes: &[u8] = &[
            0, 0, 0, 10, 73, 100, 101, 110, 116, 105, 116, 121, 73, 100, 0, 0, 0, 1,
        ];
        assert_eq!(res, expected_bytes);
    }
}