Skip to content

Commit c25f69a

Browse files
committed
Remove unsafety from unsupported/mutex.rs by using a Cell.
Replacing the UnsafeCell by a Cell simplifies things and makes it all safe.
1 parent ccea570 commit c25f69a

File tree

1 file changed

+8
-14
lines changed

1 file changed

+8
-14
lines changed

library/std/src/sys/unsupported/mutex.rs

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1-
use crate::cell::UnsafeCell;
1+
#![deny(unsafe_op_in_unsafe_fn)]
2+
3+
use crate::cell::Cell;
24

35
pub struct Mutex {
4-
locked: UnsafeCell<bool>,
6+
locked: Cell<bool>,
57
}
68

79
pub type MovableMutex = Mutex;
@@ -12,33 +14,25 @@ unsafe impl Sync for Mutex {} // no threads on this platform
1214
impl Mutex {
1315
#[rustc_const_stable(feature = "const_sys_mutex_new", since = "1.0.0")]
1416
pub const fn new() -> Mutex {
15-
Mutex { locked: UnsafeCell::new(false) }
17+
Mutex { locked: Cell::new(false) }
1618
}
1719

1820
#[inline]
1921
pub unsafe fn init(&mut self) {}
2022

2123
#[inline]
2224
pub unsafe fn lock(&self) {
23-
let locked = self.locked.get();
24-
assert!(!*locked, "cannot recursively acquire mutex");
25-
*locked = true;
25+
assert_eq!(self.locked.replace(true), false, "cannot recursively acquire mutex");
2626
}
2727

2828
#[inline]
2929
pub unsafe fn unlock(&self) {
30-
*self.locked.get() = false;
30+
self.locked.set(false);
3131
}
3232

3333
#[inline]
3434
pub unsafe fn try_lock(&self) -> bool {
35-
let locked = self.locked.get();
36-
if *locked {
37-
false
38-
} else {
39-
*locked = true;
40-
true
41-
}
35+
self.locked.replace(true) == false
4236
}
4337

4438
#[inline]

0 commit comments

Comments
 (0)