|
1 | 1 | use core::alloc::Layout; |
| 2 | +use core::any::Any; |
2 | 3 | use core::fmt; |
3 | 4 | use core::marker::PhantomData; |
4 | 5 | use core::mem::MaybeUninit; |
@@ -143,6 +144,69 @@ impl<'a, T: ?Sized> Buffered<'a, T> { |
143 | 144 | } |
144 | 145 | } |
145 | 146 | } |
| 147 | +impl<'a> Buffered<'a, dyn Any> { |
| 148 | + /// Attempts to downcast the pointer to a concrete type. |
| 149 | + pub fn downcast<T: Any>(self) -> Result<Buffered<'a, T>, Self> { |
| 150 | + if self.is::<T>() { |
| 151 | + unsafe { Ok(self.downcast_unchecked()) } |
| 152 | + } else { |
| 153 | + Err(self) |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + /// Downcasts the box to a concrete type. |
| 158 | + /// |
| 159 | + /// For a safe alternative see [`downcast`](Self::downcast). |
| 160 | + /// |
| 161 | + /// # Safety |
| 162 | + /// |
| 163 | + /// The contained value must be of type `T`. |
| 164 | + pub unsafe fn downcast_unchecked<T: Any>(self) -> Buffered<'a, T> { |
| 165 | + Buffered::from_raw(self.into_raw().cast()) |
| 166 | + } |
| 167 | +} |
| 168 | +impl<'a> Buffered<'a, dyn Any + Send> { |
| 169 | + /// Attempts to downcast the pointer to a concrete type. |
| 170 | + pub fn downcast<T: Any>(self) -> Result<Buffered<'a, T>, Self> { |
| 171 | + if self.is::<T>() { |
| 172 | + unsafe { Ok(self.downcast_unchecked()) } |
| 173 | + } else { |
| 174 | + Err(self) |
| 175 | + } |
| 176 | + } |
| 177 | + |
| 178 | + /// Downcasts the box to a concrete type. |
| 179 | + /// |
| 180 | + /// For a safe alternative see [`downcast`](Self::downcast). |
| 181 | + /// |
| 182 | + /// # Safety |
| 183 | + /// |
| 184 | + /// The contained value must be of type `T`. |
| 185 | + pub unsafe fn downcast_unchecked<T: Any>(self) -> Buffered<'a, T> { |
| 186 | + Buffered::from_raw(self.into_raw().cast()) |
| 187 | + } |
| 188 | +} |
| 189 | +impl<'a> Buffered<'a, dyn Any + Send + Sync> { |
| 190 | + /// Attempts to downcast the pointer to a concrete type. |
| 191 | + pub fn downcast<T: Any>(self) -> Result<Buffered<'a, T>, Self> { |
| 192 | + if self.is::<T>() { |
| 193 | + unsafe { Ok(self.downcast_unchecked()) } |
| 194 | + } else { |
| 195 | + Err(self) |
| 196 | + } |
| 197 | + } |
| 198 | + |
| 199 | + /// Downcasts the box to a concrete type. |
| 200 | + /// |
| 201 | + /// For a safe alternative see [`downcast`](Self::downcast). |
| 202 | + /// |
| 203 | + /// # Safety |
| 204 | + /// |
| 205 | + /// The contained value must be of type `T`. |
| 206 | + pub unsafe fn downcast_unchecked<T: Any>(self) -> Buffered<'a, T> { |
| 207 | + Buffered::from_raw(self.into_raw().cast()) |
| 208 | + } |
| 209 | +} |
146 | 210 |
|
147 | 211 | // Pretend `Buffered` owns the value of `T` rather than just a pointer to it. |
148 | 212 | // This, along with the `Buffered::project*` APIs, makes it easy to obtain a |
|
0 commit comments