Last active
December 1, 2024 23:27
-
-
Save jberkenbilt/e78446dc9cceef5b75ba83928ffcd9bd to your computer and use it in GitHub Desktop.
Go to Rust: just implbox
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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