mqtt_protocol_core/mqtt/packet/
packet_id.rs

1/**
2 * MIT License
3 *
4 * Copyright (c) 2025 Takatoshi Kondo
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24use num_traits::{Bounded, One, PrimInt};
25use serde::Serialize;
26use std::fmt::{Debug, Display};
27use std::hash::Hash;
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}