Skip to content

Commit 0e9b465

Browse files
committed
Auto merge of #62748 - luca-barbieri:optimize-refcell-borrow, r=RalfJung
Optimize RefCell read borrowing Instead of doing two comparisons we can do only one with a bit of cleverness. LLVM currently can't do this optimization itself on x86-64.
2 parents 09e3989 + 44c1650 commit 0e9b465

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

src/libcore/cell.rs

+15-5
Original file line numberDiff line numberDiff line change
@@ -1101,13 +1101,23 @@ struct BorrowRef<'b> {
11011101
impl<'b> BorrowRef<'b> {
11021102
#[inline]
11031103
fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRef<'b>> {
1104-
let b = borrow.get();
1105-
if is_writing(b) || b == isize::max_value() {
1106-
// If there's currently a writing borrow, or if incrementing the
1107-
// refcount would overflow into a writing borrow.
1104+
let b = borrow.get().wrapping_add(1);
1105+
if !is_reading(b) {
1106+
// Incrementing borrow can result in a non-reading value (<= 0) in these cases:
1107+
// 1. It was < 0, i.e. there are writing borrows, so we can't allow a read borrow
1108+
// due to Rust's reference aliasing rules
1109+
// 2. It was isize::max_value() (the max amount of reading borrows) and it overflowed
1110+
// into isize::min_value() (the max amount of writing borrows) so we can't allow
1111+
// an additional read borrow because isize can't represent so many read borrows
1112+
// (this can only happen if you mem::forget more than a small constant amount of
1113+
// `Ref`s, which is not good practice)
11081114
None
11091115
} else {
1110-
borrow.set(b + 1);
1116+
// Incrementing borrow can result in a reading value (> 0) in these cases:
1117+
// 1. It was = 0, i.e. it wasn't borrowed, and we are taking the first read borrow
1118+
// 2. It was > 0 and < isize::max_value(), i.e. there were read borrows, and isize
1119+
// is large enough to represent having one more read borrow
1120+
borrow.set(b);
11111121
Some(BorrowRef { borrow })
11121122
}
11131123
}

0 commit comments

Comments
 (0)