Skip to main content

twine_codec/dataset/
mesh_local_prefix.rs

1// Copyright (c) 2025 Jake Swensen
2// SPDX-License-Identifier: MPL-2.0
3//
4// This Source Code Form is subject to the terms of the Mozilla Public
5// License, v. 2.0. If a copy of the MPL was not distributed with this
6// file, You can obtain one at http://mozilla.org/MPL/2.0/.
7
8use twine_rs_macros::Tlv;
9
10const MESH_LOCAL_PREFIX_SIZE: usize = 8;
11
12#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Tlv)]
13#[tlv(tlv_type = 0x07, tlv_length = 8, derive_inner)]
14pub struct MeshLocalPrefix([u8; MESH_LOCAL_PREFIX_SIZE]);
15
16impl MeshLocalPrefix {
17    pub fn random_ula() -> Self {
18        let mut bytes = [0u8; MESH_LOCAL_PREFIX_SIZE];
19        bytes[0] = 0xfd; // ULA prefix
20        crate::fill_random_bytes(&mut bytes[1..]);
21        Self(bytes)
22    }
23}
24
25impl core::fmt::Display for MeshLocalPrefix {
26    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
27        let b = &self.0;
28
29        let g0 = ((b[0] as u16) << 8) | (b[1] as u16);
30        let g1 = ((b[2] as u16) << 8) | (b[3] as u16);
31        let g2 = ((b[4] as u16) << 8) | (b[5] as u16);
32        let g3 = ((b[6] as u16) << 8) | (b[7] as u16);
33
34        write!(f, "{g0:04x}:{g1:04x}:{g2:04x}:{g3:04x}::/64")
35    }
36}
37
38impl From<[u8; MESH_LOCAL_PREFIX_SIZE]> for MeshLocalPrefix {
39    fn from(value: [u8; MESH_LOCAL_PREFIX_SIZE]) -> Self {
40        Self(value)
41    }
42}
43
44#[cfg(test)]
45mod tests {
46    use super::*;
47
48    #[test]
49    fn display_mesh_local_prefix() {
50        let bytes = [0xfd, 0xe2, 0x2f, 0xdc, 0x94, 0x77, 0x9b, 0x16];
51        let prefix = MeshLocalPrefix::from(bytes);
52        assert_eq!(std::format!("{}", prefix), "fde2:2fdc:9477:9b16::/64");
53    }
54}