Skip to content

Commit 90ce3d9

Browse files
committed
Add core::util, with swap, replace, and noncopyable
1 parent 6fdd1ef commit 90ce3d9

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

src/libcore/core.rc

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,10 @@ mod option_iter {
179179
mod result;
180180
mod to_str;
181181
mod to_bytes;
182+
mod util;
183+
184+
// Data structure modules
185+
182186
mod dvec;
183187
#[path="iter-trait"]
184188
mod dvec_iter {

src/libcore/util.rs

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* Miscellaneous helpers for common patterns.
3+
*/
4+
5+
/**
6+
* Swap the values at two mutable locations of the same type, without
7+
* deinitialising or copying either one.
8+
*/
9+
fn swap<T>(x: &mut T, y: &mut T) {
10+
*x <-> *y;
11+
}
12+
13+
/**
14+
* Replace the value at a mutable location with a new one, returning the old
15+
* value, without deinitialising or copying either one.
16+
*/
17+
fn replace<T>(dest: &mut T, +src: T) -> T {
18+
let mut tmp = src;
19+
swap(dest, &mut tmp);
20+
tmp
21+
}
22+
23+
/// A non-copyable dummy type.
24+
class noncopyable {
25+
i: ();
26+
new() { self.i = (); }
27+
drop { }
28+
}
29+
30+
mod tests {
31+
#[test]
32+
fn test_swap() {
33+
let mut x = 31337;
34+
let mut y = 42;
35+
swap(&mut x, &mut y);
36+
assert x == 42;
37+
assert y == 31337;
38+
}
39+
#[test]
40+
fn test_replace() {
41+
let mut x = some(noncopyable());
42+
let y = replace(&mut x, none);
43+
assert x.is_none();
44+
assert y.is_some();
45+
}
46+
}

0 commit comments

Comments
 (0)