anchor.rs

  1use crate::rope::TextDimension;
  2
  3use super::{Buffer, Content, FromAnchor, FullOffset, Point, ToOffset};
  4use anyhow::Result;
  5use std::{
  6    cmp::Ordering,
  7    fmt::{Debug, Formatter},
  8    ops::Range,
  9};
 10use sum_tree::{Bias, SumTree};
 11
 12#[derive(Clone, Eq, PartialEq, Debug, Hash)]
 13pub struct Anchor {
 14    pub full_offset: FullOffset,
 15    pub bias: Bias,
 16    pub version: clock::Global,
 17}
 18
 19#[derive(Clone)]
 20pub struct AnchorMap<T> {
 21    pub(crate) version: clock::Global,
 22    pub(crate) entries: Vec<((FullOffset, Bias), T)>,
 23}
 24
 25#[derive(Clone)]
 26pub struct AnchorSet(pub(crate) AnchorMap<()>);
 27
 28#[derive(Clone)]
 29pub struct AnchorRangeMap<T> {
 30    pub(crate) version: clock::Global,
 31    pub(crate) entries: Vec<(Range<(FullOffset, Bias)>, T)>,
 32}
 33
 34#[derive(Clone)]
 35pub struct AnchorRangeSet(pub(crate) AnchorRangeMap<()>);
 36
 37#[derive(Clone)]
 38pub struct AnchorRangeMultimap<T: Clone> {
 39    pub(crate) entries: SumTree<AnchorRangeMultimapEntry<T>>,
 40    pub(crate) version: clock::Global,
 41    pub(crate) start_bias: Bias,
 42    pub(crate) end_bias: Bias,
 43}
 44
 45#[derive(Clone)]
 46pub(crate) struct AnchorRangeMultimapEntry<T> {
 47    pub(crate) range: FullOffsetRange,
 48    pub(crate) value: T,
 49}
 50
 51#[derive(Clone, Debug)]
 52pub(crate) struct FullOffsetRange {
 53    pub(crate) start: FullOffset,
 54    pub(crate) end: FullOffset,
 55}
 56
 57#[derive(Clone, Debug)]
 58pub(crate) struct AnchorRangeMultimapSummary {
 59    start: FullOffset,
 60    end: FullOffset,
 61    min_start: FullOffset,
 62    max_end: FullOffset,
 63    count: usize,
 64}
 65
 66impl Anchor {
 67    pub fn min() -> Self {
 68        Self {
 69            full_offset: FullOffset(0),
 70            bias: Bias::Left,
 71            version: Default::default(),
 72        }
 73    }
 74
 75    pub fn max() -> Self {
 76        Self {
 77            full_offset: FullOffset::MAX,
 78            bias: Bias::Right,
 79            version: Default::default(),
 80        }
 81    }
 82
 83    pub fn cmp<'a>(&self, other: &Anchor, buffer: impl Into<Content<'a>>) -> Result<Ordering> {
 84        let buffer = buffer.into();
 85
 86        if self == other {
 87            return Ok(Ordering::Equal);
 88        }
 89
 90        let offset_comparison = if self.version == other.version {
 91            self.full_offset.cmp(&other.full_offset)
 92        } else {
 93            buffer
 94                .full_offset_for_anchor(self)
 95                .cmp(&buffer.full_offset_for_anchor(other))
 96        };
 97
 98        Ok(offset_comparison.then_with(|| self.bias.cmp(&other.bias)))
 99    }
100
101    pub fn bias_left(&self, buffer: &Buffer) -> Anchor {
102        if self.bias == Bias::Left {
103            self.clone()
104        } else {
105            buffer.anchor_before(self)
106        }
107    }
108
109    pub fn bias_right(&self, buffer: &Buffer) -> Anchor {
110        if self.bias == Bias::Right {
111            self.clone()
112        } else {
113            buffer.anchor_after(self)
114        }
115    }
116
117    pub fn summary<'a, D, C>(&self, content: C) -> D
118    where
119        D: TextDimension<'a>,
120        C: Into<Content<'a>>,
121    {
122        content.into().summary_for_anchor(self)
123    }
124}
125
126impl<T> AnchorMap<T> {
127    pub fn version(&self) -> &clock::Global {
128        &self.version
129    }
130
131    pub fn len(&self) -> usize {
132        self.entries.len()
133    }
134
135    pub fn iter<'a, D, C>(&'a self, content: C) -> impl Iterator<Item = (D, &'a T)> + 'a
136    where
137        D: 'a + TextDimension<'a>,
138        C: 'a + Into<Content<'a>>,
139    {
140        let content = content.into();
141        content
142            .summaries_for_anchors(self)
143            .map(move |(sum, value)| (sum, value))
144    }
145}
146
147impl AnchorSet {
148    pub fn version(&self) -> &clock::Global {
149        &self.0.version
150    }
151
152    pub fn len(&self) -> usize {
153        self.0.len()
154    }
155
156    pub fn iter<'a, D, C>(&'a self, content: C) -> impl Iterator<Item = D> + 'a
157    where
158        D: 'a + TextDimension<'a>,
159        C: 'a + Into<Content<'a>>,
160    {
161        self.0.iter(content).map(|(position, _)| position)
162    }
163}
164
165impl<T> AnchorRangeMap<T> {
166    pub fn version(&self) -> &clock::Global {
167        &self.version
168    }
169
170    pub fn len(&self) -> usize {
171        self.entries.len()
172    }
173
174    pub fn from_full_offset_ranges(
175        version: clock::Global,
176        entries: Vec<(Range<(FullOffset, Bias)>, T)>,
177    ) -> Self {
178        Self { version, entries }
179    }
180
181    pub fn ranges<'a, D>(
182        &'a self,
183        content: impl Into<Content<'a>> + 'a,
184    ) -> impl Iterator<Item = (Range<D>, &'a T)> + 'a
185    where
186        D: 'a + TextDimension<'a>,
187    {
188        let content = content.into();
189        content.summaries_for_anchor_ranges(self)
190    }
191
192    pub fn full_offset_ranges(&self) -> impl Iterator<Item = (Range<FullOffset>, &T)> {
193        self.entries
194            .iter()
195            .map(|(range, value)| (range.start.0..range.end.0, value))
196    }
197}
198
199impl<T: PartialEq> PartialEq for AnchorRangeMap<T> {
200    fn eq(&self, other: &Self) -> bool {
201        self.version == other.version && self.entries == other.entries
202    }
203}
204
205impl<T: Eq> Eq for AnchorRangeMap<T> {}
206
207impl<T: Debug> Debug for AnchorRangeMap<T> {
208    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
209        let mut f = f.debug_map();
210        for (range, value) in &self.entries {
211            f.key(range);
212            f.value(value);
213        }
214        f.finish()
215    }
216}
217
218impl Debug for AnchorRangeSet {
219    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
220        let mut f = f.debug_set();
221        for (range, _) in &self.0.entries {
222            f.entry(range);
223        }
224        f.finish()
225    }
226}
227
228impl AnchorRangeSet {
229    pub fn len(&self) -> usize {
230        self.0.len()
231    }
232
233    pub fn version(&self) -> &clock::Global {
234        self.0.version()
235    }
236
237    pub fn ranges<'a, D, C>(&'a self, content: C) -> impl 'a + Iterator<Item = Range<Point>>
238    where
239        D: 'a + TextDimension<'a>,
240        C: 'a + Into<Content<'a>>,
241    {
242        self.0.ranges(content).map(|(range, _)| range)
243    }
244}
245
246impl<T: Clone> Default for AnchorRangeMultimap<T> {
247    fn default() -> Self {
248        Self {
249            entries: Default::default(),
250            version: Default::default(),
251            start_bias: Bias::Left,
252            end_bias: Bias::Left,
253        }
254    }
255}
256
257impl<T: Clone> AnchorRangeMultimap<T> {
258    pub fn version(&self) -> &clock::Global {
259        &self.version
260    }
261
262    pub fn intersecting_ranges<'a, I, O>(
263        &'a self,
264        range: Range<I>,
265        content: Content<'a>,
266        inclusive: bool,
267    ) -> impl Iterator<Item = (usize, Range<O>, &T)> + 'a
268    where
269        I: ToOffset,
270        O: FromAnchor,
271    {
272        let end_bias = if inclusive { Bias::Right } else { Bias::Left };
273        let range = range.start.to_full_offset(&content, Bias::Left)
274            ..range.end.to_full_offset(&content, end_bias);
275        let mut cursor = self.entries.filter::<_, usize>(
276            {
277                let content = content.clone();
278                let mut endpoint = Anchor {
279                    full_offset: FullOffset(0),
280                    bias: Bias::Right,
281                    version: self.version.clone(),
282                };
283                move |summary: &AnchorRangeMultimapSummary| {
284                    endpoint.full_offset = summary.max_end;
285                    endpoint.bias = self.end_bias;
286                    let max_end = endpoint.to_full_offset(&content, self.end_bias);
287                    let start_cmp = range.start.cmp(&max_end);
288
289                    endpoint.full_offset = summary.min_start;
290                    endpoint.bias = self.start_bias;
291                    let min_start = endpoint.to_full_offset(&content, self.start_bias);
292                    let end_cmp = range.end.cmp(&min_start);
293
294                    if inclusive {
295                        start_cmp <= Ordering::Equal && end_cmp >= Ordering::Equal
296                    } else {
297                        start_cmp == Ordering::Less && end_cmp == Ordering::Greater
298                    }
299                }
300            },
301            &(),
302        );
303
304        std::iter::from_fn({
305            let mut endpoint = Anchor {
306                full_offset: FullOffset(0),
307                bias: Bias::Left,
308                version: self.version.clone(),
309            };
310            move || {
311                if let Some(item) = cursor.item() {
312                    let ix = *cursor.start();
313                    endpoint.full_offset = item.range.start;
314                    endpoint.bias = self.start_bias;
315                    let start = O::from_anchor(&endpoint, &content);
316                    endpoint.full_offset = item.range.end;
317                    endpoint.bias = self.end_bias;
318                    let end = O::from_anchor(&endpoint, &content);
319                    let value = &item.value;
320                    cursor.next(&());
321                    Some((ix, start..end, value))
322                } else {
323                    None
324                }
325            }
326        })
327    }
328
329    pub fn from_full_offset_ranges(
330        version: clock::Global,
331        start_bias: Bias,
332        end_bias: Bias,
333        entries: impl Iterator<Item = (Range<FullOffset>, T)>,
334    ) -> Self {
335        Self {
336            version,
337            start_bias,
338            end_bias,
339            entries: SumTree::from_iter(
340                entries.map(|(range, value)| AnchorRangeMultimapEntry {
341                    range: FullOffsetRange {
342                        start: range.start,
343                        end: range.end,
344                    },
345                    value,
346                }),
347                &(),
348            ),
349        }
350    }
351
352    pub fn full_offset_ranges(&self) -> impl Iterator<Item = (Range<FullOffset>, &T)> {
353        self.entries
354            .cursor::<()>()
355            .map(|entry| (entry.range.start..entry.range.end, &entry.value))
356    }
357}
358
359impl<T: Clone> sum_tree::Item for AnchorRangeMultimapEntry<T> {
360    type Summary = AnchorRangeMultimapSummary;
361
362    fn summary(&self) -> Self::Summary {
363        AnchorRangeMultimapSummary {
364            start: self.range.start,
365            end: self.range.end,
366            min_start: self.range.start,
367            max_end: self.range.end,
368            count: 1,
369        }
370    }
371}
372
373impl Default for AnchorRangeMultimapSummary {
374    fn default() -> Self {
375        Self {
376            start: FullOffset(0),
377            end: FullOffset::MAX,
378            min_start: FullOffset::MAX,
379            max_end: FullOffset(0),
380            count: 0,
381        }
382    }
383}
384
385impl sum_tree::Summary for AnchorRangeMultimapSummary {
386    type Context = ();
387
388    fn add_summary(&mut self, other: &Self, _: &Self::Context) {
389        self.min_start = self.min_start.min(other.min_start);
390        self.max_end = self.max_end.max(other.max_end);
391
392        #[cfg(debug_assertions)]
393        {
394            let start_comparison = self.start.cmp(&other.start);
395            assert!(start_comparison <= Ordering::Equal);
396            if start_comparison == Ordering::Equal {
397                assert!(self.end.cmp(&other.end) >= Ordering::Equal);
398            }
399        }
400
401        self.start = other.start;
402        self.end = other.end;
403        self.count += other.count;
404    }
405}
406
407impl Default for FullOffsetRange {
408    fn default() -> Self {
409        Self {
410            start: FullOffset(0),
411            end: FullOffset::MAX,
412        }
413    }
414}
415
416impl<'a> sum_tree::Dimension<'a, AnchorRangeMultimapSummary> for usize {
417    fn add_summary(&mut self, summary: &'a AnchorRangeMultimapSummary, _: &()) {
418        *self += summary.count;
419    }
420}
421
422impl<'a> sum_tree::Dimension<'a, AnchorRangeMultimapSummary> for FullOffsetRange {
423    fn add_summary(&mut self, summary: &'a AnchorRangeMultimapSummary, _: &()) {
424        self.start = summary.start;
425        self.end = summary.end;
426    }
427}
428
429impl<'a> sum_tree::SeekTarget<'a, AnchorRangeMultimapSummary, FullOffsetRange> for FullOffsetRange {
430    fn cmp(&self, cursor_location: &FullOffsetRange, _: &()) -> Ordering {
431        Ord::cmp(&self.start, &cursor_location.start)
432            .then_with(|| Ord::cmp(&cursor_location.end, &self.end))
433    }
434}
435
436pub trait AnchorRangeExt {
437    fn cmp<'a>(&self, b: &Range<Anchor>, buffer: impl Into<Content<'a>>) -> Result<Ordering>;
438}
439
440impl AnchorRangeExt for Range<Anchor> {
441    fn cmp<'a>(&self, other: &Range<Anchor>, buffer: impl Into<Content<'a>>) -> Result<Ordering> {
442        let buffer = buffer.into();
443        Ok(match self.start.cmp(&other.start, &buffer)? {
444            Ordering::Equal => other.end.cmp(&self.end, buffer)?,
445            ord @ _ => ord,
446        })
447    }
448}