Skip to content

Commit 1edd033

Browse files
asahilinaojeda
authored andcommitted
rust: sync: arc: Implement Arc<dyn Any + Send + Sync>::downcast()
This mirrors the standard library's alloc::sync::Arc::downcast(). Based on the Rust standard library implementation, ver 1.62.0, licensed under "Apache-2.0 OR MIT", from: https://github.com/rust-lang/rust/tree/1.62.0/library/alloc/src For copyright details, please see: https://github.com/rust-lang/rust/blob/1.62.0/COPYRIGHT Reviewed-by: Martin Rodriguez Reboredo <[email protected]> Reviewed-by: Andreas Hindborg <[email protected]> Reviewed-by: Vincenzo Palazzo <[email protected]> Reviewed-by: Gary Guo <[email protected]> Signed-off-by: Asahi Lina <[email protected]> Link: https://lore.kernel.org/r/[email protected] [ Moved `mod std_vendor;` up. ] Signed-off-by: Miguel Ojeda <[email protected]>
1 parent 39867fe commit 1edd033

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

rust/kernel/sync/arc.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ use core::{
3030
ptr::NonNull,
3131
};
3232

33+
mod std_vendor;
34+
3335
/// A reference-counted pointer to an instance of `T`.
3436
///
3537
/// The reference count is incremented when new instances of [`Arc`] are created, and decremented

rust/kernel/sync/arc/std_vendor.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
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+
}

0 commit comments

Comments
 (0)