Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize RefCell read borrowing #62748

Merged
merged 3 commits into from
Jul 27, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions src/libcore/cell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1101,13 +1101,23 @@ struct BorrowRef<'b> {
impl<'b> BorrowRef<'b> {
#[inline]
fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRef<'b>> {
let b = borrow.get();
if is_writing(b) || b == isize::max_value() {
// If there's currently a writing borrow, or if incrementing the
// refcount would overflow into a writing borrow.
let b = borrow.get().wrapping_add(1);
luca-barbieri marked this conversation as resolved.
Show resolved Hide resolved
luca-barbieri marked this conversation as resolved.
Show resolved Hide resolved
if !is_reading(b) {
// Incrementing borrow can result in a non-reading value (<= 0) in these cases:
// 1. It was < 0, i.e. there are writing borrows, so we can't allow a read borrow
// due to Rust's reference aliasing rules
// 2. It was isize::max_value() (the max amount of reading borrows) and it overflowed
// into isize::min_value() (the max amount of writing borrows) so we can't allow
// an additional read borrow because isize can't represent so many read borrows
// (this can only happen if you mem::forget more than a small constant amount of
// `Ref`s, which is not good practice)
None
} else {
borrow.set(b + 1);
// Incrementing borrow can result in a reading value (> 0) in these cases:
// 1. It was = 0, i.e. it wasn't borrowed, and we are taking the first read borrow
// 2. It was > 0 and < isize::max_value(), i.e. there were read borrows, and isize
// is large enough to represent having one more read borrow
borrow.set(b);
Some(BorrowRef { borrow })
}
}
Expand Down