Commit 62e8200
committed
Add std::cell::map_ref
For slightly complex data structures like `rustc_serialize::json::Json`,
it is often convenient to have helper methods like
`Json::as_string(&self) -> Option<&str>` that return a borrow of some
component of `&self`.
However, when `RefCell`s are involved, keeping a `Ref` around is required
to hold a borrow to the insides of a `RefCell`. But `Ref` so far only
references the entirety of the contents of a `RefCell`, not a component.
But there is no reason it couldn’t: `Ref` internally contains just a data
reference and a borrow count reference. The two can be dissociated.
This adds a `map_ref` function that creates a new `Ref` for some other data,
but borrowing the same `RefCell` as an existing `Ref`.
Example:
```rust
struct RefCellJson(RefCell<Json>);
impl RefCellJson {
fn as_string(&self) -> Option<Ref<str>> {
let borrow = self.borrow();
borrow.as_string().map(|s| map_ref(&borrow, s))
}
}
```1 parent 62d4b62 commit 62e8200
2 files changed
+43
-0
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
555 | 555 | | |
556 | 556 | | |
557 | 557 | | |
| 558 | + | |
| 559 | + | |
| 560 | + | |
| 561 | + | |
| 562 | + | |
| 563 | + | |
| 564 | + | |
| 565 | + | |
| 566 | + | |
| 567 | + | |
| 568 | + | |
| 569 | + | |
| 570 | + | |
| 571 | + | |
| 572 | + | |
| 573 | + | |
| 574 | + | |
| 575 | + | |
| 576 | + | |
| 577 | + | |
| 578 | + | |
| 579 | + | |
| 580 | + | |
| 581 | + | |
| 582 | + | |
| 583 | + | |
| 584 | + | |
558 | 585 | | |
559 | 586 | | |
560 | 587 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
129 | 129 | | |
130 | 130 | | |
131 | 131 | | |
| 132 | + | |
| 133 | + | |
| 134 | + | |
| 135 | + | |
| 136 | + | |
| 137 | + | |
| 138 | + | |
| 139 | + | |
| 140 | + | |
| 141 | + | |
| 142 | + | |
| 143 | + | |
| 144 | + | |
| 145 | + | |
| 146 | + | |
| 147 | + | |
132 | 148 | | |
133 | 149 | | |
134 | 150 | | |
| |||
0 commit comments