diff --git a/src/libstd/cell.rs b/src/libstd/cell.rs new file mode 100644 index 000000000000..d32a47a8ab52 --- /dev/null +++ b/src/libstd/cell.rs @@ -0,0 +1,42 @@ +/// A dynamic, mutable location. +/// +/// Similar to a mutable option type, but friendlier. + +struct Cell { + mut value: option; +} + +/// Creates a new full cell with the given value. +fn Cell(+value: T) -> Cell { + Cell { value: some(move value) } +} + +fn empty_cell() -> Cell { + Cell { value: none } +} + +impl Cell { + /// Yields the value, failing if the cell is empty. + fn take() -> T { + let value = none; + value <-> self.value; + if value.is_none() { + fail "attempt to take an empty cell"; + } + return option::unwrap(value); + } + + /// Returns the value, failing if the cell is full. + fn put_back(+value: T) { + if self.value.is_none() { + fail "attempt to put a value back into a full cell"; + } + self.value = some(move value); + } + + /// Returns true if the cell is empty and false if the cell is full. + fn is_empty() -> bool { + self.value.is_none() + } +} +