Add protocol impelemtation for tcp

Signed-off-by: trivernis <trivernis@protonmail.com>
pull/18/head
trivernis 3 years ago
parent b55c6e526b
commit cff9b07e76
Signed by: Trivernis
GPG Key ID: DFFFCC2C7A02DB45

@ -1,3 +1,5 @@
mod tcp;
use crate::prelude::IPCResult;
use async_trait::async_trait;
use tokio::io::{AsyncRead, AsyncWrite};
@ -14,9 +16,9 @@ pub trait AsyncStreamProtocolListener: Sized {
type RemoteAddressType;
type Stream: AsyncProtocolStream;
async fn bind(address: Self::AddressType) -> IPCResult<Self>;
async fn protocol_bind(address: Self::AddressType) -> IPCResult<Self>;
async fn accept(&self) -> IPCResult<(Self::Stream, Self::RemoteAddressType)>;
async fn protocol_accept(&self) -> IPCResult<(Self::Stream, Self::RemoteAddressType)>;
}
#[async_trait]
@ -25,7 +27,7 @@ pub trait AsyncProtocolStream: AsyncRead + AsyncWrite + Sized + Send + Sync {
type OwnedSplitReadHalf: AsyncRead + Send + Sync;
type OwnedSplitWriteHalf: AsyncWrite + Send + Sync;
async fn connect(address: Self::AddressType) -> IPCResult<Self>;
async fn protocol_connect(address: Self::AddressType) -> IPCResult<Self>;
async fn into_split(self) -> IPCResult<(Self::OwnedSplitReadHalf, Self::OwnedSplitWriteHalf)>;
async fn protocol_into_split(self) -> (Self::OwnedSplitReadHalf, Self::OwnedSplitWriteHalf);
}

@ -0,0 +1,50 @@
use crate::prelude::IPCResult;
use crate::protocol::{AsyncProtocolStream, AsyncStreamProtocol, AsyncStreamProtocolListener};
use async_trait::async_trait;
use std::net::SocketAddr;
use tokio::net::tcp::{OwnedReadHalf, OwnedWriteHalf};
use tokio::net::{TcpListener, TcpStream};
pub struct TcpProtocol;
#[async_trait]
impl AsyncStreamProtocol for TcpProtocol {
type Listener = TcpListener;
type Stream = TcpStream;
}
#[async_trait]
impl AsyncStreamProtocolListener for TcpListener {
type AddressType = SocketAddr;
type RemoteAddressType = SocketAddr;
type Stream = TcpStream;
async fn protocol_bind(address: Self::AddressType) -> IPCResult<Self> {
let listener = TcpListener::bind(address).await?;
Ok(listener)
}
async fn protocol_accept(&self) -> IPCResult<(Self::Stream, Self::RemoteAddressType)> {
let connection = self.accept().await?;
Ok(connection)
}
}
#[async_trait]
impl AsyncProtocolStream for TcpStream {
type AddressType = SocketAddr;
type OwnedSplitReadHalf = OwnedReadHalf;
type OwnedSplitWriteHalf = OwnedWriteHalf;
async fn protocol_connect(address: Self::AddressType) -> IPCResult<Self> {
let stream = TcpStream::connect(address).await?;
Ok(stream)
}
async fn protocol_into_split(self) -> (Self::OwnedSplitReadHalf, Self::OwnedSplitWriteHalf) {
self.into_split()
}
}
Loading…
Cancel
Save