]> git.lizzy.rs Git - rust.git/commit
Auto merge of #25747 - SimonSapin:map_ref, r=alexcrichton
authorbors <bors@rust-lang.org>
Fri, 29 May 2015 07:07:07 +0000 (07:07 +0000)
committerbors <bors@rust-lang.org>
Fri, 29 May 2015 07:07:07 +0000 (07:07 +0000)
commit25fc917c65f7c51fafdab0f023772171f84c7f0a
treec30bec8b690dc6cee25c5e43deb79e2ddd9f2581
parent42a59aef710c66e17627e00cc4d00cf29a7b46ed
parentd0afa6ede3ce5fd6b35c8f1fd5fc89336ec2dc96
Auto merge of #25747 - SimonSapin:map_ref, r=alexcrichton

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>> {
        map_ref(self.borrow(), |j| j.as_string())
    }
}
```

r? @alexcrichton
src/libcore/cell.rs