use std::ffi::c_void;
use std::fmt;
use std::marker::PhantomData;
use std::ptr::{self, NonNull};
use std::sync::atomic::{AtomicPtr, Ordering};
use crate::error::{check, Error, ErrorCode, Result};
use crate::fnptr::FnPtr;
use crate::host::Host;
use crate::sys::AnvilChange;
#[must_use = "dropping a Change removes the change; keep it in the plugin, or call keep()"]
pub struct Change {
handle: Option<NonNull<AnvilChange>>,
}
unsafe impl Send for Change {}
unsafe impl Sync for Change {}
impl Change {
pub(crate) fn from_raw(handle: *mut AnvilChange) -> Self {
Self {
handle: NonNull::new(handle),
}
}
pub fn as_raw(&self) -> *mut AnvilChange {
self.handle.map_or(ptr::null_mut(), NonNull::as_ptr)
}
pub fn remove(mut self) -> Result<()> {
remove_handle(self.handle.take())
}
pub fn keep(mut self) {
self.handle = None;
}
}
impl Drop for Change {
fn drop(&mut self) {
let _ = remove_handle(self.handle.take());
}
}
impl fmt::Debug for Change {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Change").field(&self.as_raw()).finish()
}
}
fn remove_handle(handle: Option<NonNull<AnvilChange>>) -> Result<()> {
let (Some(handle), Some(host)) = (handle, Host::current()) else {
return Ok(());
};
let Some(remove) = host.c_api().remove else {
return Ok(());
};
let result = unsafe { remove(host.raw_plugin(), handle.as_ptr()) };
match check(result, || "remove") {
Err(error) if error.code() == ErrorCode::NotFound => Ok(()),
other => other,
}
}
fn remove_slot(slot: &AtomicPtr<AnvilChange>) -> Result<()> {
remove_handle(NonNull::new(slot.swap(ptr::null_mut(), Ordering::AcqRel)))
}
pub struct FunctionHook<F: FnPtr> {
next: AtomicPtr<c_void>,
change: AtomicPtr<AnvilChange>,
_function: PhantomData<F>,
}
impl<F: FnPtr> FunctionHook<F> {
pub const fn new() -> Self {
Self {
next: AtomicPtr::new(ptr::null_mut()),
change: AtomicPtr::new(ptr::null_mut()),
_function: PhantomData,
}
}
pub fn next(&self) -> Option<F> {
let raw = self.next.load(Ordering::Acquire);
(!raw.is_null()).then(|| unsafe { F::from_raw(raw) })
}
pub fn is_active(&self) -> bool {
!self.change.load(Ordering::Acquire).is_null()
}
pub fn remove(&self) -> Result<()> {
remove_slot(&self.change)
}
pub(crate) fn claim(&self, call: &'static str) -> Result<()> {
if self.is_active() {
return Err(Error::new(
ErrorCode::InvalidArgument,
format!("{call}: the hook object already holds a change; remove() it first"),
));
}
Ok(())
}
pub(crate) fn next_slot(&self) -> *mut *mut c_void {
self.next.as_ptr()
}
pub(crate) fn set_change(&self, change: *mut AnvilChange) {
self.change.store(change, Ordering::Release);
}
}
impl<F: FnPtr> Default for FunctionHook<F> {
fn default() -> Self {
Self::new()
}
}
impl<F: FnPtr> fmt::Debug for FunctionHook<F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FunctionHook")
.field("next", &self.next.load(Ordering::Relaxed))
.field("active", &self.is_active())
.finish()
}
}
pub struct PointerSwap {
previous: AtomicPtr<c_void>,
change: AtomicPtr<AnvilChange>,
}
impl PointerSwap {
pub const fn new() -> Self {
Self {
previous: AtomicPtr::new(ptr::null_mut()),
change: AtomicPtr::new(ptr::null_mut()),
}
}
pub fn previous(&self) -> *mut c_void {
self.previous.load(Ordering::Acquire)
}
pub fn is_active(&self) -> bool {
!self.change.load(Ordering::Acquire).is_null()
}
pub fn remove(&self) -> Result<()> {
remove_slot(&self.change)
}
pub(crate) fn claim(&self) -> Result<()> {
if self.is_active() {
return Err(Error::new(
ErrorCode::InvalidArgument,
"swap_pointer: the swap object already holds a change; remove() it first",
));
}
Ok(())
}
pub(crate) fn previous_slot(&self) -> *mut *mut c_void {
self.previous.as_ptr()
}
pub(crate) fn set_change(&self, change: *mut AnvilChange) {
self.change.store(change, Ordering::Release);
}
}
impl Default for PointerSwap {
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for PointerSwap {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PointerSwap")
.field("previous", &self.previous())
.field("active", &self.is_active())
.finish()
}
}