about summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorPatrick Walton <pcwalton@mimiga.net>2012-08-09 19:06:06 -0700
committerPatrick Walton <pcwalton@mimiga.net>2012-08-09 19:45:05 -0700
commitb9b0d374d3fee6ba204943edff750e5d5739c82a (patch)
treed2f4f8487165322871f35db89e7ce524a5b68b61 /src/libstd
parent758dd786f65a86a160c76889ebd3d5fc1b206445 (diff)
libstd: Implement cells as a nicer replacement for the option dance
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/cell.rs42
1 files changed, 42 insertions, 0 deletions
diff --git a/src/libstd/cell.rs b/src/libstd/cell.rs
new file mode 100644
index 00000000000..d32a47a8ab5
--- /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<T> {
+    mut value: option<T>;
+}
+
+/// Creates a new full cell with the given value.
+fn Cell<T>(+value: T) -> Cell<T> {
+    Cell { value: some(move value) }
+}
+
+fn empty_cell<T>() -> Cell<T> {
+    Cell { value: none }
+}
+
+impl<T> Cell<T> {
+    /// 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()
+    }
+}
+