| 1 | use alloc::rc::Rc; |
| 2 | use core::{borrow::Borrow, fmt, ops::Bound}; |
| 3 | |
| 4 | #[derive(Eq, Hash, Ord, PartialEq, PartialOrd)] |
| 5 | pub struct Ref<T>(pub Rc<T>); |
| 6 | |
| 7 | impl<T> Clone for Ref<T> { |
| 8 | fn clone(&self) -> Self { |
| 9 | Self(self.0.clone()) |
| 10 | } |
| 11 | } |
| 12 | |
| 13 | impl<T> fmt::Debug for Ref<T> |
| 14 | where |
| 15 | T: fmt::Debug, |
| 16 | { |
| 17 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 18 | self.0.fmt(f) |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | #[derive(Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] |
| 23 | #[repr(transparent)] |
| 24 | pub struct Wrapper<T: ?Sized>(pub T); |
| 25 | |
| 26 | impl<T: ?Sized> Wrapper<T> { |
| 27 | pub fn wrap(value: &T) -> &Self { |
| 28 | // safe because Wrapper<T> is #[repr(transparent)] |
| 29 | unsafe { &*(value as *const T as *const Self) } |
| 30 | } |
| 31 | |
| 32 | pub fn wrap_bound(bound: Bound<&T>) -> Bound<&Self> { |
| 33 | match bound { |
| 34 | Bound::Included(t) => Bound::Included(Self::wrap(t)), |
| 35 | Bound::Excluded(t) => Bound::Excluded(Self::wrap(t)), |
| 36 | Bound::Unbounded => Bound::Unbounded, |
| 37 | } |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | impl<K, Q> Borrow<Wrapper<Q>> for Ref<K> |
| 42 | where |
| 43 | K: Borrow<Q>, |
| 44 | Q: ?Sized, |
| 45 | { |
| 46 | fn borrow(&self) -> &Wrapper<Q> { |
| 47 | // Rc<K>: Borrow<K> |
| 48 | let k: &K = self.0.borrow(); |
| 49 | // K: Borrow<Q> |
| 50 | let q: &Q = k.borrow(); |
| 51 | |
| 52 | Wrapper::wrap(q) |
| 53 | } |
| 54 | } |