use crate::mqtt::packet::IsPacketId;
use crate::mqtt::result_code::MqttError;
use crate::mqtt::ValueAllocator;
pub struct PacketIdManager<T>
where
T: IsPacketId,
{
allocator: ValueAllocator<T>,
}
impl<T> PacketIdManager<T>
where
T: IsPacketId,
{
pub fn new() -> Self {
Self {
allocator: ValueAllocator::new(T::one(), T::max_value()),
}
}
pub fn acquire_unique_id(&mut self) -> Result<T, MqttError> {
self.allocator
.allocate()
.ok_or(MqttError::PacketIdentifierFullyUsed)
}
pub fn register_id(&mut self, packet_id: T) -> Result<(), MqttError> {
self.allocator
.use_value(packet_id)
.then_some(())
.ok_or(MqttError::PacketIdentifierConflict)
}
pub fn is_used_id(&self, packet_id: T) -> bool {
self.allocator.is_used(packet_id)
}
pub fn release_id(&mut self, packet_id: T) {
self.allocator.deallocate(packet_id);
}
pub fn clear(&mut self) {
self.allocator.clear();
}
}