rust/src/libcore/util.rs

88 lines
1.9 KiB
Rust
Raw Normal View History

2012-08-14 12:11:15 -07:00
// NB: transitionary, de-mode-ing.
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
2012-08-30 12:15:53 -07:00
use cmp::Eq;
/**
* Miscellaneous helpers for common patterns.
*/
2012-08-02 14:26:52 -04:00
/// The identity function.
2012-09-10 12:14:14 -07:00
pure fn id<T>(+x: T) -> T { move x }
2012-08-02 14:26:52 -04:00
2012-08-07 14:16:51 -04:00
/// Ignores a value.
pure fn ignore<T>(+_x: T) { }
/// Sets `*ptr` to `new_value`, invokes `op()`, and then restores the
/// original value of `*ptr`.
#[inline(always)]
fn with<T: Copy, R>(
ptr: &mut T,
+new_value: T,
op: &fn() -> R) -> R
{
// NDM: if swap operator were defined somewhat differently,
// we wouldn't need to copy...
let old_value = *ptr;
*ptr = move new_value;
let result = op();
*ptr = move old_value;
return move result;
}
/**
* Swap the values at two mutable locations of the same type, without
* deinitialising or copying either one.
*/
#[inline(always)]
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.
*/
#[inline(always)]
fn replace<T>(dest: &mut T, +src: T) -> T {
2012-09-10 12:14:14 -07:00
let mut tmp <- src;
swap(dest, &mut tmp);
2012-09-10 12:14:14 -07:00
move tmp
}
/// A non-copyable dummy type.
2012-08-15 18:46:55 -07:00
struct NonCopyable {
i: (),
drop { }
}
2012-09-04 15:23:28 -07:00
fn NonCopyable() -> NonCopyable { NonCopyable { i: () } }
mod tests {
2012-08-02 14:26:52 -04:00
#[test]
fn identity_crisis() {
// Writing a test for the identity function. How did it come to this?
2012-08-27 16:26:35 -07:00
let x = ~[(5, false)];
//FIXME #3387 assert x.eq(id(copy x));
let y = copy x;
assert x.eq(id(y));
2012-08-02 14:26:52 -04: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-20 12:23:37 -07:00
let mut x = Some(NonCopyable());
let y = replace(&mut x, None);
assert x.is_none();
assert y.is_some();
}
}