stream-tungstenite 0.6.1

A streaming implementation of the Tungstenite WebSocket protocol
Documentation
//! Unified connection context used by handshake and extension code.
use std::collections::HashMap;

/// Unified connection context
#[derive(Debug, Clone, Default)]
pub struct ConnectionContext {
    pub connection_id: u64,
    pub reconnect_count: u64,
    pub is_reconnection: bool,
    /// Current attempt number (1-based for `Handshake::new`; 0 for Default)
    pub attempt: u32,
    pub metadata: HashMap<String, String>,
}

impl ConnectionContext {
    /// Create a new context with a specific connection id (attempt starts at 1)
    #[must_use]
    pub fn new(connection_id: u64) -> Self {
        Self {
            connection_id,
            reconnect_count: 0,
            is_reconnection: false,
            attempt: 1,
            metadata: HashMap::new(),
        }
    }

    /// Set reconnect count (updates `is_reconnection` accordingly)
    #[must_use]
    pub const fn with_reconnect_count(mut self, count: u64) -> Self {
        self.reconnect_count = count;
        self.is_reconnection = count > 0;
        self
    }

    /// Set attempt number
    #[must_use]
    pub const fn with_attempt(mut self, attempt: u32) -> Self {
        self.attempt = attempt;
        self
    }

    /// Add metadata
    #[must_use]
    pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// Insert or update metadata
    pub fn put_metadata(&mut self, key: impl Into<String>, value: impl Into<String>) {
        self.metadata.insert(key.into(), value.into());
    }

    /// Get metadata
    #[must_use]
    pub fn get_metadata(&self, key: &str) -> Option<&String> {
        self.metadata.get(key)
    }

    /// Update connection id and reconnect count
    pub fn update(&mut self, connection_id: u64, reconnect_count: u64) {
        self.connection_id = connection_id;
        self.reconnect_count = reconnect_count;
        self.is_reconnection = reconnect_count > 0;
    }
}