Skip to content

Commit 4809190

Browse files
committed
Introduce non-panicking borrow methods on RefCell<T>
1 parent dc05382 commit 4809190

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

text/0000-try-borrow.md

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
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+
/// Returned when `RefCell::try_borrow` fails.
24+
pub struct BorrowError { _inner: () }
25+
26+
/// Returned when `RefCell::try_borrow_mut` fails.
27+
pub struct BorrowMutError { _inner: () }
28+
29+
impl RefCell<T> {
30+
/// Tries to immutably borrows the value. This returns `Err(_)` if the cell
31+
/// was already borrowed mutably.
32+
pub fn try_borrow(&self) -> Result<Ref<T>, BorrowError> { ... }
33+
34+
/// Tries to mutably borrows the value. This returns `Err(_)` if the cell
35+
/// was already borrowed.
36+
pub fn try_borrow_mut(&self) -> Result<RefMut<T>, BorrowMutError> { ... }
37+
}
38+
```
39+
40+
# Drawbacks
41+
[drawbacks]: #drawbacks
42+
43+
This departs from the fallible/infallible convention where we avoid providing
44+
both panicking and non-panicking methods for the same operation.
45+
46+
# Alternatives
47+
[alternatives]: #alternatives
48+
49+
The alternative is to provide a `borrow_state` method returning the state
50+
of the borrow flag of the cell, i.e:
51+
52+
```rust
53+
pub enum BorrowState {
54+
Reading,
55+
Writing,
56+
Unused,
57+
}
58+
59+
impl<T> RefCell<T> {
60+
pub fn borrow_state(&self) -> BorrowState... }
61+
}
62+
```
63+
64+
See [the Rust tracking issue](https://github.com/rust-lang/rust/issues/27733)
65+
for this feature.
66+
67+
# Unresolved questions
68+
[unresolved]: #unresolved-questions
69+
70+
There are no unresolved questions.

0 commit comments

Comments
 (0)