mqtt_protocol_core/mqtt/packet/
packet_id.rs

1use core::fmt::{Debug, Display};
2use core::hash::Hash;
3/**
4 * MIT License
5 *
6 * Copyright (c) 2025 Takatoshi Kondo
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in all
16 * copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 * SOFTWARE.
25 */
26use num_traits::{Bounded, One, PrimInt};
27use serde::Serialize;
28
29/// Packet ID types with associated buffer operations
30pub trait IsPacketId:
31    PrimInt + One + Bounded + Debug + Display + Hash + Eq + Serialize + 'static
32{
33    /// Fixed-size buffer type
34    type Buffer: AsRef<[u8]> + AsMut<[u8]> + Clone + Default + Eq;
35
36    /// Convert packet ID to fixed-size buffer
37    fn to_buffer(&self) -> Self::Buffer;
38
39    /// Parse packet ID from buffer
40    fn from_buffer(buf: &[u8]) -> Self;
41}
42
43impl IsPacketId for u16 {
44    type Buffer = [u8; 2];
45
46    fn to_buffer(&self) -> Self::Buffer {
47        self.to_be_bytes()
48    }
49
50    fn from_buffer(buf: &[u8]) -> Self {
51        if buf.len() >= 2 {
52            u16::from_be_bytes([buf[0], buf[1]])
53        } else {
54            0
55        }
56    }
57}
58
59impl IsPacketId for u32 {
60    type Buffer = [u8; 4];
61
62    fn to_buffer(&self) -> Self::Buffer {
63        self.to_be_bytes()
64    }
65
66    fn from_buffer(buf: &[u8]) -> Self {
67        if buf.len() >= 4 {
68            u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]])
69        } else {
70            0
71        }
72    }
73}