Skip to content

Commit

Permalink
Add cell#with_mut_ref for handling mutable references to the content.
Browse files Browse the repository at this point in the history
  • Loading branch information
metajack committed Apr 4, 2013
1 parent 717ed51 commit 2c02aab
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/libcore/cell.rs
Expand Up @@ -73,6 +73,14 @@ pub impl<T> Cell<T> {
self.put_back(v);
r
}

// Calls a closure with a mutable reference to the value.
fn with_mut_ref<R>(&self, op: &fn(v: &mut T) -> R) -> R {
let mut v = self.take();
let r = op(&mut v);
self.put_back(v);
r
}
}

#[test]
Expand Down Expand Up @@ -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);
}

5 comments on commit 2c02aab

@bors
Copy link
Contributor

@bors bors commented on 2c02aab Apr 5, 2013

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

saw approval from catamorphism
at metajack@2c02aab

@bors
Copy link
Contributor

@bors bors commented on 2c02aab Apr 5, 2013

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

merging metajack/rust/cell-with-ref-mut = 2c02aab into auto

@bors
Copy link
Contributor

@bors bors commented on 2c02aab Apr 5, 2013

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

metajack/rust/cell-with-ref-mut = 2c02aab merged ok, testing candidate = babe5063

@bors
Copy link
Contributor

@bors bors commented on 2c02aab Apr 5, 2013

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bors
Copy link
Contributor

@bors bors commented on 2c02aab Apr 5, 2013

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fast-forwarding incoming to auto = babe5063

Please sign in to comment.