mod datagram;
pub use datagram::UnixDatagram;
use super::io;
use crate::{Result, SuspensionReason, blocking};
use std::{
io::{Read, Write},
net::Shutdown,
os::{fd::AsFd, unix::net::SocketAddr},
path::Path,
};
#[derive(Debug)]
pub struct UnixListener {
inner: std::os::unix::net::UnixListener,
}
#[derive(Debug)]
pub struct UnixStream {
inner: std::os::unix::net::UnixStream,
}
impl UnixListener {
pub fn bind(path: impl AsRef<Path>) -> Result<Self> {
let inner = std::os::unix::net::UnixListener::bind(path.as_ref()).map_err(|error| {
crate::Error::io("UnixListener bind", path.as_ref().display(), error)
})?;
io::checked(
"set nonblocking",
inner.as_fd(),
inner.set_nonblocking(true),
)?;
Ok(Self { inner })
}
pub fn accept(&self) -> Result<(UnixStream, SocketAddr)> {
let (inner, address) = io::operation(
self.inner.as_fd(),
zio::Interest::READABLE,
SuspensionReason::IoAccept,
|| self.inner.accept(),
)?;
io::checked(
"set nonblocking",
inner.as_fd(),
inner.set_nonblocking(true),
)?;
Ok((UnixStream { inner }, address))
}
}
impl UnixStream {
pub fn connect(path: impl AsRef<Path>) -> Result<Self> {
let path = path.as_ref().to_owned();
blocking::run_for(SuspensionReason::IoConnect, move || {
let inner = std::os::unix::net::UnixStream::connect(&path)
.map_err(|error| crate::Error::io("UnixStream connect", path.display(), error))?;
io::checked(
"set nonblocking",
inner.as_fd(),
inner.set_nonblocking(true),
)?;
Ok(Self { inner })
})?
}
pub fn pair() -> Result<(Self, Self)> {
let (left, right) = std::os::unix::net::UnixStream::pair()
.map_err(|error| crate::Error::io("UnixStream pair", "anonymous endpoints", error))?;
io::checked("set nonblocking", left.as_fd(), left.set_nonblocking(true))?;
io::checked(
"set nonblocking",
right.as_fd(),
right.set_nonblocking(true),
)?;
Ok((Self { inner: left }, Self { inner: right }))
}
pub fn read(&self, buffer: &mut [u8]) -> Result<usize> {
io::operation(
self.inner.as_fd(),
zio::Interest::READABLE,
SuspensionReason::IoRead,
|| (&self.inner).read(buffer),
)
}
pub fn write(&self, buffer: &[u8]) -> Result<usize> {
io::operation(
self.inner.as_fd(),
zio::Interest::WRITABLE,
SuspensionReason::IoWrite,
|| (&self.inner).write(buffer),
)
}
pub fn read_exact(&self, buffer: &mut [u8]) -> Result<()> {
io::read_exact(|part| self.read(part), buffer)
}
pub fn write_all(&self, buffer: &[u8]) -> Result<()> {
io::write_all(|part| self.write(part), buffer)
}
pub fn shutdown(&self, how: Shutdown) -> Result<()> {
io::checked(
"socket shutdown",
self.inner.as_fd(),
self.inner.shutdown(how),
)
}
}
#[cfg(test)]
#[path = "unix_test.rs"]
mod unix_test;