mqtt_protocol_core/mqtt/packet_id_manager.rs
1use crate::mqtt::packet::IsPacketId;
2/**
3 * MIT License
4 *
5 * Copyright (c) 2025 Takatoshi Kondo
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in all
15 * copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 * SOFTWARE.
24 */
25use crate::mqtt::result_code::MqttError;
26use crate::mqtt::value_allocator::ValueAllocator;
27
28pub struct PacketIdManager<T>
29where
30 T: IsPacketId,
31{
32 allocator: ValueAllocator<T>,
33}
34
35impl<T> PacketIdManager<T>
36where
37 T: IsPacketId,
38{
39 /// Create a new packet ID manager with valid IDs in range [1, T::max_value()]
40 pub fn new() -> Self {
41 Self {
42 allocator: ValueAllocator::new(T::one(), T::max_value()),
43 }
44 }
45
46 /// Acquire a new unique packet ID.
47 /// Returns `Ok(T)` if successful, `Err(MqttError)` if no IDs are available.
48 pub fn acquire_unique_id(&mut self) -> Result<T, MqttError> {
49 self.allocator
50 .allocate()
51 .ok_or(MqttError::PacketIdentifierFullyUsed)
52 }
53
54 /// Register a packet ID externally acquired or reused.
55 /// Returns `Ok(())` if successful, `Err(MqttError)` if the ID is already in use.
56 pub fn register_id(&mut self, packet_id: T) -> Result<(), MqttError> {
57 self.allocator
58 .use_value(packet_id)
59 .then_some(())
60 .ok_or(MqttError::PacketIdentifierConflict)
61 }
62
63 /// Check whether a packet ID is in use.
64 pub fn is_used_id(&self, packet_id: T) -> bool {
65 self.allocator.is_used(packet_id)
66 }
67
68 /// Release a previously acquired or registered packet ID.
69 pub fn release_id(&mut self, packet_id: T) {
70 self.allocator.deallocate(packet_id);
71 }
72
73 /// Clear all state: all packet IDs become available again.
74 pub fn clear(&mut self) {
75 self.allocator.clear();
76 }
77}