Skip to content

Commit 3d192ac

Browse files
committed
Remove unsafety from unsupported/rwlosck.rs by using a Cell.
Replacing the UnsafeCell by a Cell makes it all safe.
1 parent c25f69a commit 3d192ac

File tree

1 file changed

+16
-18
lines changed

1 file changed

+16
-18
lines changed

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

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

35
pub struct RWLock {
4-
mode: UnsafeCell<isize>,
6+
mode: Cell<isize>,
57
}
68

79
unsafe impl Send for RWLock {}
810
unsafe impl Sync for RWLock {} // no threads on this platform
911

1012
impl RWLock {
1113
pub const fn new() -> RWLock {
12-
RWLock { mode: UnsafeCell::new(0) }
14+
RWLock { mode: Cell::new(0) }
1315
}
1416

1517
#[inline]
1618
pub unsafe fn read(&self) {
17-
let mode = self.mode.get();
18-
if *mode >= 0 {
19-
*mode += 1;
19+
let m = self.mode.get();
20+
if m >= 0 {
21+
self.mode.set(m + 1);
2022
} else {
2123
rtabort!("rwlock locked for writing");
2224
}
2325
}
2426

2527
#[inline]
2628
pub unsafe fn try_read(&self) -> bool {
27-
let mode = self.mode.get();
28-
if *mode >= 0 {
29-
*mode += 1;
29+
let m = self.mode.get();
30+
if m >= 0 {
31+
self.mode.set(m + 1);
3032
true
3133
} else {
3234
false
@@ -35,19 +37,15 @@ impl RWLock {
3537

3638
#[inline]
3739
pub unsafe fn write(&self) {
38-
let mode = self.mode.get();
39-
if *mode == 0 {
40-
*mode = -1;
41-
} else {
40+
if self.mode.replace(-1) != 0 {
4241
rtabort!("rwlock locked for reading")
4342
}
4443
}
4544

4645
#[inline]
4746
pub unsafe fn try_write(&self) -> bool {
48-
let mode = self.mode.get();
49-
if *mode == 0 {
50-
*mode = -1;
47+
if self.mode.get() == 0 {
48+
self.mode.set(-1);
5149
true
5250
} else {
5351
false
@@ -56,12 +54,12 @@ impl RWLock {
5654

5755
#[inline]
5856
pub unsafe fn read_unlock(&self) {
59-
*self.mode.get() -= 1;
57+
self.mode.set(self.mode.get() - 1);
6058
}
6159

6260
#[inline]
6361
pub unsafe fn write_unlock(&self) {
64-
*self.mode.get() += 1;
62+
self.mode.set(0);
6563
}
6664

6765
#[inline]

0 commit comments

Comments
 (0)