Skip to main content

twine_codec/dataset/
pskc.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
8#[cfg(any(test, feature = "alloc"))]
9use alloc::vec::Vec;
10
11use twine_rs_macros::Tlv;
12
13const PSKC_MAX_SIZE: usize = 16;
14
15/// A Thread PSKc
16#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Tlv)]
17#[tlv(tlv_type = 0x04, tlv_length = 16, derive_inner)]
18pub struct Pskc([u8; PSKC_MAX_SIZE]);
19
20impl Pskc {
21    pub fn random() -> Self {
22        let mut bytes = [0u8; PSKC_MAX_SIZE];
23        crate::fill_random_bytes(&mut bytes);
24        Self(bytes)
25    }
26}
27
28impl core::fmt::Display for Pskc {
29    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
30        for byte in &self.0 {
31            write!(f, "{:02x}", byte)?;
32        }
33
34        Ok(())
35    }
36}
37
38#[cfg(any(test, feature = "alloc"))]
39impl From<Pskc> for Vec<u8> {
40    fn from(value: Pskc) -> Self {
41        value.0.to_vec()
42    }
43}
44
45impl From<Pskc> for u128 {
46    fn from(value: Pskc) -> Self {
47        u128::from_be_bytes(value.0)
48    }
49}
50
51impl From<u128> for Pskc {
52    fn from(pskc: u128) -> Self {
53        Self(pskc.to_be_bytes())
54    }
55}
56
57impl From<[u8; PSKC_MAX_SIZE]> for Pskc {
58    fn from(value: [u8; PSKC_MAX_SIZE]) -> Self {
59        Self(value)
60    }
61}