Skip to content

Instantly share code, notes, and snippets.

@jberkenbilt
Last active December 1, 2024 23:27
Show Gist options
  • Save jberkenbilt/e78446dc9cceef5b75ba83928ffcd9bd to your computer and use it in GitHub Desktop.
Save jberkenbilt/e78446dc9cceef5b75ba83928ffcd9bd to your computer and use it in GitHub Desktop.
Go to Rust: just implbox
use std::any::TypeId;
use std::marker::PhantomData;
unsafe impl<T: Send> Send for ImplBox<T> {}
unsafe impl<T: Sync> Sync for ImplBox<T> {}
pub struct ImplBox<T> {
id: TypeId,
ptr: *const (),
destroy: fn(*const ()),
_t: PhantomData<T>,
}
impl<T> ImplBox<T> {
pub fn new(id: TypeId, destroy: fn(*const ()), ptr: *const ()) -> Self {
Self {
id,
ptr,
destroy,
_t: Default::default(),
}
}
pub fn with<F, Ret>(&self, id: TypeId, f: F) -> Ret
where
F: FnOnce(*const ()) -> Ret,
{
if self.id == id {
f(self.ptr)
} else {
panic!("id mismatch");
}
}
}
impl<T> Drop for ImplBox<T> {
fn drop(&mut self) {
(self.destroy)(self.ptr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment