relay_server/utils/
split_off.rs

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
use itertools::Either;

/// Splits off items from a vector matching a predicate.
///
/// Matching elements are returned in the second vector.
pub fn split_off<T>(data: Vec<T>, mut f: impl FnMut(&T) -> bool) -> (Vec<T>, Vec<T>) {
    split_off_map(data, |item| {
        if f(&item) {
            Either::Right(item)
        } else {
            Either::Left(item)
        }
    })
}

/// Splits off items from a vector matching a predicate and mapping the removed items.
pub fn split_off_map<T, S>(data: Vec<T>, mut f: impl FnMut(T) -> Either<T, S>) -> (Vec<T>, Vec<S>) {
    let mut right = Vec::new();

    let left = data
        .into_iter()
        .filter_map(|item| match f(item) {
            Either::Left(item) => Some(item),
            Either::Right(p) => {
                right.push(p);
                None
            }
        })
        .collect();

    (left, right)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_split_off() {
        let data = vec!["apple", "apple", "orange"];

        let (apples, oranges) = split_off(data, |item| *item == "orange");
        assert_eq!(apples, vec!["apple", "apple"]);
        assert_eq!(oranges, vec!["orange"]);
    }

    #[test]
    fn test_split_off_map() {
        let data = vec!["apple", "apple", "orange"];

        let (apples, oranges) = split_off_map(data, |item| {
            if item != "orange" {
                Either::Left(item)
            } else {
                Either::Right(item)
            }
        });
        assert_eq!(apples, vec!["apple", "apple"]);
        assert_eq!(oranges, vec!["orange"]);
    }
}