locator.rs

 1use lazy_static::lazy_static;
 2use smallvec::{smallvec, SmallVec};
 3use std::iter;
 4
 5lazy_static! {
 6    pub static ref MIN: Locator = Locator::min();
 7    pub static ref MAX: Locator = Locator::max();
 8}
 9
10#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
11pub struct Locator(SmallVec<[u64; 4]>);
12
13impl Locator {
14    pub fn min() -> Self {
15        Self(smallvec![u64::MIN])
16    }
17
18    pub fn max() -> Self {
19        Self(smallvec![u64::MAX])
20    }
21
22    pub fn assign(&mut self, other: &Self) {
23        self.0.resize(other.0.len(), 0);
24        self.0.copy_from_slice(&other.0);
25    }
26
27    pub fn between(lhs: &Self, rhs: &Self) -> Self {
28        let lhs = lhs.0.iter().copied().chain(iter::repeat(u64::MIN));
29        let rhs = rhs.0.iter().copied().chain(iter::repeat(u64::MAX));
30        let mut location = SmallVec::new();
31        for (lhs, rhs) in lhs.zip(rhs) {
32            let mid = lhs + ((rhs.saturating_sub(lhs)) >> 48);
33            location.push(mid);
34            if mid > lhs {
35                break;
36            }
37        }
38        Self(location)
39    }
40
41    pub fn len(&self) -> usize {
42        self.0.len()
43    }
44}
45
46impl Default for Locator {
47    fn default() -> Self {
48        Self::min()
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55    use rand::prelude::*;
56    use std::mem;
57
58    #[gpui::test(iterations = 100)]
59    fn test_locators(mut rng: StdRng) {
60        let mut lhs = Default::default();
61        let mut rhs = Default::default();
62        while lhs == rhs {
63            lhs = Locator(
64                (0..rng.gen_range(1..=5))
65                    .map(|_| rng.gen_range(0..=100))
66                    .collect(),
67            );
68            rhs = Locator(
69                (0..rng.gen_range(1..=5))
70                    .map(|_| rng.gen_range(0..=100))
71                    .collect(),
72            );
73        }
74
75        if lhs > rhs {
76            mem::swap(&mut lhs, &mut rhs);
77        }
78
79        let middle = Locator::between(&lhs, &rhs);
80        assert!(middle > lhs);
81        assert!(middle < rhs);
82        for ix in 0..middle.0.len() - 1 {
83            assert!(
84                middle.0[ix] == *lhs.0.get(ix).unwrap_or(&0)
85                    || middle.0[ix] == *rhs.0.get(ix).unwrap_or(&0)
86            );
87        }
88    }
89}