@@ -23,7 +23,7 @@ pure fn get<T: copy>(opt: option<T>) -> T {
23
23
* Fails if the value equals `none`
24
24
*/
25
25
26
- alt opt { some( x) { return x; } none { fail ~"option none"; } }
26
+ alt opt { some( x) { return x; } none { fail ~"option : : get none"; } }
27
27
}
28
28
29
29
pure fn expect<T : copy>( opt: option<T >, reason: ~str) -> T {
@@ -112,14 +112,21 @@ pure fn unwrap<T>(-opt: option<T>) -> T {
112
112
unsafe {
113
113
let addr = alt opt {
114
114
some( x) { ptr:: addr_of ( x) }
115
- none { fail ~"option none" }
115
+ none { fail ~"option : : unwrap none" }
116
116
} ;
117
117
let liberated_value = unsafe :: reinterpret_cast ( * addr) ;
118
118
unsafe :: forget( opt) ;
119
119
return liberated_value;
120
120
}
121
121
}
122
122
123
+ /// The ubiquitous option dance.
124
+ #[ inline( always) ]
125
+ fn swap_unwrap < T > ( opt : & mut option < T > ) -> T {
126
+ if opt. is_none ( ) { fail ~"option:: swap_unwrap none" }
127
+ unwrap ( util:: replace ( opt, none) )
128
+ }
129
+
123
130
pure fn unwrap_expect<T >( -opt: option<T >, reason: ~str) -> T {
124
131
//! As unwrap, but with a specified failure message.
125
132
if opt. is_none ( ) { fail reason; }
@@ -204,6 +211,24 @@ fn test_unwrap_resource() {
204
211
assert * i == 1 ;
205
212
}
206
213
214
+ #[ test]
215
+ fn test_option_dance ( ) {
216
+ let x = some ( ( ) ) ;
217
+ let mut y = some ( 5 ) ;
218
+ let mut y2 = 0 ;
219
+ do x. iter |_x| {
220
+ y2 = swap_unwrap ( & mut y) ;
221
+ }
222
+ assert y2 == 5 ;
223
+ assert y. is_none ( ) ;
224
+ }
225
+ #[ test] #[ should_fail] #[ ignore( cfg( windows) ) ]
226
+ fn test_option_too_much_dance ( ) {
227
+ let mut y = some ( util:: noncopyable ( ) ) ;
228
+ let _y2 = swap_unwrap ( & mut y) ;
229
+ let _y3 = swap_unwrap ( & mut y) ;
230
+ }
231
+
207
232
#[ test]
208
233
fn test_option_while_some ( ) {
209
234
let mut i = 0 ;
0 commit comments