58 lines
1.6 KiB
Rust
58 lines
1.6 KiB
Rust
use std::net::TcpStream;
|
|||
|
|
use std::os::unix::net::UnixStream;
|
||
|
|
use anyhow::Result;
|
||
|
|
use super::frame;
|
||
|
|
|
||
|
|
pub enum Connection {
|
||
|
|
Tcp(TcpStream),
|
||
|
|
Unix(UnixStream),
|
||
|
|
}
|
||
|
|
|
||
|
|
impl Connection {
|
||
|
|
pub fn connect_tcp(addr: &str) -> Result<Self> {
|
||
|
|
let stream = TcpStream::connect(addr)?;
|
||
|
|
stream.set_nodelay(true)?;
|
||
|
|
Ok(Connection::Tcp(stream))
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn connect_unix(path: &str) -> Result<Self> {
|
||
|
|
let stream = UnixStream::connect(path)?;
|
||
|
|
Ok(Connection::Unix(stream))
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn send<T: serde::Serialize>(&mut self, value: &T) -> Result<()> {
|
||
|
|
let data = frame::serialize_frame(value)?;
|
||
|
|
match self {
|
||
|
|
Connection::Tcp(ref mut s) => frame::write_frame(s, &data),
|
||
|
|
Connection::Unix(ref mut s) => frame::write_frame(s, &data),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn receive<T: serde::de::DeserializeOwned>(&mut self) -> Result<Option<T>> {
|
||
|
|
let data = match self {
|
||
|
|
Connection::Tcp(ref mut s) => frame::read_frame(s)?,
|
||
|
|
Connection::Unix(ref mut s) => frame::read_frame(s)?,
|
||
|
|
};
|
||
|
|
match data {
|
||
|
|
Some(bytes) => {
|
||
|
|
let value: T = frame::deserialize_frame(&bytes)?;
|
||
|
|
Ok(Some(value))
|
||
|
|
}
|
||
|
|
None => Ok(None),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn try_clone(&self) -> Result<Self> {
|
||
|
|
match self {
|
||
|
|
Connection::Tcp(s) => {
|
||
|
|
let cloned = s.try_clone()?;
|
||
|
|
Ok(Connection::Tcp(cloned))
|
||
|
|
}
|
||
|
|
Connection::Unix(s) => {
|
||
|
|
let cloned = s.try_clone()?;
|
||
|
|
Ok(Connection::Unix(cloned))
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|