implement readable and callable for all structs in the hooks crate

This commit is contained in:
Evan Almloff committed 2024-03-08 11:17:28 -06:00
1 parent 98158bdc6f
commit ffc49530f6
13 files changed
+167 -491

No files matched your search

+38 -2
View File
@@ -49,7 +49,43 @@ impl<O: 'static> Copy for UseCallback<O> {}
impl<O> UseCallback<O> {
/// Call the callback
pub fn call(&mut self) -> O {
self.inner.with_mut(|f| f())
pub fn call(&self) -> O {
(self.inner.write_unchecked())()
}
}
// This makes UseCallback callable like a normal function
impl<O> std::ops::Deref for UseCallback<O> {
type Target = dyn Fn() -> O;
fn deref(&self) -> &Self::Target {
use std::mem::MaybeUninit;
// https://github.com/dtolnay/case-studies/tree/master/callable-types
// First we create a closure that captures something with the Same in memory layout as Self (MaybeUninit<Self>).
let uninit_callable = MaybeUninit::<Self>::uninit();
// Then move that value into the closure. We assume that the closure now has a in memory layout of Self.
let uninit_closure = move || Self::call(unsafe { &*uninit_callable.as_ptr() });
// Check that the size of the closure is the same as the size of Self in case the compiler changed the layout of the closure.
let size_of_closure = std::mem::size_of_val(&uninit_closure);
assert_eq!(size_of_closure, std::mem::size_of::<Self>());
// Then cast the lifetime of the closure to the lifetime of &self.
fn cast_lifetime<'a, T>(_a: &T, b: &'a T) -> &'a T {
b
}
let reference_to_closure = cast_lifetime(
{
// The real closure that we will never use.
&uninit_closure
},
// We transmute self into a reference to the closure. This is safe because we know that the closure has the same memory layout as Self so &Closure == &Self.
unsafe { std::mem::transmute(self) },
);
// Cast the closure to a trait object.
reference_to_closure as &_
}
}