1use smallvec::{smallvec, SmallVec};
2use std::iter;
3use std::sync::LazyLock;
4
5static MIN: LazyLock<Locator> = LazyLock::new(Locator::min);
6static MAX: LazyLock<Locator> = LazyLock::new(Locator::max);
7
8/// An identifier for a position in a ordered collection.
9///
10/// Allows prepending and appending without needing to renumber existing locators
11/// using `Locator::between(lhs, rhs)`.
12///
13/// The initial location for a collection should be `Locator::between(Locator::min(), Locator::max())`,
14/// leaving room for items to be inserted before and after it.
15#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
16pub struct Locator(SmallVec<[u64; 4]>);
17
18impl Locator {
19 pub fn min() -> Self {
20 Self(smallvec![u64::MIN])
21 }
22
23 pub fn max() -> Self {
24 Self(smallvec![u64::MAX])
25 }
26
27 pub fn min_ref() -> &'static Self {
28 &MIN
29 }
30
31 pub fn max_ref() -> &'static Self {
32 &MAX
33 }
34
35 pub fn assign(&mut self, other: &Self) {
36 self.0.resize(other.0.len(), 0);
37 self.0.copy_from_slice(&other.0);
38 }
39
40 pub fn between(lhs: &Self, rhs: &Self) -> Self {
41 let lhs = lhs.0.iter().copied().chain(iter::repeat(u64::MIN));
42 let rhs = rhs.0.iter().copied().chain(iter::repeat(u64::MAX));
43 let mut location = SmallVec::new();
44 for (lhs, rhs) in lhs.zip(rhs) {
45 let mid = lhs + ((rhs.saturating_sub(lhs)) >> 48);
46 location.push(mid);
47 if mid > lhs {
48 break;
49 }
50 }
51 Self(location)
52 }
53
54 pub fn len(&self) -> usize {
55 self.0.len()
56 }
57
58 pub fn is_empty(&self) -> bool {
59 self.len() == 0
60 }
61}
62
63impl Default for Locator {
64 fn default() -> Self {
65 Self::min()
66 }
67}
68
69impl sum_tree::Item for Locator {
70 type Summary = Locator;
71
72 fn summary(&self) -> Self::Summary {
73 self.clone()
74 }
75}
76
77impl sum_tree::KeyedItem for Locator {
78 type Key = Locator;
79
80 fn key(&self) -> Self::Key {
81 self.clone()
82 }
83}
84
85impl sum_tree::Summary for Locator {
86 type Context = ();
87
88 fn add_summary(&mut self, summary: &Self, _: &()) {
89 self.assign(summary);
90 }
91}
92
93#[cfg(test)]
94mod tests {
95 use super::*;
96 use rand::prelude::*;
97 use std::mem;
98
99 #[gpui::test(iterations = 100)]
100 fn test_locators(mut rng: StdRng) {
101 let mut lhs = Default::default();
102 let mut rhs = Default::default();
103 while lhs == rhs {
104 lhs = Locator(
105 (0..rng.gen_range(1..=5))
106 .map(|_| rng.gen_range(0..=100))
107 .collect(),
108 );
109 rhs = Locator(
110 (0..rng.gen_range(1..=5))
111 .map(|_| rng.gen_range(0..=100))
112 .collect(),
113 );
114 }
115
116 if lhs > rhs {
117 mem::swap(&mut lhs, &mut rhs);
118 }
119
120 let middle = Locator::between(&lhs, &rhs);
121 assert!(middle > lhs);
122 assert!(middle < rhs);
123 for ix in 0..middle.0.len() - 1 {
124 assert!(
125 middle.0[ix] == *lhs.0.get(ix).unwrap_or(&0)
126 || middle.0[ix] == *rhs.0.get(ix).unwrap_or(&0)
127 );
128 }
129 }
130}