use crate::{runtime, LazyCell};
use core::{
cell::UnsafeCell,
fmt::{self, Debug, Formatter},
};
pub struct InterruptCell<T> {
inner: UnsafeCell<T>,
thread_id: usize,
}
impl<T> InterruptCell<T> {
pub const fn new_with_threadid(value: T, thread_id: usize) -> Self {
Self { inner: UnsafeCell::new(value), thread_id }
}
pub fn new(value: T) -> Self {
let thread_id = unsafe { runtime::_runtime_threadid_ZhZIZBv4() };
Self::new_with_threadid(value, thread_id)
}
pub fn scope<F, FR>(&self, scope: F) -> FR
where
F: FnOnce(&mut T) -> FR,
{
let thread_id = unsafe { runtime::_runtime_threadid_ZhZIZBv4() };
assert_eq!(thread_id, self.thread_id, "cannot access local cell from another thread");
let mut scope = Some(scope);
let mut result: Option<FR> = None;
let mut call_scope = || {
let scope = scope.take().expect("missing scope function");
let result_ = unsafe { self.raw(scope) };
result = Some(result_);
};
unsafe { runtime::_runtime_interruptsafe_1l52Ge5e(&mut call_scope) };
result.expect("implementation scope did not set result value")
}
pub unsafe fn raw<F, FR>(&self, scope: F) -> FR
where
F: FnOnce(&mut T) -> FR,
{
let inner_ptr = self.inner.get();
let value = inner_ptr.as_mut().expect("unexpected NULL pointer inside cell");
scope(value)
}
}
impl<T> InterruptCell<LazyCell<T>> {
pub fn lazy_scope<F, FR>(&self, scope: F) -> FR
where
F: FnOnce(&mut T) -> FR,
{
self.scope(|lazy| lazy.scope_mut(scope))
}
}
impl<T> Debug for InterruptCell<T>
where
T: Debug,
{
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let thread_id = unsafe { runtime::_runtime_threadid_ZhZIZBv4() };
if thread_id != self.thread_id {
return f.debug_tuple("InterruptCell").field(&"<opaque due to different thread>").finish();
}
self.scope(|value| value.fmt(f))
}
}
unsafe impl<T> Sync for InterruptCell<T>
where
T: Send,
{
}