xref: /openbmc/linux/rust/kernel/sync/arc/std_vendor.rs (revision 2a954832)
1 // SPDX-License-Identifier: Apache-2.0 OR MIT
2 
3 //! The contents of this file come from the Rust standard library, hosted in
4 //! the <https://github.com/rust-lang/rust> repository, licensed under
5 //! "Apache-2.0 OR MIT" and adapted for kernel use. For copyright details,
6 //! see <https://github.com/rust-lang/rust/blob/master/COPYRIGHT>.
7 
8 use crate::sync::{arc::ArcInner, Arc};
9 use core::any::Any;
10 
11 impl Arc<dyn Any + Send + Sync> {
12     /// Attempt to downcast the `Arc<dyn Any + Send + Sync>` to a concrete type.
13     pub fn downcast<T>(self) -> core::result::Result<Arc<T>, Self>
14     where
15         T: Any + Send + Sync,
16     {
17         if (*self).is::<T>() {
18             // SAFETY: We have just checked that the type is correct, so we can cast the pointer.
19             unsafe {
20                 let ptr = self.ptr.cast::<ArcInner<T>>();
21                 core::mem::forget(self);
22                 Ok(Arc::from_inner(ptr))
23             }
24         } else {
25             Err(self)
26         }
27     }
28 }
29