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

Introduce RefCell::try_borrow_unguarded #59211

Merged
merged 4 commits into from
Apr 11, 2019
Merged
Show file tree
Hide file tree
Changes from 2 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

------------------------
45 changes: 45 additions & 0 deletions src/libcore/cell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -569,6 +569,18 @@ pub struct RefCell<T: ?Sized> {
value: UnsafeCell<T>,
}

/// An enumeration of values returned from the `state` method on a `RefCell<T>`.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[unstable(feature = "borrow_state", issue = "27733")]
pub enum BorrowState {
/// The cell is currently being read, there is at least one active `borrow`.
Reading,
/// The cell is currently being written to, there is an active `borrow_mut`.
Writing,
/// There are no outstanding borrows on this cell.
Unused,
}

/// An error returned by [`RefCell::try_borrow`](struct.RefCell.html#method.try_borrow).
#[stable(feature = "try_borrow", since = "1.13.0")]
pub struct BorrowError {
Expand Down Expand Up @@ -753,6 +765,39 @@ impl<T> RefCell<T> {
}

impl<T: ?Sized> RefCell<T> {
/// Query the current state of this `RefCell`
///
/// The returned value can be dispatched on to determine if a call to
/// `borrow` or `borrow_mut` would succeed.
///
/// # Examples
///
/// ```
/// #![feature(borrow_state)]
///
/// use std::cell::{BorrowState, RefCell};
///
/// let c = RefCell::new(5);
///
/// match c.borrow_state() {
/// BorrowState::Writing => println!("Cannot be borrowed"),
/// BorrowState::Reading => println!("Cannot be borrowed mutably"),
/// BorrowState::Unused => println!("Can be borrowed (mutably as well)"),
/// }
/// ```
#[unstable(feature = "borrow_state", issue = "27733")]
#[inline]
pub fn borrow_state(&self) -> BorrowState {
let borrow = self.borrow.get();
if is_writing(borrow) {
BorrowState::Writing
} else if is_reading(borrow) {
BorrowState::Reading
} else {
BorrowState::Unused
}
}

/// Immutably borrows the wrapped value.
///
/// The borrow lasts until the returned `Ref` exits scope. Multiple
Expand Down