Skip to content

Introduce RefCell::try_borrow_unguarded #59211

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

Merged
merged 4 commits into from
Apr 11, 2019
Merged
Show file tree
Hide file tree
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
7 changes: 7 additions & 0 deletions src/doc/unstable-book/src/library-features/borrow-state.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# `borrow_state`

The tracking issue for this feature is: [#27733]

[#27733]: https://github.com/rust-lang/rust/issues/27733

------------------------
38 changes: 38 additions & 0 deletions src/libcore/cell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -958,6 +958,44 @@ impl<T: ?Sized> RefCell<T> {
&mut *self.value.get()
}
}

/// Immutably borrows the wrapped value, returning an error if the value is
/// currently mutably borrowed.
///
/// # Safety
///
/// Unlike `RefCell::borrow`, this method is unsafe because it does not
/// return a `Ref`, thus leaving the borrow flag untouched. Mutably
/// borrowing the `RefCell` while the reference returned by this method
/// is alive is undefined behaviour.
///
/// # Examples
///
/// ```
/// #![feature(borrow_state)]
/// use std::cell::RefCell;
///
/// let c = RefCell::new(5);
///
/// {
/// let m = c.borrow_mut();
/// assert!(unsafe { c.try_borrow_unguarded() }.is_err());
/// }
///
/// {
/// let m = c.borrow();
/// assert!(unsafe { c.try_borrow_unguarded() }.is_ok());
/// }
/// ```
#[unstable(feature = "borrow_state", issue = "27733")]
#[inline]
pub unsafe fn try_borrow_unguarded(&self) -> Result<&T, BorrowError> {
if !is_writing(self.borrow.get()) {
Ok(&*self.value.get())
} else {
Err(BorrowError { _private: () })
}
}
}

#[stable(feature = "rust1", since = "1.0.0")]
Expand Down