Skip to main content

moq_transport/coding/
location.rs

1use crate::coding::{Decode, DecodeError, Encode, EncodeError};
2
3#[derive(Default, Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
4pub struct Location {
5    pub group_id: u64,
6    pub object_id: u64,
7}
8
9impl Location {
10    pub fn new(group_id: u64, object_id: u64) -> Self {
11        Self {
12            group_id,
13            object_id,
14        }
15    }
16}
17
18impl Decode for Location {
19    fn decode<R: bytes::Buf>(r: &mut R) -> Result<Self, DecodeError> {
20        let group_id = u64::decode(r)?;
21        let object_id = u64::decode(r)?;
22        Ok(Location::new(group_id, object_id))
23    }
24}
25
26impl Encode for Location {
27    fn encode<W: bytes::BufMut>(&self, w: &mut W) -> Result<(), EncodeError> {
28        self.group_id.encode(w)?;
29        self.object_id.encode(w)?;
30        Ok(())
31    }
32}
33
34#[cfg(test)]
35mod tests {
36    use super::*;
37    use bytes::BytesMut;
38
39    #[test]
40    fn encode_decode() {
41        let mut buf = BytesMut::new();
42
43        let loc = Location::new(12345, 67890);
44        loc.encode(&mut buf).unwrap();
45
46        #[rustfmt::skip]
47        assert_eq!(
48            buf.to_vec(),
49            vec![
50                0x70, 0x39, // 12345 encoded as VarInt
51                0x80, 0x01, 0x09, 0x32 // 67890 encoded as VarInt
52            ]
53        );
54        let decoded = Location::decode(&mut buf).unwrap();
55        assert_eq!(decoded, loc);
56    }
57
58    #[test]
59    fn verify_ordering() {
60        let loc1 = Location::new(1, 2);
61        let loc2 = Location::new(1, 5);
62        let loc3 = Location::new(2, 1);
63        let loc4 = Location::new(2, 2);
64        let loc5 = Location::new(2, 6);
65        let loc6 = Location::new(2, 6);
66        assert!(loc1 < loc2);
67        assert!(loc1 <= loc2);
68        assert!(loc2 > loc1);
69        assert!(loc2 < loc3);
70        assert!(loc3 < loc4);
71        assert!(loc4 < loc5);
72        assert!(loc5 == loc6);
73        assert!(loc5 >= loc6);
74    }
75}