From 2c02aab75851f6bc86b033f07d971fe892c111ef Mon Sep 17 00:00:00 2001 From: Jack Moffitt Date: Thu, 4 Apr 2013 11:34:35 -0600 Subject: [PATCH] Add cell#with_mut_ref for handling mutable references to the content. --- src/libcore/cell.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/libcore/cell.rs b/src/libcore/cell.rs index c2983e033e537..1707bddc2b9d4 100644 --- a/src/libcore/cell.rs +++ b/src/libcore/cell.rs @@ -73,6 +73,14 @@ pub impl Cell { self.put_back(v); r } + + // Calls a closure with a mutable reference to the value. + fn with_mut_ref(&self, op: &fn(v: &mut T) -> R) -> R { + let mut v = self.take(); + let r = op(&mut v); + self.put_back(v); + r + } } #[test] @@ -101,3 +109,21 @@ fn test_put_back_non_empty() { let value_cell = Cell(~10); value_cell.put_back(~20); } + +#[test] +fn test_with_ref() { + let good = 6; + let c = Cell(~[1, 2, 3, 4, 5, 6]); + let l = do c.with_ref() |v| { v.len() }; + assert!(l == good); +} + +#[test] +fn test_with_mut_ref() { + let good = ~[1, 2, 3]; + let mut v = ~[1, 2]; + let c = Cell(v); + do c.with_mut_ref() |v| { v.push(3); } + let v = c.take(); + assert!(v == good); +}