mc_core/util/
sync.rs

1use std::hash::{Hash, Hasher};
2
3
4/// This structure can be used to store a statically bound reference `&'static T` in a
5/// safe wrapper that also implements `Send` and `Sync`. These traits are implemented
6/// because the content cannot be recovered after the construction, and also because
7/// the pointer has a static lifetime.
8///
9/// This opaque pointer also implements `Hash` and `Eq` to be usable as a map key.
10#[repr(transparent)]
11#[derive(Copy, Clone)]
12pub struct OpaquePtr<T>(*const T);
13
14unsafe impl<T> Send for OpaquePtr<T> {}
15unsafe impl<T> Sync for OpaquePtr<T> {}
16
17impl<T> OpaquePtr<T> {
18
19    #[inline]
20    pub const fn new(rf: &'static T) -> Self {
21        Self(rf)
22    }
23
24    #[inline]
25    pub fn inner(self) -> &'static T {
26        unsafe { std::mem::transmute(self.0) }
27    }
28
29}
30
31impl<T> Hash for OpaquePtr<T> {
32    #[inline]
33    fn hash<H: Hasher>(&self, state: &mut H) {
34        self.0.hash(state);
35    }
36}
37
38impl<T> PartialEq for OpaquePtr<T> {
39    #[inline]
40    fn eq(&self, other: &Self) -> bool {
41        self.0 == other.0
42    }
43}
44
45impl<T> Eq for OpaquePtr<T> {}