-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Introduce non-panicking borrow methods on
RefCell<T>
- Loading branch information
Showing
1 changed file
with
64 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |