Skip to content

Commit

Permalink
rust/samples: miscdev: eliminate unsafe block
Browse files Browse the repository at this point in the history
When creating a pinned `Arc`, eliminate an `unsafe` block by using
the fallible version of `Arc::pin()`.

While we're here, update the `// SAFETY` proofs, which have
become stale.

Tested using QEMU.

Signed-off-by: Sven Van Asbroeck <[email protected]>
  • Loading branch information
Sven Van Asbroeck committed May 26, 2021
1 parent 02138fd commit 5a67315
Showing 1 changed file with 8 additions and 11 deletions.
19 changes: 8 additions & 11 deletions samples/rust/rust_miscdev.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,19 +39,16 @@ struct SharedState {

impl SharedState {
fn try_new() -> Result<Pin<Arc<Self>>> {
// SAFETY: `state` is pinning `Arc`, which implements `Unpin`.
let state = unsafe {
Pin::new_unchecked(Arc::try_new(Self {
// SAFETY: `condvar_init!` is called below.
state_changed: CondVar::new(),
// SAFETY: `mutex_init!` is called below.
inner: Mutex::new(SharedStateInner { token_count: 0 }),
})?)
};
// SAFETY: `state_changed` is pinned behind `Arc`.
let state = Arc::try_pin(Self {
// SAFETY: `condvar_init!` is called below.
state_changed: unsafe { CondVar::new() },
// SAFETY: `mutex_init!` is called below.
inner: unsafe { Mutex::new(SharedStateInner { token_count: 0 }) },
})?;
// SAFETY: `state_changed` is pinned behind `Pin<Arc>`.
let state_changed = unsafe { Pin::new_unchecked(&state.state_changed) };
kernel::condvar_init!(state_changed, "SharedState::state_changed");
// SAFETY: `inner` is pinned behind `Arc`.
// SAFETY: `inner` is pinned behind `Pin<Arc>`.
let inner = unsafe { Pin::new_unchecked(&state.inner) };
kernel::mutex_init!(inner, "SharedState::inner");
Ok(state)
Expand Down

0 comments on commit 5a67315

Please sign in to comment.