From b9b0d374d3fee6ba204943edff750e5d5739c82a Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Thu, 9 Aug 2012 19:06:06 -0700 Subject: [PATCH] libstd: Implement cells as a nicer replacement for the option dance --- src/libstd/cell.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/libstd/cell.rs 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() + } +} +