smux_rust 0.2.1

A simple multiplexing library for Rust, inspired by xtaci/smux
use std::time::Duration;

/// smux 会话配置
#[derive(Debug, Clone)]
pub struct Config {
    /// SMUX 协议版本,支持 1 或 2
    pub version: u8,
    /// 是否禁用保活
    pub keep_alive_disabled: bool,
    /// 保活间隔
    pub keep_alive_interval: Duration,
    /// 保活超时
    pub keep_alive_timeout: Duration,
    /// 最大帧大小
    pub max_frame_size: usize,
    /// 最大接收缓冲区大小
    pub max_receive_buffer: usize,
    /// 最大流缓冲区大小
    pub max_stream_buffer: usize,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            version: 1,
            keep_alive_disabled: false,
            keep_alive_interval: Duration::from_secs(10),
            keep_alive_timeout: Duration::from_secs(30),
            max_frame_size: 32768,
            max_receive_buffer: 4_194_304, // 4MB
            max_stream_buffer: 65536,      // 64KB
        }
    }
}

impl Config {
    /// 创建默认配置
    pub fn default_config() -> Self {
        Self::default()
    }

    /// 验证配置的有效性
    pub fn verify(&self) -> Result<(), String> {
        if self.version != 1 && self.version != 2 {
            return Err("unsupported protocol version".to_string());
        }
        if !self.keep_alive_disabled {
            if self.keep_alive_interval.as_secs() == 0 {
                return Err("keep-alive interval must be positive".to_string());
            }
            if self.keep_alive_timeout < self.keep_alive_interval {
                return Err("keep-alive timeout must be larger than keep-alive interval".to_string());
            }
        }
        if self.max_frame_size == 0 {
            return Err("max frame size must be positive".to_string());
        }
        if self.max_frame_size > 65535 {
            return Err("max frame size must not be larger than 65535".to_string());
        }
        if self.max_receive_buffer == 0 {
            return Err("max receive buffer must be positive".to_string());
        }
        if self.max_stream_buffer == 0 {
            return Err("max stream buffer must be positive".to_string());
        }
        if self.max_stream_buffer > self.max_receive_buffer {
            return Err("max stream buffer must not be larger than max receive buffer".to_string());
        }
        if self.max_stream_buffer > i32::MAX as usize {
            return Err("max stream buffer cannot be larger than 2147483647".to_string());
        }
        Ok(())
    }
}