1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use core::mem;
pub fn partition_slice<T, F>(s: &mut [T], mut p: F) -> usize
where
F: FnMut(&T) -> bool,
{
let mut i = s.iter_mut();
let mut pos = 0;
loop {
let head = loop {
match i.next() {
Some(head) => {
if !p(&head) {
break head;
}
}
None => return pos,
}
pos += 1;
};
let tail = loop {
match i.next_back() {
Some(tail) => {
if p(&tail) {
break tail;
}
}
None => return pos,
}
};
mem::swap(head, tail);
pos += 1;
}
}
#[cfg(test)]
mod tests {
use super::partition_slice;
use alloc::vec::Vec;
fn check(x: &[u32], want: &[u32]) {
assert_eq!(x.len(), want.len());
let want_count = want.iter().cloned().filter(|&x| x % 10 == 0).count();
let mut v = Vec::new();
v.extend(x.iter().cloned());
let count = partition_slice(&mut v[..], |&x| x % 10 == 0);
assert_eq!(v, want);
assert_eq!(count, want_count);
}
#[test]
fn empty() {
check(&[], &[]);
}
#[test]
fn singles() {
check(&[0], &[0]);
check(&[1], &[1]);
check(&[10], &[10]);
}
#[test]
fn doubles() {
check(&[0, 0], &[0, 0]);
check(&[0, 5], &[0, 5]);
check(&[5, 0], &[0, 5]);
check(&[5, 4], &[5, 4]);
}
#[test]
fn longer() {
check(&[1, 2, 3], &[1, 2, 3]);
check(&[1, 2, 10], &[10, 2, 1]);
check(&[1, 10, 2], &[10, 1, 2]);
check(&[1, 20, 10], &[10, 20, 1]);
check(&[1, 20, 3, 10], &[10, 20, 3, 1]);
check(&[20, 3, 10, 1], &[20, 10, 3, 1]);
}
}