Resolve the std/hashbrown conflict situation
[anymap] / src / any.rs
1 use core::fmt;
2 use core::any::{Any, TypeId};
3 #[cfg(not(feature = "std"))]
4 use alloc::boxed::Box;
5
6 #[doc(hidden)]
7 pub trait CloneToAny {
8 /// Clone `self` into a new `Box<dyn CloneAny>` object.
9 fn clone_to_any(&self) -> Box<dyn CloneAny>;
10 }
11
12 impl<T: Any + Clone> CloneToAny for T {
13 #[inline]
14 fn clone_to_any(&self) -> Box<dyn CloneAny> {
15 Box::new(self.clone())
16 }
17 }
18
19 macro_rules! impl_clone {
20 ($t:ty) => {
21 impl Clone for Box<$t> {
22 #[inline]
23 fn clone(&self) -> Box<$t> {
24 // SAFETY: this dance is to reapply any Send/Sync marker. I’m not happy about this
25 // approach, given that I used to do it in safe code, but then came a dodgy
26 // future-compatibility warning where_clauses_object_safety, which is spurious for
27 // auto traits but still super annoying (future-compatibility lints seem to mean
28 // your bin crate needs a corresponding allow!). Although I explained my plight¹
29 // and it was all explained and agreed upon, no action has been taken. So I finally
30 // caved and worked around it by doing it this way, which matches what’s done for
31 // core::any², so it’s probably not *too* bad.
32 //
33 // ¹ https://github.com/rust-lang/rust/issues/51443#issuecomment-421988013
34 // ² https://github.com/rust-lang/rust/blob/e7825f2b690c9a0d21b6f6d84c404bb53b151b38/library/alloc/src/boxed.rs#L1613-L1616
35 let clone: Box<dyn CloneAny> = (**self).clone_to_any();
36 let raw: *mut dyn CloneAny = Box::into_raw(clone);
37 unsafe { Box::from_raw(raw as *mut $t) }
38 }
39 }
40
41 impl fmt::Debug for $t {
42 #[inline]
43 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
44 f.pad(stringify!($t))
45 }
46 }
47 }
48 }
49
50 /// Methods for downcasting from an `Any`-like trait object.
51 ///
52 /// This should only be implemented on trait objects for subtraits of `Any`, though you can
53 /// implement it for other types and it’ll work fine, so long as your implementation is correct.
54 pub trait Downcast {
55 /// Gets the `TypeId` of `self`.
56 fn type_id(&self) -> TypeId;
57
58 // Note the bound through these downcast methods is 'static, rather than the inexpressible
59 // concept of Self-but-as-a-trait (where Self is `dyn Trait`). This is sufficient, exceeding
60 // TypeId’s requirements. Sure, you *can* do CloneAny.downcast_unchecked::<NotClone>() and the
61 // type system won’t protect you, but that doesn’t introduce any unsafety: the method is
62 // already unsafe because you can specify the wrong type, and if this were exposing safe
63 // downcasting, CloneAny.downcast::<NotClone>() would just return an error, which is just as
64 // correct.
65 //
66 // Now in theory we could also add T: ?Sized, but that doesn’t play nicely with the common
67 // implementation, so I’m doing without it.
68
69 /// Downcast from `&Any` to `&T`, without checking the type matches.
70 ///
71 /// # Safety
72 ///
73 /// The caller must ensure that `T` matches the trait object, on pain of *undefined behaviour*.
74 unsafe fn downcast_ref_unchecked<T: 'static>(&self) -> &T;
75
76 /// Downcast from `&mut Any` to `&mut T`, without checking the type matches.
77 ///
78 /// # Safety
79 ///
80 /// The caller must ensure that `T` matches the trait object, on pain of *undefined behaviour*.
81 unsafe fn downcast_mut_unchecked<T: 'static>(&mut self) -> &mut T;
82
83 /// Downcast from `Box<Any>` to `Box<T>`, without checking the type matches.
84 ///
85 /// # Safety
86 ///
87 /// The caller must ensure that `T` matches the trait object, on pain of *undefined behaviour*.
88 unsafe fn downcast_unchecked<T: 'static>(self: Box<Self>) -> Box<T>;
89 }
90
91 /// A trait for the conversion of an object into a boxed trait object.
92 pub trait IntoBox<A: ?Sized + Downcast>: Any {
93 /// Convert self into the appropriate boxed form.
94 fn into_box(self) -> Box<A>;
95 }
96
97 macro_rules! implement {
98 ($any_trait:ident $(+ $auto_traits:ident)*) => {
99 impl Downcast for dyn $any_trait $(+ $auto_traits)* {
100 #[inline]
101 fn type_id(&self) -> TypeId {
102 self.type_id()
103 }
104
105 #[inline]
106 unsafe fn downcast_ref_unchecked<T: 'static>(&self) -> &T {
107 &*(self as *const Self as *const T)
108 }
109
110 #[inline]
111 unsafe fn downcast_mut_unchecked<T: 'static>(&mut self) -> &mut T {
112 &mut *(self as *mut Self as *mut T)
113 }
114
115 #[inline]
116 unsafe fn downcast_unchecked<T: 'static>(self: Box<Self>) -> Box<T> {
117 Box::from_raw(Box::into_raw(self) as *mut T)
118 }
119 }
120
121 impl<T: $any_trait $(+ $auto_traits)*> IntoBox<dyn $any_trait $(+ $auto_traits)*> for T {
122 #[inline]
123 fn into_box(self) -> Box<dyn $any_trait $(+ $auto_traits)*> {
124 Box::new(self)
125 }
126 }
127 }
128 }
129
130 implement!(Any);
131 implement!(Any + Send);
132 implement!(Any + Send + Sync);
133
134 /// [`Any`], but with cloning.
135 ///
136 /// Every type with no non-`'static` references that implements `Clone` implements `CloneAny`.
137 /// See [`core::any`] for more details on `Any` in general.
138 pub trait CloneAny: Any + CloneToAny { }
139 impl<T: Any + Clone> CloneAny for T { }
140 implement!(CloneAny);
141 implement!(CloneAny + Send);
142 implement!(CloneAny + Send + Sync);
143 impl_clone!(dyn CloneAny);
144 impl_clone!(dyn CloneAny + Send);
145 impl_clone!(dyn CloneAny + Send + Sync);