Skip to content

Commit e21e991

Browse files
author
Sven Van Asbroeck
committed
rust/kernel: define a fallible implementation of Arc::pin
This is convenient to create pinned pointers inside the kernel, without having to use/prove an `unsafe` block each time. Defined as a trait, so it can be implemented for `core` pointers such as `Arc`, `Rc`, or `Box`. Includes a sample implementation for `Arc`. Signed-off-by: Sven Van Asbroeck <[email protected]>
1 parent 698f04d commit e21e991

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

rust/kernel/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ pub mod file;
4444
pub mod file_operations;
4545
pub mod miscdev;
4646
pub mod pages;
47+
pub mod traits;
4748

4849
pub mod linked_list;
4950
mod raw_list;

rust/kernel/traits.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// SPDX-License-Identifier: GPL-2.0
2+
3+
//! Traits useful to Drivers, and their implementations for common types.
4+
5+
use core::{ops::Deref, pin::Pin};
6+
7+
use alloc::{alloc::AllocError, sync::Arc};
8+
9+
/// Trait which implements a fallible version of `pin()` for any pointer type.
10+
///
11+
/// Common pointer types which implement `pin()` include `Box`, `Arc` and `Rc`.
12+
pub trait TryPin<P: Deref> {
13+
/// Constructs a new Pin<pointer<T>>. If T does not implement Unpin, then data
14+
/// will be pinned in memory and unable to be moved. An error will be returned
15+
/// if allocation fails.
16+
fn try_pin(data: P::Target) -> core::result::Result<Pin<P>, AllocError>;
17+
}
18+
19+
impl<T> TryPin<Arc<T>> for Arc<T> {
20+
fn try_pin(data: T) -> core::result::Result<Pin<Arc<T>>, AllocError> {
21+
// SAFETY: the data T is exposed only through a `Pin<Arc<T>>`, which
22+
// does not allow data to move out of the `Arc`. Therefore it can
23+
// never be moved.
24+
Ok(unsafe { Pin::new_unchecked(Arc::try_new(data)?) })
25+
}
26+
}

0 commit comments

Comments
 (0)