use anyhow::{Context, Result};
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::os::unix::io::{FromRawFd, OwnedFd, RawFd};
use uds::tokio::UnixSeqpacketConn;
pub async fn read_json<T: DeserializeOwned>(conn: &mut UnixSeqpacketConn) -> Result<T> {
let mut buf = vec![0u8; 65536]; let bytes_read = conn
.recv(&mut buf)
.await
.context("Failed to read packet from socket")?;
buf.truncate(bytes_read);
serde_json::from_slice(&buf).context("Failed to parse JSON from packet")
}
pub async fn write_json<T: Serialize>(conn: &mut UnixSeqpacketConn, data: &T) -> Result<()> {
let json_bytes = serde_json::to_vec(data).context("Failed to serialize JSON")?;
conn.send(&json_bytes)
.await
.context("Failed to send JSON packet")?;
Ok(())
}
pub async fn read_json_with_fds<T: DeserializeOwned>(
conn: &mut UnixSeqpacketConn,
) -> Result<(T, Vec<OwnedFd>)> {
let mut buf = vec![0u8; 65536]; let mut fd_buf = vec![0i32; 250]; let (bytes_read, _truncated, fds_read) = conn
.recv_fds(&mut buf, &mut fd_buf)
.await
.context("Failed to read packet with FDs from socket")?;
#[allow(unsafe_code)]
let owned_fds: Vec<OwnedFd> = fd_buf[..fds_read]
.iter()
.map(|&raw_fd| unsafe { OwnedFd::from_raw_fd(raw_fd) })
.collect();
buf.truncate(bytes_read);
let data = serde_json::from_slice(&buf).context("Failed to parse JSON from packet")?;
Ok((data, owned_fds))
}
pub async fn write_json_with_fds<T: Serialize>(
conn: &mut UnixSeqpacketConn,
data: &T,
fds: &[RawFd],
) -> Result<()> {
let json_bytes = serde_json::to_vec(data).context("Failed to serialize JSON")?;
conn.send_fds(&json_bytes, fds)
.await
.context("Failed to send JSON packet with FDs")?;
Ok(())
}