Skip to content

Commit e451b59

Browse files
author
Sven Van Asbroeck
committed
rust/samples: miscdev: eliminate unsafe block
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]>
1 parent e21e991 commit e451b59

File tree

1 file changed

+9
-11
lines changed

1 file changed

+9
-11
lines changed

samples/rust/rust_miscdev.rs

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ use kernel::{
1515
io_buffer::{IoBufferReader, IoBufferWriter},
1616
miscdev,
1717
sync::{CondVar, Mutex},
18+
traits::TryPin,
1819
Error,
1920
};
2021

@@ -39,19 +40,16 @@ struct SharedState {
3940

4041
impl SharedState {
4142
fn try_new() -> Result<Pin<Arc<Self>>> {
42-
// SAFETY: `state` is pinning `Arc`, which implements `Unpin`.
43-
let state = unsafe {
44-
Pin::new_unchecked(Arc::try_new(Self {
45-
// SAFETY: `condvar_init!` is called below.
46-
state_changed: CondVar::new(),
47-
// SAFETY: `mutex_init!` is called below.
48-
inner: Mutex::new(SharedStateInner { token_count: 0 }),
49-
})?)
50-
};
51-
// SAFETY: `state_changed` is pinned behind `Arc`.
43+
let state = Arc::try_pin(Self {
44+
// SAFETY: `condvar_init!` is called below.
45+
state_changed: unsafe { CondVar::new() },
46+
// SAFETY: `mutex_init!` is called below.
47+
inner: unsafe { Mutex::new(SharedStateInner { token_count: 0 }) },
48+
})?;
49+
// SAFETY: `state_changed` is pinned behind `Pin<Arc>`.
5250
let state_changed = unsafe { Pin::new_unchecked(&state.state_changed) };
5351
kernel::condvar_init!(state_changed, "SharedState::state_changed");
54-
// SAFETY: `inner` is pinned behind `Arc`.
52+
// SAFETY: `inner` is pinned behind `Pin<Arc>`.
5553
let inner = unsafe { Pin::new_unchecked(&state.inner) };
5654
kernel::mutex_init!(inner, "SharedState::inner");
5755
Ok(state)

0 commit comments

Comments
 (0)