ugly_smart_lib 0.1.1

jonny's ugly smart lib for Rust
Documentation
//! src/tcp_pub.rs
//!
//! `tcp_pub` 是一个公共文件
//!
//! 它包含以下结构。
//! - ConnectionState 会话管理
//! - spawn_and_log_error 产生一个异步任务接口
//! - TcpFrameTrait 客户端和服务端特质
//! - 一些公共声明

use super::smart_pub::{MpscAsyncSender, StdArc, StdResult};

pub const SERVER_KEY: &'static str = "Server";
pub const CLIENT_KEY: &'static str = "Client";

/// 连接状态
#[derive(Debug)]
pub enum EConnectionState<T> {
    /// 正在连接
    Connecting,
    /// 正常连接
    Running(MpscAsyncSender<T>),
    // Running(MpscAsyncSender<(String, Vec<u8>)>),
    /// 中断
    Interrupt,
    /// 停止
    Stoped,
}

impl Default for EConnectionState<Vec<u8>> {
    fn default() -> Self {
        EConnectionState::Stoped
    }
}

impl Default for EConnectionState<(String, Vec<u8>)> {
    fn default() -> Self {
        EConnectionState::Stoped
    }
}

/// 服务类型
#[derive(Clone, Copy, PartialEq)]
pub enum ServiceType {
    /// 服务器
    Server,
    /// 客户端
    Client,
}

impl Default for ServiceType {
    fn default() -> Self {
        Self::Client
    }
}

impl From<i32> for ServiceType {
    fn from(value: i32) -> Self {
        match value {
            0 => ServiceType::Server,
            1 => ServiceType::Client,
            _ => Self::Client,
        }
    }
}

impl From<String> for ServiceType {
    fn from(value: String) -> Self {
        match &value as &str {
            SERVER_KEY => ServiceType::Server,
            CLIENT_KEY => ServiceType::Client,
            _ => ServiceType::Client,
        }
    }
}

impl std::fmt::Display for ServiceType {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::Server => {
                write!(f, "{}", SERVER_KEY)
            }
            Self::Client => {
                write!(f, "{}", CLIENT_KEY)
            }
        }
    }
}

impl std::fmt::Debug for ServiceType {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::Server => {
                write!(f, "{}", SERVER_KEY)
            }
            Self::Client => {
                write!(f, "{}", CLIENT_KEY)
            }
        }
    }
}

/// 回调函数特质
pub trait INetCallBack<T>
where
    Self: Send + Sync,
{
    /// 数据回调接口
    ///
    /// # Arguments
    /// * 'self' 自身对象的共享指针
    /// * 'data' 收到的数据
    /// * 'handle' 额外参数
    /// * 'serv_type' 服务类型
    ///
    /// # Returns
    /// * 无
    fn data_callback(self: StdArc<Self>, data: Vec<u8>, handle: String, serv_type: ServiceType);

    /// 连接状态回调接口
    ///
    /// # Arguments
    /// * 'self' 自身对象的共享指针
    /// * 'handle' 额外参数
    /// * 'state' 连接状态
    /// * 'serv_type' 服务类型
    ///
    /// # Returns
    /// * 无
    fn state_callback(
        self: StdArc<Self>,
        // &mut self,
        handle: String,
        state: EConnectionState<T>,
        serv_type: ServiceType,
    );
}

impl std::fmt::Display for dyn INetCallBack<Vec<u8>> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "CallBackTrait Display")
    }
}

impl std::fmt::Debug for dyn INetCallBack<Vec<u8>> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "CallBackTrait Debug")
    }
}

impl std::fmt::Display for dyn INetCallBack<(String, Vec<u8>)> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "CallBackTrait Display")
    }
}

impl std::fmt::Debug for dyn INetCallBack<(String, Vec<u8>)> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "CallBackTrait Debug")
    }
}

/// 客户端和服务端特质
pub trait INetwork {
    // type ReturnFuture; // = impl std::future::Future<Output = StdResult<()>> + Send;

    /// 实现开启服务或连接
    ///
    /// # Arguments
    /// * 'self' 自身对象的共享指针
    ///
    /// # Returns
    /// * future trait,用于异步调用
    fn start(self: StdArc<Self>) -> impl std::future::Future<Output = StdResult<()>> + Send;

    /// 实现停止服务或断开连接
    ///
    /// # Arguments
    /// * 'self' 自身对象的共享指针
    ///
    /// # Returns
    /// * future trait,用于异步调用
    fn stop(self: StdArc<Self>) -> impl std::future::Future<Output = StdResult<()>> + Send;
}

/*
/// 实现 输出连接状态 打印
///
/// # Arguments
/// * 'addr' - 连接地址
/// * 'state' - 连接状态
///
/// # Returns
/// * 无
///
/// # Examples
/// ```rust
/// use smart_lib::tcp_pub;
/// fn main() {
/// 	let e:tcp_pub::EConnectionState = tcp_pub::EConnectionState::Connecting;
/// 	let addr:String = "127.0.0.1:80".to_string();
/// 	tcp_pub::inspect_connection_state(&addr, &e);
/// }
/// ```
///
pub fn inspect_connection_state(addr: &String, state: &EConnectionState) {
    match state {
        EConnectionState::Connecting => tklog::info!(addr, "connection connecting."),
        EConnectionState::Running(_) => tklog::info!(addr, "connection normal running."),
        EConnectionState::Interrupt => tklog::error!(addr, "connection interrrupt."),
        EConnectionState::Stoped => tklog::fatal!(addr, "connection stoped."),
    }
}
*/

/// 产生一个异步任务
pub fn spawn_and_log_error<F>(fut: F) -> tokio::task::JoinHandle<()>
where
    F: std::future::Future<Output = StdResult<()>> + Send + 'static,
{
    tokio::spawn(async move {
        if let Err(e) = fut.await {
            tracing::error!(e)
        }
    })
}