2012-08-01 18:04:43 -05:00
|
|
|
/**
|
|
|
|
* Miscellaneous helpers for common patterns.
|
|
|
|
*/
|
|
|
|
|
2012-08-02 13:26:52 -05:00
|
|
|
/// The identity function.
|
|
|
|
pure fn id<T>(+x: T) -> T { x }
|
|
|
|
|
2012-08-07 13:16:51 -05:00
|
|
|
/// Ignores a value.
|
|
|
|
pure fn ignore<T>(+_x: T) { }
|
|
|
|
|
2012-08-01 18:04:43 -05:00
|
|
|
/**
|
|
|
|
* Swap the values at two mutable locations of the same type, without
|
|
|
|
* deinitialising or copying either one.
|
|
|
|
*/
|
2012-08-02 13:40:42 -05:00
|
|
|
#[inline(always)]
|
2012-08-01 18:04:43 -05:00
|
|
|
fn swap<T>(x: &mut T, y: &mut T) {
|
|
|
|
*x <-> *y;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Replace the value at a mutable location with a new one, returning the old
|
|
|
|
* value, without deinitialising or copying either one.
|
|
|
|
*/
|
2012-08-02 13:40:42 -05:00
|
|
|
#[inline(always)]
|
2012-08-01 18:04:43 -05:00
|
|
|
fn replace<T>(dest: &mut T, +src: T) -> T {
|
|
|
|
let mut tmp = src;
|
|
|
|
swap(dest, &mut tmp);
|
|
|
|
tmp
|
|
|
|
}
|
|
|
|
|
|
|
|
/// A non-copyable dummy type.
|
2012-08-13 18:20:27 -05:00
|
|
|
class NonCopyable {
|
2012-08-01 18:04:43 -05:00
|
|
|
i: ();
|
|
|
|
new() { self.i = (); }
|
|
|
|
drop { }
|
|
|
|
}
|
|
|
|
|
|
|
|
mod tests {
|
2012-08-02 13:26:52 -05:00
|
|
|
#[test]
|
|
|
|
fn identity_crisis() {
|
|
|
|
// Writing a test for the identity function. How did it come to this?
|
|
|
|
let x = ~[{mut a: 5, b: false}];
|
|
|
|
assert x == id(copy x);
|
|
|
|
}
|
2012-08-01 18:04:43 -05:00
|
|
|
#[test]
|
|
|
|
fn test_swap() {
|
|
|
|
let mut x = 31337;
|
|
|
|
let mut y = 42;
|
|
|
|
swap(&mut x, &mut y);
|
|
|
|
assert x == 42;
|
|
|
|
assert y == 31337;
|
|
|
|
}
|
|
|
|
#[test]
|
|
|
|
fn test_replace() {
|
2012-08-13 18:20:27 -05:00
|
|
|
let mut x = some(NonCopyable());
|
2012-08-01 18:04:43 -05:00
|
|
|
let y = replace(&mut x, none);
|
|
|
|
assert x.is_none();
|
|
|
|
assert y.is_some();
|
|
|
|
}
|
|
|
|
}
|