Skip to content

Commit b9b0d37

Browse files
committed
libstd: Implement cells as a nicer replacement for the option dance
1 parent 758dd78 commit b9b0d37

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/libstd/cell.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/// A dynamic, mutable location.
2+
///
3+
/// Similar to a mutable option type, but friendlier.
4+
5+
struct Cell<T> {
6+
mut value: option<T>;
7+
}
8+
9+
/// Creates a new full cell with the given value.
10+
fn Cell<T>(+value: T) -> Cell<T> {
11+
Cell { value: some(move value) }
12+
}
13+
14+
fn empty_cell<T>() -> Cell<T> {
15+
Cell { value: none }
16+
}
17+
18+
impl<T> Cell<T> {
19+
/// Yields the value, failing if the cell is empty.
20+
fn take() -> T {
21+
let value = none;
22+
value <-> self.value;
23+
if value.is_none() {
24+
fail "attempt to take an empty cell";
25+
}
26+
return option::unwrap(value);
27+
}
28+
29+
/// Returns the value, failing if the cell is full.
30+
fn put_back(+value: T) {
31+
if self.value.is_none() {
32+
fail "attempt to put a value back into a full cell";
33+
}
34+
self.value = some(move value);
35+
}
36+
37+
/// Returns true if the cell is empty and false if the cell is full.
38+
fn is_empty() -> bool {
39+
self.value.is_none()
40+
}
41+
}
42+

0 commit comments

Comments
 (0)