diff options
| author | Ben Blum <bblum@andrew.cmu.edu> | 2012-08-01 19:04:43 -0400 |
|---|---|---|
| committer | Ben Blum <bblum@andrew.cmu.edu> | 2012-08-01 19:07:28 -0400 |
| commit | 90ce3d94e45233f8aa49e40b1e8a2efc7a0f35ef (patch) | |
| tree | efd0d921ebf95bf98ac75116315aa167e7ab60d4 /src | |
| parent | 6fdd1ef9b18039eb29d8c8ba322883a565e94e43 (diff) | |
| download | rust-90ce3d94e45233f8aa49e40b1e8a2efc7a0f35ef.tar.gz rust-90ce3d94e45233f8aa49e40b1e8a2efc7a0f35ef.zip | |
Add core::util, with swap, replace, and noncopyable
Diffstat (limited to 'src')
| -rw-r--r-- | src/libcore/core.rc | 4 | ||||
| -rw-r--r-- | src/libcore/util.rs | 46 |
2 files changed, 50 insertions, 0 deletions
diff --git a/src/libcore/core.rc b/src/libcore/core.rc index 3dff701e875..ed9f642cc96 100644 --- a/src/libcore/core.rc +++ b/src/libcore/core.rc @@ -179,6 +179,10 @@ mod option_iter { mod result; mod to_str; mod to_bytes; +mod util; + +// Data structure modules + mod dvec; #[path="iter-trait"] mod dvec_iter { diff --git a/src/libcore/util.rs b/src/libcore/util.rs new file mode 100644 index 00000000000..0c7a54053b2 --- /dev/null +++ b/src/libcore/util.rs @@ -0,0 +1,46 @@ +/** + * Miscellaneous helpers for common patterns. + */ + +/** + * Swap the values at two mutable locations of the same type, without + * deinitialising or copying either one. + */ +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. + */ +fn replace<T>(dest: &mut T, +src: T) -> T { + let mut tmp = src; + swap(dest, &mut tmp); + tmp +} + +/// A non-copyable dummy type. +class noncopyable { + i: (); + new() { self.i = (); } + drop { } +} + +mod tests { + #[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() { + let mut x = some(noncopyable()); + let y = replace(&mut x, none); + assert x.is_none(); + assert y.is_some(); + } +} |
