rs_connections/
conn.rs

1use std::{any::Any, sync::Arc};
2
3use async_trait::async_trait;
4use rs_event_emitter::Handle;
5
6use crate::{
7    base::{ConnectionBaseInterface, ConnectionInterface, Emitter},
8    ConnectError,
9};
10
11pub trait ConnAssemble: ConnectionInterface + Emitter + ConnectionBaseInterface {
12    fn clone_box(&self) -> Box<dyn ConnAssemble>;
13}
14
15pub struct Conn(Box<dyn ConnAssemble>);
16
17impl Clone for Conn {
18    fn clone(&self) -> Self {
19        Self(self.0.clone_box())
20    }
21}
22
23impl Conn {
24    pub fn new<T: ConnAssemble + 'static>(conn: T) -> Self {
25        Conn(Box::new(conn))
26    }
27}
28
29#[async_trait]
30impl ConnectionInterface for Conn {
31    async fn connect(&mut self) -> Result<bool, ConnectError> {
32        self.0.connect().await
33    }
34    async fn disconnect(&mut self) -> Result<bool, ConnectError> {
35        self.0.disconnect().await
36    }
37    async fn send(&mut self, data: &[u8]) -> Result<bool, ConnectError> {
38        self.0.send(data).await
39    }
40    async fn receive(&mut self) -> Result<Vec<u8>, ()> {
41        self.0.receive().await
42    }
43}
44
45impl Emitter for Conn {
46    fn emit(&mut self, event: &'static str, data: Box<dyn Any>) -> () {
47        self.0.emit(event, data);
48    }
49
50    fn on(&mut self, event: &'static str, callback: Arc<dyn Handle>) -> () {
51        self.0.on(event, callback);
52    }
53
54    fn off(&mut self, event: &'static str, callback: Arc<dyn Handle>) -> () {
55        self.0.off(event, callback);
56    }
57}
58
59impl ConnectionBaseInterface for Conn {
60    fn get_address(&self) -> String {
61        self.0.get_address()
62    }
63}