Skip to content

Commit

Permalink
Introduce non-panicking borrow methods on RefCell<T>
Browse files Browse the repository at this point in the history
  • Loading branch information
nox committed Jun 28, 2016
1 parent dc05382 commit 57063ad
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions text/0000-try-borrow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
- Feature Name: try_borrow
- Start Date: 2016-06-27
- RFC PR: (leave this empty)
- Rust Issue: (leave this empty)

# Summary
[summary]: #summary

Introduce non-panicking borrow methods on `RefCell<T>`.

# Motivation
[motivation]: #motivation

Whenever something is built from user input, for example a graph in which nodes
are `RefCell<T>` values, it is primordial to avoid panicking on bad input. The
only way to avoid panics on cyclic input in this case is a way to
conditionally-borrow the cell contents.

# Detailed design
[design]: #detailed-design

```rust
impl RefCell<T> {
/// Tries to immutably borrows the value. This returns `None` if the cell
/// was already borrowed mutably.
pub fn try_borrow(&self) -> Option<Ref<T>> { ... }

/// Tries to mutably borrows the value. This returns `None` if the cell
/// was already borrowed.
pub fn try_borrow_mut(&self) -> Option<RefMut<T>> { ... }
}
```

# Drawbacks
[drawbacks]: #drawbacks

This departs from the fallible/infallible convention where we avoid providing
both panicking and non-panicking methods for the same operation.

# Alternatives
[alternatives]: #alternatives

The alternative is to provide a `borrow_state` methods returning the state
of the borrow flag of the cell, i.e:

```rust
pub enum BorrowState {
Reading,
Writing,
Unused,
}

impl<T> RefCell<T> {
pub fn borrow_state(&self) -> BorrowState... }
}
```

See [the Rust tracking issue](https://github.com/rust-lang/rust/issues/27733)
for this feature.

# Unresolved questions
[unresolved]: #unresolved-questions

There are no unresolved questions.

0 comments on commit 57063ad

Please sign in to comment.