Skip to main content

rustflexstack/geonet/
gn_address.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2024 Fundació Privada Internet i Innovació Digital a Catalunya (i2CAT)
3
4use std::cmp::PartialEq;
5
6#[derive(Clone, Copy, Debug)]
7pub enum M {
8    GnUnicast,
9    GnMulticast,
10}
11
12impl M {
13    pub fn encode_to_address(&self) -> u64 {
14        match self {
15            M::GnUnicast => (0 << 7) << (8 * 7),
16            M::GnMulticast => (1 << 7) << (8 * 7),
17        }
18    }
19
20    pub fn decode_from_address(address: u64) -> Self {
21        // Bit 63 is the M (multicast/unicast) flag
22        if (address >> 63) & 1 == 1 {
23            M::GnMulticast
24        } else {
25            M::GnUnicast
26        }
27    }
28}
29
30#[derive(Clone, Copy, Debug)]
31pub enum ST {
32    Unknown,
33    Pedestrian,
34    Cyclist,
35    Moped,
36    Motorcycle,
37    PassengerCar,
38    Bus,
39    LightTruck,
40    HeavyTruck,
41    Trailer,
42    SpecialVehicle,
43    Tram,
44    RoadSideUnit,
45}
46
47impl ST {
48    pub fn encode_to_address(&self) -> u64 {
49        match self {
50            ST::Unknown => (0 << 2) << (8 * 7),
51            ST::Pedestrian => (1 << 2) << (8 * 7),
52            ST::Cyclist => (2 << 2) << (8 * 7),
53            ST::Moped => (3 << 2) << (8 * 7),
54            ST::Motorcycle => (4 << 2) << (8 * 7),
55            ST::PassengerCar => (5 << 2) << (8 * 7),
56            ST::Bus => (6 << 2) << (8 * 7),
57            ST::LightTruck => (7 << 2) << (8 * 7),
58            ST::HeavyTruck => (8 << 2) << (8 * 7),
59            ST::Trailer => (9 << 2) << (8 * 7),
60            ST::SpecialVehicle => (10 << 2) << (8 * 7),
61            ST::Tram => (11 << 2) << (8 * 7),
62            ST::RoadSideUnit => (12 << 2) << (8 * 7),
63        }
64    }
65
66    pub fn decode_from_address(address: u64) -> Self {
67        // Station type occupies bits 62-58 (bits 6-2 of the most significant byte)
68        // Bit 63 is M (manual/derived), so ST starts at bit 62
69        match (address >> (8 * 7 + 2)) & 0x1F {
70            0 => ST::Unknown,
71            1 => ST::Pedestrian,
72            2 => ST::Cyclist,
73            3 => ST::Moped,
74            4 => ST::Motorcycle,
75            5 => ST::PassengerCar,
76            6 => ST::Bus,
77            7 => ST::LightTruck,
78            8 => ST::HeavyTruck,
79            9 => ST::Trailer,
80            10 => ST::SpecialVehicle,
81            11 => ST::Tram,
82            12 => ST::RoadSideUnit,
83            _ => ST::Unknown,
84        }
85    }
86}
87
88#[derive(Clone, Copy, Debug)]
89
90pub struct MID {
91    mid: [u8; 6],
92}
93
94impl MID {
95    pub fn new(mid: [u8; 6]) -> Self {
96        MID { mid }
97    }
98
99    /// MID for GN over ITS-G5: the 48-bit MAC address of the ITS-G5
100    /// interface (ETSI TS 103 836-4-2 V2.1.1, clause 6.1).
101    pub fn from_its_g5_mac(mac_address: [u8; 6]) -> Self {
102        MID { mid: mac_address }
103    }
104
105    /// MID for GN over LTE-V2X: the 24-bit Source Layer 2 ID in octets 2-4
106    /// of the GN address, octets 5-7 set to zero (ETSI TS 103 836-4-3
107    /// V2.1.1, clause 5.2). `None` when `l2_id` does not fit in 24 bits.
108    pub fn from_lte_v2x_l2_id(l2_id: u32) -> Option<Self> {
109        if l2_id >= 1 << 24 {
110            return None;
111        }
112        let b = l2_id.to_be_bytes();
113        Some(MID {
114            mid: [b[1], b[2], b[3], 0, 0, 0],
115        })
116    }
117
118    /// The link-layer address carried in the MID field.
119    pub fn as_bytes(&self) -> [u8; 6] {
120        self.mid
121    }
122
123    pub fn encode_to_address(&self) -> u64 {
124        self.mid
125            .iter()
126            .fold(0u64, |address, &octet| (address << 8) | octet as u64)
127    }
128
129    pub fn decode_from_address(address: u64) -> Self {
130        let mut mid: [u8; 6] = [0; 6];
131        for (i, byte) in mid.iter_mut().enumerate() {
132            *byte = (address >> (8 * (5 - i))) as u8;
133        }
134        MID { mid }
135    }
136}
137
138#[derive(Clone, Copy, Debug)]
139
140pub struct GNAddress {
141    pub m: M,
142    pub st: ST,
143    pub mid: MID,
144}
145
146impl GNAddress {
147    pub fn new(m: M, st: ST, mid: MID) -> Self {
148        GNAddress { m, st, mid }
149    }
150
151    pub fn encode_to_int(&self) -> u64 {
152        self.m.encode_to_address() | self.st.encode_to_address() | self.mid.encode_to_address()
153    }
154
155    pub fn encode(&self) -> [u8; 8] {
156        self.encode_to_int().to_be_bytes()
157    }
158
159    pub fn decode(data: &[u8]) -> Self {
160        let as_number: u64 = u64::from_be_bytes([
161            data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7],
162        ]);
163        let m: M = M::decode_from_address(as_number);
164        let st: ST = ST::decode_from_address(as_number);
165        let mid: MID = MID::decode_from_address(as_number);
166        GNAddress { m, st, mid }
167    }
168}
169
170impl PartialEq for GNAddress {
171    fn eq(&self, other: &Self) -> bool {
172        self.encode_to_int() == other.encode_to_int()
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179
180    #[test]
181    fn m_encode_decode_unicast() {
182        let encoded = M::GnUnicast.encode_to_address();
183        let decoded = M::decode_from_address(encoded);
184        assert!(matches!(decoded, M::GnUnicast));
185    }
186
187    #[test]
188    fn m_encode_decode_multicast() {
189        let encoded = M::GnMulticast.encode_to_address();
190        let decoded = M::decode_from_address(encoded);
191        assert!(matches!(decoded, M::GnMulticast));
192    }
193
194    #[test]
195    fn st_encode_decode_all_variants() {
196        let variants = [
197            (ST::Unknown, 0),
198            (ST::Pedestrian, 1),
199            (ST::Cyclist, 2),
200            (ST::Moped, 3),
201            (ST::Motorcycle, 4),
202            (ST::PassengerCar, 5),
203            (ST::Bus, 6),
204            (ST::LightTruck, 7),
205            (ST::HeavyTruck, 8),
206            (ST::Trailer, 9),
207            (ST::SpecialVehicle, 10),
208            (ST::Tram, 11),
209            (ST::RoadSideUnit, 12),
210        ];
211        for (st, _) in &variants {
212            let encoded = st.encode_to_address();
213            let decoded = ST::decode_from_address(encoded);
214            // Check roundtrip: encode, then decode → same bit pattern
215            assert_eq!(decoded.encode_to_address(), st.encode_to_address());
216        }
217    }
218
219    #[test]
220    fn st_decode_unknown_value() {
221        // Unknown ST values (> 12) should map to Unknown
222        let addr = 0x1F_u64 << (8 * 7 + 2); // ST bits = 31
223        let decoded = ST::decode_from_address(addr);
224        assert!(matches!(decoded, ST::Unknown));
225    }
226
227    #[test]
228    fn mid_encode_decode_roundtrip() {
229        let mid = MID::new([0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF]);
230        let encoded = mid.encode_to_address();
231        let decoded = MID::decode_from_address(encoded);
232        assert_eq!(decoded.mid, [0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF]);
233    }
234
235    #[test]
236    fn mid_all_zeros() {
237        let mid = MID::new([0, 0, 0, 0, 0, 0]);
238        assert_eq!(mid.encode_to_address(), 0);
239    }
240
241    #[test]
242    fn gn_address_encode_decode_roundtrip() {
243        let addr = GNAddress::new(
244            M::GnUnicast,
245            ST::PassengerCar,
246            MID::new([0x00, 0x11, 0x22, 0x33, 0x44, 0x55]),
247        );
248        let bytes = addr.encode();
249        assert_eq!(bytes.len(), 8);
250        let decoded = GNAddress::decode(&bytes);
251        assert_eq!(addr, decoded);
252    }
253
254    #[test]
255    fn gn_address_equality() {
256        let a = GNAddress::new(M::GnUnicast, ST::Bus, MID::new([1, 2, 3, 4, 5, 6]));
257        let b = GNAddress::new(M::GnUnicast, ST::Bus, MID::new([1, 2, 3, 4, 5, 6]));
258        assert_eq!(a, b);
259    }
260
261    #[test]
262    fn gn_address_inequality_different_mid() {
263        let a = GNAddress::new(M::GnUnicast, ST::Bus, MID::new([1, 2, 3, 4, 5, 6]));
264        let b = GNAddress::new(M::GnUnicast, ST::Bus, MID::new([6, 5, 4, 3, 2, 1]));
265        assert_ne!(a, b);
266    }
267
268    #[test]
269    fn gn_address_inequality_different_m() {
270        let a = GNAddress::new(M::GnUnicast, ST::Bus, MID::new([1, 2, 3, 4, 5, 6]));
271        let b = GNAddress::new(M::GnMulticast, ST::Bus, MID::new([1, 2, 3, 4, 5, 6]));
272        assert_ne!(a, b);
273    }
274
275    #[test]
276    fn gn_address_encode_to_int_consistency() {
277        let addr = GNAddress::new(
278            M::GnMulticast,
279            ST::RoadSideUnit,
280            MID::new([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]),
281        );
282        let int_val = addr.encode_to_int();
283        let bytes = int_val.to_be_bytes();
284        assert_eq!(bytes, addr.encode());
285    }
286}