use std::ffi::CString;
use std::path::Path;
use std::sync::{Condvar, Mutex, PoisonError};
use antfly_embedded_sys::{ANTFLY_OK, antfly_buffer, antfly_error_code, antfly_slice};
use crate::error::{Error, Result};
pub(crate) fn borrow_slice(bytes: &[u8]) -> antfly_slice {
if bytes.is_empty() {
antfly_slice {
ptr: std::ptr::null(),
len: 0,
}
} else {
antfly_slice {
ptr: bytes.as_ptr(),
len: bytes.len(),
}
}
}
pub(crate) fn path_has_suffix(path: &Path, suffix: &str) -> bool {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
path.as_os_str().as_bytes().ends_with(suffix.as_bytes())
}
#[cfg(not(unix))]
{
path.to_string_lossy().ends_with(suffix)
}
}
#[cfg(unix)]
pub(crate) fn path_to_cstring(path: &Path) -> Result<CString> {
use std::os::unix::ffi::OsStrExt;
CString::new(path.as_os_str().as_bytes()).map_err(|_| Error::InvalidArgument)
}
#[cfg(not(unix))]
pub(crate) fn path_to_cstring(path: &Path) -> Result<CString> {
let s = path.to_str().ok_or(Error::InvalidArgument)?;
CString::new(s).map_err(|_| Error::InvalidArgument)
}
pub(crate) unsafe fn take_buffer(mut buffer: antfly_buffer) -> Vec<u8> {
let out = if buffer.ptr.is_null() || buffer.len == 0 {
Vec::new()
} else {
unsafe { std::slice::from_raw_parts(buffer.ptr, buffer.len) }.to_vec()
};
unsafe { antfly_embedded_sys::antfly_buffer_free(&mut buffer) };
out
}
pub(crate) fn check(code: antfly_error_code) -> Result<()> {
if code == ANTFLY_OK {
Ok(())
} else {
Err(Error::from_native(code))
}
}
pub(crate) fn check_outcome(code: antfly_error_code) -> Result<()> {
if code == ANTFLY_OK {
Ok(())
} else {
Err(Error::from_native_with_receipt(code))
}
}
pub(crate) fn path_to_bytes(path: &Path) -> Vec<u8> {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
path.as_os_str().as_bytes().to_vec()
}
#[cfg(not(unix))]
{
path.to_string_lossy().into_owned().into_bytes()
}
}
struct GateState<T> {
handle: Option<*mut T>,
readers: u32,
closer_waiting: bool,
closer_active: bool,
}
pub(crate) struct HandleGate<T> {
state: Mutex<GateState<T>>,
cond: Condvar,
}
impl<T> HandleGate<T> {
pub(crate) fn new(handle: *mut T) -> HandleGate<T> {
HandleGate {
state: Mutex::new(GateState {
handle: Some(handle),
readers: 0,
closer_waiting: false,
closer_active: false,
}),
cond: Condvar::new(),
}
}
pub(crate) fn with_handle<R>(&self, f: impl FnOnce(*mut T) -> Result<R>) -> Result<R> {
let handle = {
let mut guard = self.state.lock().unwrap_or_else(PoisonError::into_inner);
loop {
if guard.closer_waiting || guard.closer_active {
guard = self
.cond
.wait(guard)
.unwrap_or_else(PoisonError::into_inner);
continue;
}
break;
}
match guard.handle {
Some(handle) => {
guard.readers += 1;
handle
}
None => return Err(Error::InvalidArgument),
}
};
struct ReaderSlot<'a, T>(&'a HandleGate<T>);
impl<T> Drop for ReaderSlot<'_, T> {
fn drop(&mut self) {
let mut guard = self.0.state.lock().unwrap_or_else(PoisonError::into_inner);
guard.readers -= 1;
if guard.readers == 0 {
self.0.cond.notify_all();
}
}
}
let _slot = ReaderSlot(self);
f(handle)
}
pub(crate) fn close(&self, close_fn: impl FnOnce(*mut T)) {
let mut guard = self.state.lock().unwrap_or_else(PoisonError::into_inner);
if guard.handle.is_none() {
return;
}
guard.closer_waiting = true;
while guard.readers > 0 || guard.closer_active {
guard = self
.cond
.wait(guard)
.unwrap_or_else(PoisonError::into_inner);
}
guard.closer_waiting = false;
let Some(handle) = guard.handle.take() else {
self.cond.notify_all();
return;
};
guard.closer_active = true;
drop(guard);
close_fn(handle);
let mut guard = self.state.lock().unwrap_or_else(PoisonError::into_inner);
guard.closer_active = false;
self.cond.notify_all();
}
pub(crate) fn is_open(&self) -> bool {
self.state
.lock()
.map(|guard| guard.handle.is_some())
.unwrap_or(false)
}
}