use std::{marker::PhantomData, ops::Deref, panic::Location};
use crate::bindings::{
vlib_main_t, vlib_worker_thread_barrier_release, vlib_worker_thread_barrier_sync_int,
};
pub mod sync;
#[repr(transparent)]
pub struct MainRef(foreign_types::Opaque);
impl MainRef {
pub unsafe fn from_ptr_mut<'a>(ptr: *mut vlib_main_t) -> &'a mut Self {
unsafe { &mut *(ptr as *mut _) }
}
pub fn as_ptr(&self) -> *mut vlib_main_t {
self as *const _ as *mut _
}
pub fn thread_index(&self) -> u16 {
unsafe { (*self.as_ptr()).thread_index }
}
#[track_caller]
pub fn barrier_sync(&self) -> BarrierGuard<'_> {
assert_eq!(
self.thread_index(),
0,
"Barrier can only be taken on the VPP main thread"
);
unsafe {
vlib_worker_thread_barrier_sync_int(
self.as_ptr(),
Location::caller().file_as_c_str().as_ptr(),
);
}
BarrierGuard {
vm: self,
_phantom: PhantomData,
}
}
}
#[must_use = "if unused the barrier will immediately be released"]
pub struct BarrierGuard<'vm> {
vm: &'vm MainRef,
_phantom: PhantomData<*mut ()>,
}
impl Deref for BarrierGuard<'_> {
type Target = BarrierHeldMainRef;
fn deref(&self) -> &Self::Target {
unsafe { &*(self.vm as *const MainRef as *const BarrierHeldMainRef) }
}
}
impl Drop for BarrierGuard<'_> {
fn drop(&mut self) {
unsafe { vlib_worker_thread_barrier_release(self.vm.as_ptr()) }
}
}
#[repr(transparent)]
pub struct BarrierHeldMainRef(MainRef);
impl BarrierHeldMainRef {
pub unsafe fn from_ptr_mut<'a>(ptr: *mut vlib_main_t) -> &'a mut Self {
unsafe {
debug_assert!((*ptr).thread_index == 0);
&mut *(ptr as *mut _)
}
}
}
impl Deref for BarrierHeldMainRef {
type Target = MainRef;
fn deref(&self) -> &Self::Target {
&self.0
}
}