|
| 1 | +- Feature Name: try_borrow |
| 2 | +- Start Date: 2016-06-27 |
| 3 | +- RFC PR: (leave this empty) |
| 4 | +- Rust Issue: (leave this empty) |
| 5 | + |
| 6 | +# Summary |
| 7 | +[summary]: #summary |
| 8 | + |
| 9 | +Introduce non-panicking borrow methods on `RefCell<T>`. |
| 10 | + |
| 11 | +# Motivation |
| 12 | +[motivation]: #motivation |
| 13 | + |
| 14 | +Whenever something is built from user input, for example a graph in which nodes |
| 15 | +are `RefCell<T>` values, it is primordial to avoid panicking on bad input. The |
| 16 | +only way to avoid panics on cyclic input in this case is a way to |
| 17 | +conditionally-borrow the cell contents. |
| 18 | + |
| 19 | +# Detailed design |
| 20 | +[design]: #detailed-design |
| 21 | + |
| 22 | +```rust |
| 23 | +impl RefCell<T> { |
| 24 | + /// Tries to immutably borrows the value. This returns `None` if the cell |
| 25 | + /// was already borrowed mutably. |
| 26 | + pub fn try_borrow(&self) -> Option<Ref<T>> { ... } |
| 27 | + |
| 28 | + /// Tries to mutably borrows the value. This returns `None` if the cell |
| 29 | + /// was already borrowed. |
| 30 | + pub fn try_borrow_mut(&self) -> Option<RefMut<T>> { ... } |
| 31 | +} |
| 32 | +``` |
| 33 | + |
| 34 | +# Drawbacks |
| 35 | +[drawbacks]: #drawbacks |
| 36 | + |
| 37 | +This departs from the fallible/infallible convention where we avoid providing |
| 38 | +both panicking and non-panicking methods for the same operation. |
| 39 | + |
| 40 | +# Alternatives |
| 41 | +[alternatives]: #alternatives |
| 42 | + |
| 43 | +The alternative is to provide a `borrow_state` methods returning the state |
| 44 | +of the borrow flag of the cell, i.e: |
| 45 | + |
| 46 | +```rust |
| 47 | +pub enum BorrowState { |
| 48 | + Reading, |
| 49 | + Writing, |
| 50 | + Unused, |
| 51 | +} |
| 52 | + |
| 53 | +impl<T> RefCell<T> { |
| 54 | + pub fn borrow_state(&self) -> BorrowState { ... } |
| 55 | +} |
| 56 | +``` |
| 57 | + |
| 58 | +See [the Rust tracking issue](https://github.com/rust-lang/rust/issues/27733) |
| 59 | +for this feature. |
| 60 | + |
| 61 | +# Unresolved questions |
| 62 | +[unresolved]: #unresolved-questions |
| 63 | + |
| 64 | +There are no unresolved questions. |
0 commit comments