#[cfg(any(target_os = "linux", target_os = "android"))]
use std::collections::VecDeque;
use std::io;
#[cfg(unix)]
use std::os::fd::OwnedFd;
#[cfg(any(target_os = "linux", target_os = "android"))]
use std::os::fd::{AsFd, BorrowedFd};
#[cfg(windows)]
use std::os::windows::io::OwnedHandle;
#[cfg(any(target_os = "linux", target_os = "android"))]
use memmap2::MmapMut;
pub use tilo_shm::Mapping;
#[cfg(unix)]
pub type Sealed = OwnedFd;
#[cfg(windows)]
pub type Sealed = OwnedHandle;
pub fn sealed_blob(name: &str, bytes: &[u8]) -> io::Result<Sealed> {
tilo_shm::from_bytes(name, bytes)
}
#[cfg(any(target_os = "linux", target_os = "android"))]
pub struct RingWriter {
fd: OwnedFd,
map: MmapMut,
len: usize,
outstanding: VecDeque<(u64, usize, usize)>,
head: usize,
}
#[cfg(any(target_os = "linux", target_os = "android"))]
impl RingWriter {
pub fn create(len: usize) -> io::Result<Self> {
let file = tilo_shm::create("tilo-render-ring", len as u64)?;
tilo_shm::seal_sizes(&file)?;
let map = tilo_shm::map_writable(&file)?;
Ok(Self {
fd: file.into(),
map,
len,
outstanding: VecDeque::new(),
head: 0,
})
}
pub fn fd(&self) -> BorrowedFd<'_> {
self.fd.as_fd()
}
pub fn len(&self) -> usize {
self.len
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
pub fn busy(&self) -> bool {
!self.outstanding.is_empty()
}
pub fn write(&mut self, sequence: u64, record: &[u8]) -> Option<usize> {
let len = record.len();
if len == 0 || len > self.len {
return None;
}
let start = self.place(len)?;
let end = start.checked_add(len)?;
let ring: &mut [u8] = &mut self.map;
ring.get_mut(start..end)?.copy_from_slice(record);
self.outstanding.push_back((sequence, start, end));
self.head = end;
Some(start)
}
fn place(&self, len: usize) -> Option<usize> {
let Some(&(_, oldest, _)) = self.outstanding.front() else {
return Some(if self.head.checked_add(len)? <= self.len {
self.head
} else {
0
});
};
let head = self.head;
if head >= oldest {
if head.checked_add(len)? <= self.len {
return Some(head);
}
return (len <= oldest).then_some(0);
}
(head.checked_add(len)? <= oldest).then_some(head)
}
pub fn release(&mut self, sequence: u64) {
while self
.outstanding
.front()
.is_some_and(|(seq, _, _)| *seq <= sequence)
{
self.outstanding.pop_front();
}
}
pub fn reset(&mut self) {
self.outstanding.clear();
self.head = 0;
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
pub struct SharedMemory {
fd: OwnedFd,
map: MmapMut,
}
#[cfg(any(target_os = "linux", target_os = "android"))]
impl SharedMemory {
pub fn create(name: &str, len: usize) -> io::Result<Self> {
let file = tilo_shm::create(name, len as u64)?;
tilo_shm::seal_sizes(&file)?;
let map = tilo_shm::map_writable(&file)?;
Ok(Self {
fd: file.into(),
map,
})
}
pub fn fd(&self) -> BorrowedFd<'_> {
self.fd.as_fd()
}
pub fn as_mut_slice(&mut self) -> &mut [u8] {
&mut self.map
}
}