Skip to content

Commit 9c35ac5

Browse files
Keegan McAllisteralexcrichton
Keegan McAllister
authored andcommitted
Implement cell::clone_ref
Per discussion with @alexcrichton, this is a free function.
1 parent a0594eb commit 9c35ac5

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

src/libcore/cell.rs

+34
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,25 @@ impl<'b, T> Deref<T> for Ref<'b, T> {
186186
}
187187
}
188188

189+
/// Copy a `Ref`.
190+
///
191+
/// The `RefCell` is already immutably borrowed, so this cannot fail.
192+
///
193+
/// A `Clone` implementation would interfere with the widespread
194+
/// use of `r.borrow().clone()` to clone the contents of a `RefCell`.
195+
#[experimental]
196+
pub fn clone_ref<'b, T>(orig: &Ref<'b, T>) -> Ref<'b, T> {
197+
// Since this Ref exists, we know the borrow flag
198+
// is not set to WRITING.
199+
let borrow = orig.parent.borrow.get();
200+
debug_assert!(borrow != WRITING && borrow != UNUSED);
201+
orig.parent.borrow.set(borrow + 1);
202+
203+
Ref {
204+
parent: orig.parent,
205+
}
206+
}
207+
189208
/// Wraps a mutable borrowed reference to a value in a `RefCell` box.
190209
pub struct RefMut<'b, T> {
191210
parent: &'b RefCell<T>
@@ -307,4 +326,19 @@ mod test {
307326
let _ = _b;
308327
let _b = x.borrow_mut();
309328
}
329+
330+
#[test]
331+
fn clone_ref_updates_flag() {
332+
let x = RefCell::new(0);
333+
{
334+
let b1 = x.borrow();
335+
assert!(x.try_borrow_mut().is_none());
336+
{
337+
let _b2 = clone_ref(&b1);
338+
assert!(x.try_borrow_mut().is_none());
339+
}
340+
assert!(x.try_borrow_mut().is_none());
341+
}
342+
assert!(x.try_borrow_mut().is_some());
343+
}
310344
}

0 commit comments

Comments
 (0)