use super::HasHrTimer;
use super::HrTimer;
use super::HrTimerCallback;
use super::HrTimerCallbackContext;
use super::HrTimerHandle;
use super::HrTimerMode;
use super::HrTimerPointer;
use super::RawHrTimerCallback;
use crate::prelude::*;
use core::ptr::NonNull;
pub struct BoxHrTimerHandle<T, A>
where
T: HasHrTimer<T>,
A: crate::alloc::Allocator,
{
pub(crate) inner: NonNull<T>,
_p: core::marker::PhantomData<A>,
}
unsafe impl<T, A> HrTimerHandle for BoxHrTimerHandle<T, A>
where
T: HasHrTimer<T>,
A: crate::alloc::Allocator,
{
fn cancel(&mut self) -> bool {
let timer_ptr = unsafe { <T as HasHrTimer<T>>::raw_get_timer(self.inner.as_ptr()) };
unsafe { HrTimer::<T>::raw_cancel(timer_ptr) }
}
}
impl<T, A> Drop for BoxHrTimerHandle<T, A>
where
T: HasHrTimer<T>,
A: crate::alloc::Allocator,
{
fn drop(&mut self) {
self.cancel();
drop(unsafe { Box::<T, A>::from_raw(self.inner.as_ptr()) })
}
}
impl<T, A> HrTimerPointer for Pin<Box<T, A>>
where
T: 'static,
T: Send + Sync,
T: HasHrTimer<T>,
T: for<'a> HrTimerCallback<Pointer<'a> = Pin<Box<T, A>>>,
A: crate::alloc::Allocator,
{
type TimerMode = <T as HasHrTimer<T>>::TimerMode;
type TimerHandle = BoxHrTimerHandle<T, A>;
fn start(
self,
expires: <<T as HasHrTimer<T>>::TimerMode as HrTimerMode>::Expires,
) -> Self::TimerHandle {
let inner =
unsafe { NonNull::new_unchecked(Box::into_raw(Pin::into_inner_unchecked(self))) };
unsafe { T::start(inner.as_ptr(), expires) };
BoxHrTimerHandle {
inner,
_p: core::marker::PhantomData,
}
}
}
impl<T, A> RawHrTimerCallback for Pin<Box<T, A>>
where
T: 'static,
T: HasHrTimer<T>,
T: for<'a> HrTimerCallback<Pointer<'a> = Pin<Box<T, A>>>,
A: crate::alloc::Allocator,
{
type CallbackTarget<'a> = Pin<&'a mut T>;
unsafe extern "C" fn run(ptr: *mut bindings::hrtimer) -> bindings::hrtimer_restart {
let timer_ptr = ptr.cast::<super::HrTimer<T>>();
let data_ptr = unsafe { T::timer_container_of(timer_ptr) };
let data_mut_ref = unsafe { Pin::new_unchecked(&mut *data_ptr) };
let context = unsafe { HrTimerCallbackContext::from_raw(timer_ptr) };
T::run(data_mut_ref, context).into_c()
}
}