Skip to content
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