use std::io;
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use std::process::{Child, Stdio};
use windows_sys::Win32::Foundation::{DUPLICATE_SAME_ACCESS, DuplicateHandle};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
use super::super::{
Activity, Descriptor, SharedAudio,
doorbell::Doorbell,
errors::{TRANSFER, invalid},
realtime::{Ring, RingDescriptor},
};
pub struct Sender;
pub struct Receiver;
impl Sender {
pub fn new() -> io::Result<(Self, Stdio)> {
Ok((Self, Stdio::null()))
}
pub fn send(&self, memory: &SharedAudio, child: &Child) -> io::Result<u64> {
duplicate(memory.memory.handle(), child)
}
pub fn send_activity(&self, activity: &Activity, child: &Child) -> io::Result<u64> {
duplicate(activity.memory.handle(), child)
}
pub fn send_ring(&self, ring: &Ring, child: &Child) -> io::Result<Vec<u64>> {
let mut tokens = vec![duplicate(ring.control_memory().handle(), child)?];
for lane in ring.lane_audio() {
tokens.push(duplicate(lane.memory.handle(), child)?);
}
tokens.push(duplicate(&ring.doorbell().event, child)?);
Ok(tokens)
}
}
fn duplicate(section: &OwnedHandle, child: &Child) -> io::Result<u64> {
let mut handle = std::ptr::null_mut();
let result = unsafe {
DuplicateHandle(
GetCurrentProcess(),
section.as_raw_handle(),
child.as_raw_handle(),
&mut handle,
0,
0,
DUPLICATE_SAME_ACCESS,
)
};
if result == 0 {
return Err(io::Error::last_os_error());
}
Ok(handle as usize as u64)
}
impl Receiver {
pub fn take_from_stdin() -> io::Result<Self> {
Ok(Self)
}
pub unsafe fn receive(&self, descriptor: Descriptor, token: u64) -> io::Result<SharedAudio> {
unsafe { SharedAudio::open(take(token)?, descriptor) }
}
pub unsafe fn receive_activity(&self, token: u64) -> io::Result<Activity> {
unsafe { Activity::open(take(token)?) }
}
}
impl Receiver {
pub unsafe fn receive_ring(
&self,
descriptor: RingDescriptor,
tokens: &[u64],
) -> io::Result<Ring> {
let [control, lanes @ .., event] = tokens else {
return Err(invalid(TRANSFER));
};
let control = unsafe { take(*control) }?;
let lanes = lanes
.iter()
.map(|&token| unsafe { take(token) })
.collect::<io::Result<_>>()?;
let doorbell = Doorbell {
event: unsafe { take(*event) }?,
};
unsafe { Ring::open(descriptor, control, lanes, doorbell) }
}
}
unsafe fn take(token: u64) -> io::Result<OwnedHandle> {
if token == 0 || token == u64::MAX {
return Err(invalid(TRANSFER));
}
Ok(unsafe { OwnedHandle::from_raw_handle(token as usize as _) })
}