rust/src/libstd/cell.rs

79 lines
1.7 KiB
Rust
Raw Normal View History

#[forbid(deprecated_mode)];
/// A dynamic, mutable location.
///
/// Similar to a mutable option type, but friendlier.
pub struct Cell<T> {
mut value: Option<T>
}
/// Creates a new full cell with the given value.
pub fn Cell<T>(value: T) -> Cell<T> {
2012-08-20 14:23:37 -05:00
Cell { value: Some(move value) }
}
pub pure fn empty_cell<T>() -> Cell<T> {
2012-08-20 14:23:37 -05:00
Cell { value: None }
}
impl<T> Cell<T> {
/// Yields the value, failing if the cell is empty.
fn take() -> T {
if self.is_empty() {
fail ~"attempt to take an empty cell";
}
2012-08-20 14:23:37 -05:00
let mut value = None;
value <-> self.value;
2012-09-11 19:17:54 -05:00
return option::unwrap(move value);
}
/// Returns the value, failing if the cell is full.
fn put_back(value: T) {
if !self.is_empty() {
fail ~"attempt to put a value back into a full cell";
}
2012-08-20 14:23:37 -05:00
self.value = Some(move value);
}
/// Returns true if the cell is empty and false if the cell is full.
pure fn is_empty() -> bool {
self.value.is_none()
}
// Calls a closure with a reference to the value.
fn with_ref<R>(op: fn(v: &T) -> R) -> R {
let v = self.take();
let r = op(&v);
self.put_back(move v);
move r
}
}
#[test]
fn test_basic() {
let value_cell = Cell(~10);
assert !value_cell.is_empty();
let value = value_cell.take();
assert value == ~10;
assert value_cell.is_empty();
2012-09-19 00:35:42 -05:00
value_cell.put_back(move value);
assert !value_cell.is_empty();
}
#[test]
#[should_fail]
#[ignore(cfg(windows))]
fn test_take_empty() {
let value_cell = empty_cell::<~int>();
value_cell.take();
}
#[test]
#[should_fail]
#[ignore(cfg(windows))]
fn test_put_back_non_empty() {
let value_cell = Cell(~10);
value_cell.put_back(~20);
}