symqtt 0.1.1

Synchronous MQTT 3.1.1/5.0 client — blocking API, no async runtime
Documentation
//! Bidirectional topic alias management for MQTT 5.0 connections.
//!
//! Topic aliases reduce bandwidth by replacing repeated topic strings with
//! short integer identifiers. This module manages both outbound (client→server)
//! and inbound (server→client) alias tables.

use std::collections::HashMap;

use super::error::Error;

/// Outbound topic alias manager (client → server).
///
/// Maintains a topic→alias mapping. Capacity is set by the server's
/// `topic_alias_maximum` from CONNACK.
pub struct OutboundTopicAliases {
    /// topic → alias (1-based)
    map: HashMap<String, u16>,
    max: u16,
    next: u16,
}

impl OutboundTopicAliases {
    /// Create with capacity from server CONNACK `topic_alias_maximum`.
    /// If max=0, all resolve() calls will return None (disabled).
    pub fn new(max: u16) -> Self {
        Self {
            max,
            next: 1, // aliases are 1-based
            map: HashMap::with_capacity(max as usize),
        }
    }

    /// Attempt to resolve a topic to an alias.
    ///
    /// Returns:
    /// - `Some((alias, true))` — existing alias found, send with empty topic + alias
    /// - `Some((alias, false))` — new alias assigned, send with topic + alias (registration)
    /// - `None` — alias table disabled or full, send normally without alias
    pub fn resolve(&mut self, topic: &str) -> Option<(u16, bool)> {
        if self.max == 0 {
            return None;
        }
        if let Some(&alias) = self.map.get(topic) {
            return Some((alias, true)); // existing
        }
        // Try to allocate a new alias
        if self.next <= self.max {
            let alias = self.next;
            self.next += 1;
            self.map.insert(topic.to_string(), alias);
            Some((alias, false)) // new registration
        } else {
            None // table full
        }
    }

    /// Reset the alias table (must be called on new connection).
    pub fn reset(&mut self, new_max: u16) {
        self.map.clear();
        self.max = new_max;
        self.next = 1;
    }
}

/// Inbound topic alias manager (server → client).
///
/// Capacity is set by the client's `topic_alias_maximum` sent in CONNECT.
pub struct InboundTopicAliases {
    /// alias (1-based index) → topic. Index 0 = alias 1.
    table: Vec<Option<String>>,
}

impl InboundTopicAliases {
    /// Create with capacity from client's CONNECT `topic_alias_maximum`.
    pub fn new(max: u16) -> Self {
        Self {
            table: vec![None; max as usize],
        }
    }

    /// Resolve an inbound PUBLISH's topic using alias information.
    ///
    /// Rules [MQTTv5-3.3.2.3.4]:
    /// - topic non-empty + alias present: update mapping, return topic
    /// - topic empty + alias present: lookup mapping, return stored topic
    /// - topic non-empty + no alias: return topic as-is
    /// - topic empty + no alias: protocol error (handled by codec)
    /// - alias = 0 or alias > max: protocol error
    pub fn resolve(&mut self, topic: &str, alias: Option<u16>) -> Result<String, Error> {
        let Some(alias) = alias else {
            // No alias, use topic directly
            return Ok(topic.to_string());
        };

        if alias == 0 || alias as usize > self.table.len() {
            return Err(Error::TopicAliasInvalid(alias));
        }

        let idx = (alias - 1) as usize;

        if !topic.is_empty() {
            // Registration: store topic for this alias
            self.table[idx] = Some(topic.to_string());
            Ok(topic.to_string())
        } else {
            // Lookup: retrieve previously stored topic
            self.table[idx].clone().ok_or(Error::TopicAliasInvalid(alias))
        }
    }

    /// Reset the alias table (must be called on new connection).
    pub fn reset(&mut self, new_max: u16) {
        self.table.clear();
        self.table.resize(new_max as usize, None);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn outbound_disabled_when_max_zero() {
        let mut aliases = OutboundTopicAliases::new(0);
        assert_eq!(aliases.resolve("foo/bar"), None);
    }

    #[test]
    fn outbound_register_and_reuse() {
        let mut aliases = OutboundTopicAliases::new(10);
        let result = aliases.resolve("sensor/temp");
        assert_eq!(result, Some((1, false)));
        let result = aliases.resolve("sensor/temp");
        assert_eq!(result, Some((1, true)));
    }

    #[test]
    fn outbound_multiple_topics() {
        let mut aliases = OutboundTopicAliases::new(10);
        assert_eq!(aliases.resolve("a"), Some((1, false)));
        assert_eq!(aliases.resolve("b"), Some((2, false)));
        assert_eq!(aliases.resolve("a"), Some((1, true)));
        assert_eq!(aliases.resolve("b"), Some((2, true)));
    }

    #[test]
    fn outbound_full_returns_none() {
        let mut aliases = OutboundTopicAliases::new(2);
        assert_eq!(aliases.resolve("a"), Some((1, false)));
        assert_eq!(aliases.resolve("b"), Some((2, false)));
        assert_eq!(aliases.resolve("c"), None);
        assert_eq!(aliases.resolve("a"), Some((1, true)));
    }

    #[test]
    fn outbound_reset() {
        let mut aliases = OutboundTopicAliases::new(2);
        aliases.resolve("a");
        aliases.reset(3);
        assert_eq!(aliases.resolve("a"), Some((1, false)));
    }

    #[test]
    fn inbound_no_alias_passes_through() {
        let mut aliases = InboundTopicAliases::new(10);
        assert_eq!(aliases.resolve("foo/bar", None).unwrap(), "foo/bar");
    }

    #[test]
    fn inbound_register_and_lookup() {
        let mut aliases = InboundTopicAliases::new(10);
        assert_eq!(aliases.resolve("sensor/temp", Some(1)).unwrap(), "sensor/temp");
        assert_eq!(aliases.resolve("", Some(1)).unwrap(), "sensor/temp");
    }

    #[test]
    fn inbound_alias_zero_is_error() {
        let mut aliases = InboundTopicAliases::new(10);
        assert!(aliases.resolve("foo", Some(0)).is_err());
    }

    #[test]
    fn inbound_alias_exceeds_max_is_error() {
        let mut aliases = InboundTopicAliases::new(5);
        assert!(aliases.resolve("foo", Some(6)).is_err());
    }

    #[test]
    fn inbound_unregistered_alias_lookup_is_error() {
        let mut aliases = InboundTopicAliases::new(10);
        assert!(aliases.resolve("", Some(3)).is_err());
    }

    #[test]
    fn inbound_reset() {
        let mut aliases = InboundTopicAliases::new(5);
        aliases.resolve("foo", Some(1)).unwrap();
        aliases.reset(3);
        assert!(aliases.resolve("", Some(1)).is_err());
    }
}