1
+ export swappable;
2
+ export unwrap;
3
+ export methods;
4
+
5
+ #[ doc = "
6
+ A value that may be swapped out temporarily while it is being processed
7
+ and then replaced. Swappables are most useful when working with unique
8
+ values, which often cannot be mutated unless they are stored in the local
9
+ stack frame to ensure memory safety.
10
+
11
+ The type guarantees the invariant that the value is always \" swapped in\"
12
+ except during the execution of the `swap()` and `with()` methods.
13
+ " ]
14
+ type swappable < A > = {
15
+ mut o_t : option < A >
16
+ } ;
17
+
18
+ #[ doc = "Create a swappable swapped in with a given initial value" ]
19
+ fn swappable < A > ( +t : A ) -> swappable < A > {
20
+ { mut o_t: some ( t) }
21
+ }
22
+
23
+ #[ doc = "Consumes a swappable and returns its contents without copying" ]
24
+ fn unwrap < A > ( -s : swappable < A > ) -> A {
25
+ let { o_t: o_t } <- s;
26
+ option:: unwrap ( o_t)
27
+ }
28
+
29
+ impl methods < A > for swappable < A > {
30
+ #[ doc = "
31
+ Overwrites the contents of the swappable
32
+ " ]
33
+ fn set ( +a : A ) {
34
+ self . o_t <- some ( a) ;
35
+ }
36
+
37
+ #[ doc = "
38
+ Invokes `f()` with the current value but replaces the
39
+ current value when complete. Returns the result of `f()`.
40
+
41
+ Attempts to read or access the receiver while `f()` is executing
42
+ will fail dynamically.
43
+ " ]
44
+ fn with < B > ( f : fn ( A ) -> B ) -> B {
45
+ let mut o_u = none;
46
+ self . swap { |t| o_u <- some ( f ( t) ) ; t }
47
+ option:: unwrap ( o_u)
48
+ }
49
+
50
+ #[ doc = "
51
+ Invokes `f()` with the current value and then replaces the
52
+ current value with the result of `f()`.
53
+
54
+ Attempts to read or access the receiver while `f()` is executing
55
+ will fail dynamically.
56
+ " ]
57
+ fn swap ( f : fn ( -A ) -> A ) {
58
+ alt self . o_t {
59
+ none { fail "no value present---already swapped?" ; }
60
+ some ( _) { }
61
+ }
62
+
63
+ let mut o_t = none;
64
+ o_t <-> self . o_t;
65
+ self . o_t <- some( f( option:: unwrap( o_t) ) ) ;
66
+ }
67
+
68
+ #[ doc = "True if there is a value present in this swappable" ]
69
+ fn is_present ( ) -> bool {
70
+ alt self . o_t {
71
+ none { false}
72
+ some( _) { true }
73
+ }
74
+ }
75
+
76
+ #[ doc = "
77
+ Removes the value from the swappable. Any further attempts
78
+ to use the swapabble without first invoking `set()` will fail.
79
+ " ]
80
+ fn take ( ) -> A {
81
+ alt self . o_t {
82
+ none { fail "swapped out" ; }
83
+ some ( _) { }
84
+ }
85
+
86
+ let mut o_t = none;
87
+ option:: unwrap ( o_t)
88
+ }
89
+ }
90
+
91
+ impl methods < A : copy > for swappable < A > {
92
+ #[ doc = "
93
+ Copies out the contents of the swappable
94
+ " ]
95
+ fn get ( ) -> A {
96
+ self . o_t . get ( )
97
+ }
98
+ }
0 commit comments