util.rs

 1use rand::prelude::*;
 2use std::cmp::Ordering;
 3
 4pub fn post_inc(value: &mut usize) -> usize {
 5    let prev = *value;
 6    *value += 1;
 7    prev
 8}
 9
10/// Extend a sorted vector with a sorted sequence of items, maintaining the vector's sort order and
11/// enforcing a maximum length. Sort the items according to the given callback. Before calling this,
12/// both `vec` and `new_items` should already be sorted according to the `cmp` comparator.
13pub fn extend_sorted<T, I, F>(vec: &mut Vec<T>, new_items: I, limit: usize, mut cmp: F)
14where
15    I: IntoIterator<Item = T>,
16    F: FnMut(&T, &T) -> Ordering,
17{
18    let mut start_index = 0;
19    for new_item in new_items {
20        if let Err(i) = vec[start_index..].binary_search_by(|m| cmp(m, &new_item)) {
21            let index = start_index + i;
22            if vec.len() < limit {
23                vec.insert(index, new_item);
24            } else if index < vec.len() {
25                vec.pop();
26                vec.insert(index, new_item);
27            }
28            start_index = index;
29        }
30    }
31}
32
33pub struct RandomCharIter<T: Rng>(T);
34
35impl<T: Rng> RandomCharIter<T> {
36    pub fn new(rng: T) -> Self {
37        Self(rng)
38    }
39}
40
41impl<T: Rng> Iterator for RandomCharIter<T> {
42    type Item = char;
43
44    fn next(&mut self) -> Option<Self::Item> {
45        if self.0.gen_bool(1.0 / 5.0) {
46            Some('\n')
47        } else {
48            Some(self.0.gen_range(b'a'..b'z' + 1).into())
49        }
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56
57    #[test]
58    fn test_extend_sorted() {
59        let mut vec = vec![];
60
61        extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
62        assert_eq!(vec, &[21, 17, 13, 8, 1]);
63
64        extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
65        assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
66
67        extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
68        assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
69    }
70}