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>),
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,
{
fn data_callback(self: StdArc<Self>, data: Vec<u8>, handle: String, serv_type: ServiceType);
fn state_callback(
self: StdArc<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 {
fn start(self: StdArc<Self>) -> impl std::future::Future<Output = StdResult<()>> + Send;
fn stop(self: StdArc<Self>) -> impl std::future::Future<Output = StdResult<()>> + Send;
}
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)
}
})
}