use super::*;
pub(crate) const WRITE_FRAME_DEADLINE: Duration = Duration::from_secs(5);
pub(crate) fn write_frame_blocking(stream: &mut UnixStream, frame: &[u8]) -> bool {
write_frame_blocking_with_deadline(
stream,
frame,
std::time::Instant::now() + WRITE_FRAME_DEADLINE,
)
}
pub(super) fn write_frame_bounded(
stream: &mut UnixStream,
frame: &[u8],
deadline: Instant,
) -> bool {
use std::os::fd::AsRawFd;
let fd = stream.as_raw_fd();
let mut written = 0;
while written < frame.len() {
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return false;
}
let mut pfd = libc::pollfd {
fd,
events: libc::POLLOUT,
revents: 0,
};
let timeout_ms = remaining.as_millis().clamp(1, i32::MAX as u128) as i32;
let r = unsafe { libc::poll(&mut pfd, 1, timeout_ms) };
if r < 0 {
if std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted {
continue;
}
return false;
}
if r == 0 {
return false;
}
if pfd.revents & (libc::POLLERR | libc::POLLNVAL) != 0 {
return false;
}
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return false;
}
if stream
.set_write_timeout(Some(remaining.max(Duration::from_millis(1))))
.is_err()
{
return false;
}
match stream.write(&frame[written..]) {
Ok(0) => return false,
Ok(n) => written += n,
Err(e)
if matches!(
e.kind(),
std::io::ErrorKind::Interrupted
| std::io::ErrorKind::WouldBlock
| std::io::ErrorKind::TimedOut
) => {}
Err(_) => return false,
}
}
true
}
pub(super) fn write_frame_blocking_with_deadline(
stream: &mut impl Write,
frame: &[u8],
deadline: std::time::Instant,
) -> bool {
let mut written = 0;
while written < frame.len() {
match stream.write(&frame[written..]) {
Ok(0) => return false,
Ok(n) => written += n,
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {
if std::time::Instant::now() > deadline {
return false;
}
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
if std::time::Instant::now() > deadline {
return false;
}
std::thread::sleep(Duration::from_millis(1));
}
Err(_) => return false,
}
}
true
}