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) bias: Bias,
23 pub(crate) entries: Vec<(FullOffset, T)>,
24}
25
26#[derive(Clone)]
27pub struct AnchorSet(pub(crate) AnchorMap<()>);
28
29#[derive(Clone)]
30pub struct AnchorRangeMap<T> {
31 pub(crate) version: clock::Global,
32 pub(crate) entries: Vec<(Range<FullOffset>, T)>,
33 pub(crate) start_bias: Bias,
34 pub(crate) end_bias: Bias,
35}
36
37#[derive(Clone)]
38pub struct AnchorRangeSet(pub(crate) AnchorRangeMap<()>);
39
40#[derive(Clone)]
41pub struct AnchorRangeMultimap<T: Clone> {
42 pub(crate) entries: SumTree<AnchorRangeMultimapEntry<T>>,
43 pub(crate) version: clock::Global,
44 pub(crate) start_bias: Bias,
45 pub(crate) end_bias: Bias,
46}
47
48#[derive(Clone)]
49pub(crate) struct AnchorRangeMultimapEntry<T> {
50 pub(crate) range: FullOffsetRange,
51 pub(crate) value: T,
52}
53
54#[derive(Clone, Debug)]
55pub(crate) struct FullOffsetRange {
56 pub(crate) start: FullOffset,
57 pub(crate) end: FullOffset,
58}
59
60#[derive(Clone, Debug)]
61pub(crate) struct AnchorRangeMultimapSummary {
62 start: FullOffset,
63 end: FullOffset,
64 min_start: FullOffset,
65 max_end: FullOffset,
66 count: usize,
67}
68
69impl Anchor {
70 pub fn min() -> Self {
71 Self {
72 full_offset: FullOffset(0),
73 bias: Bias::Left,
74 version: Default::default(),
75 }
76 }
77
78 pub fn max() -> Self {
79 Self {
80 full_offset: FullOffset::MAX,
81 bias: Bias::Right,
82 version: Default::default(),
83 }
84 }
85
86 pub fn cmp<'a>(&self, other: &Anchor, buffer: impl Into<Content<'a>>) -> Result<Ordering> {
87 let buffer = buffer.into();
88
89 if self == other {
90 return Ok(Ordering::Equal);
91 }
92
93 let offset_comparison = if self.version == other.version {
94 self.full_offset.cmp(&other.full_offset)
95 } else {
96 buffer
97 .full_offset_for_anchor(self)
98 .cmp(&buffer.full_offset_for_anchor(other))
99 };
100
101 Ok(offset_comparison.then_with(|| self.bias.cmp(&other.bias)))
102 }
103
104 pub fn bias_left(&self, buffer: &Buffer) -> Anchor {
105 if self.bias == Bias::Left {
106 self.clone()
107 } else {
108 buffer.anchor_before(self)
109 }
110 }
111
112 pub fn bias_right(&self, buffer: &Buffer) -> Anchor {
113 if self.bias == Bias::Right {
114 self.clone()
115 } else {
116 buffer.anchor_after(self)
117 }
118 }
119
120 pub fn summary<'a, D, C>(&self, content: C) -> D
121 where
122 D: TextDimension<'a>,
123 C: Into<Content<'a>>,
124 {
125 content.into().summary_for_anchor(self)
126 }
127}
128
129impl<T> AnchorMap<T> {
130 pub fn version(&self) -> &clock::Global {
131 &self.version
132 }
133
134 pub fn len(&self) -> usize {
135 self.entries.len()
136 }
137
138 pub fn iter<'a, D, C>(&'a self, content: C) -> impl Iterator<Item = (D, &'a T)> + 'a
139 where
140 D: 'a + TextDimension<'a>,
141 C: 'a + Into<Content<'a>>,
142 {
143 let content = content.into();
144 content
145 .summaries_for_anchors(
146 self.version.clone(),
147 self.bias,
148 self.entries.iter().map(|e| &e.0),
149 )
150 .zip(self.entries.iter().map(|e| &e.1))
151 }
152}
153
154impl AnchorSet {
155 pub fn version(&self) -> &clock::Global {
156 &self.0.version
157 }
158
159 pub fn len(&self) -> usize {
160 self.0.len()
161 }
162
163 pub fn iter<'a, D, C>(&'a self, content: C) -> impl Iterator<Item = D> + 'a
164 where
165 D: 'a + TextDimension<'a>,
166 C: 'a + Into<Content<'a>>,
167 {
168 self.0.iter(content).map(|(position, _)| position)
169 }
170}
171
172impl<T> AnchorRangeMap<T> {
173 pub fn version(&self) -> &clock::Global {
174 &self.version
175 }
176
177 pub fn len(&self) -> usize {
178 self.entries.len()
179 }
180
181 pub fn from_full_offset_ranges(
182 version: clock::Global,
183 start_bias: Bias,
184 end_bias: Bias,
185 entries: Vec<(Range<FullOffset>, T)>,
186 ) -> Self {
187 Self {
188 version,
189 start_bias,
190 end_bias,
191 entries,
192 }
193 }
194
195 pub fn ranges<'a, D>(
196 &'a self,
197 content: impl Into<Content<'a>> + 'a,
198 ) -> impl Iterator<Item = (Range<D>, &'a T)> + 'a
199 where
200 D: 'a + TextDimension<'a>,
201 {
202 let content = content.into();
203 content
204 .summaries_for_anchor_ranges(
205 self.version.clone(),
206 self.start_bias,
207 self.end_bias,
208 self.entries.iter().map(|e| &e.0),
209 )
210 .zip(self.entries.iter().map(|e| &e.1))
211 }
212
213 pub fn intersecting_ranges<'a, D, T>(
214 &'a self,
215 range: Range<(T, Bias)>,
216 content: impl Into<Content<'a>> + 'a,
217 ) -> impl Iterator<Item = (Range<D>, &'a T)> + 'a
218 where
219 D: 'a + TextDimension<'a>,
220 T: ToOffset,
221 {
222 let content = content.into();
223 let range = content.anchor_at(range.start.0, range.start.1)
224 ..content.anchor_at(range.end.0, range.end.1);
225
226 let mut probe_anchor = Anchor {
227 full_offset: Default::default(),
228 bias: self.start_bias,
229 version: self.version.clone(),
230 };
231 let start_ix = self.entries.binary_search_by(|probe| {
232 probe_anchor.full_offset = probe.0.start;
233 probe_anchor.cmp(&range.start, &content).unwrap()
234 });
235 std::iter::empty()
236 }
237
238 pub fn full_offset_ranges(&self) -> impl Iterator<Item = &(Range<FullOffset>, T)> {
239 self.entries.iter()
240 }
241
242 pub fn min_by_key<'a, C, D, F, K>(
243 &self,
244 content: C,
245 mut extract_key: F,
246 ) -> Option<(Range<D>, &T)>
247 where
248 C: Into<Content<'a>>,
249 D: 'a + TextDimension<'a>,
250 F: FnMut(&T) -> K,
251 K: Ord,
252 {
253 let content = content.into();
254 self.entries
255 .iter()
256 .min_by_key(|(_, value)| extract_key(value))
257 .map(|(range, value)| (self.resolve_range(range, &content), value))
258 }
259
260 pub fn max_by_key<'a, C, D, F, K>(
261 &self,
262 content: C,
263 mut extract_key: F,
264 ) -> Option<(Range<D>, &T)>
265 where
266 C: Into<Content<'a>>,
267 D: 'a + TextDimension<'a>,
268 F: FnMut(&T) -> K,
269 K: Ord,
270 {
271 let content = content.into();
272 self.entries
273 .iter()
274 .max_by_key(|(_, value)| extract_key(value))
275 .map(|(range, value)| (self.resolve_range(range, &content), value))
276 }
277
278 fn resolve_range<'a, D>(&self, range: &Range<FullOffset>, content: &Content<'a>) -> Range<D>
279 where
280 D: 'a + TextDimension<'a>,
281 {
282 let mut anchor = Anchor {
283 full_offset: range.start,
284 bias: self.start_bias,
285 version: self.version.clone(),
286 };
287 let start = content.summary_for_anchor(&anchor);
288
289 anchor.full_offset = range.end;
290 anchor.bias = self.end_bias;
291 let end = content.summary_for_anchor(&anchor);
292
293 start..end
294 }
295}
296
297impl<T: PartialEq> PartialEq for AnchorRangeMap<T> {
298 fn eq(&self, other: &Self) -> bool {
299 self.version == other.version && self.entries == other.entries
300 }
301}
302
303impl<T: Eq> Eq for AnchorRangeMap<T> {}
304
305impl<T: Debug> Debug for AnchorRangeMap<T> {
306 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
307 let mut f = f.debug_map();
308 for (range, value) in &self.entries {
309 f.key(range);
310 f.value(value);
311 }
312 f.finish()
313 }
314}
315
316impl Debug for AnchorRangeSet {
317 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
318 let mut f = f.debug_set();
319 for (range, _) in &self.0.entries {
320 f.entry(range);
321 }
322 f.finish()
323 }
324}
325
326impl AnchorRangeSet {
327 pub fn len(&self) -> usize {
328 self.0.len()
329 }
330
331 pub fn version(&self) -> &clock::Global {
332 self.0.version()
333 }
334
335 pub fn ranges<'a, D, C>(&'a self, content: C) -> impl 'a + Iterator<Item = Range<Point>>
336 where
337 D: 'a + TextDimension<'a>,
338 C: 'a + Into<Content<'a>>,
339 {
340 self.0.ranges(content).map(|(range, _)| range)
341 }
342}
343
344impl<T: Clone> Default for AnchorRangeMultimap<T> {
345 fn default() -> Self {
346 Self {
347 entries: Default::default(),
348 version: Default::default(),
349 start_bias: Bias::Left,
350 end_bias: Bias::Left,
351 }
352 }
353}
354
355impl<T: Clone> AnchorRangeMultimap<T> {
356 pub fn version(&self) -> &clock::Global {
357 &self.version
358 }
359
360 pub fn intersecting_ranges<'a, I, O>(
361 &'a self,
362 range: Range<I>,
363 content: Content<'a>,
364 inclusive: bool,
365 ) -> impl Iterator<Item = (usize, Range<O>, &T)> + 'a
366 where
367 I: ToOffset,
368 O: FromAnchor,
369 {
370 let end_bias = if inclusive { Bias::Right } else { Bias::Left };
371 let range = range.start.to_full_offset(&content, Bias::Left)
372 ..range.end.to_full_offset(&content, end_bias);
373 let mut cursor = self.entries.filter::<_, usize>(
374 {
375 let content = content.clone();
376 let mut endpoint = Anchor {
377 full_offset: FullOffset(0),
378 bias: Bias::Right,
379 version: self.version.clone(),
380 };
381 move |summary: &AnchorRangeMultimapSummary| {
382 endpoint.full_offset = summary.max_end;
383 endpoint.bias = self.end_bias;
384 let max_end = endpoint.to_full_offset(&content, self.end_bias);
385 let start_cmp = range.start.cmp(&max_end);
386
387 endpoint.full_offset = summary.min_start;
388 endpoint.bias = self.start_bias;
389 let min_start = endpoint.to_full_offset(&content, self.start_bias);
390 let end_cmp = range.end.cmp(&min_start);
391
392 if inclusive {
393 start_cmp <= Ordering::Equal && end_cmp >= Ordering::Equal
394 } else {
395 start_cmp == Ordering::Less && end_cmp == Ordering::Greater
396 }
397 }
398 },
399 &(),
400 );
401
402 std::iter::from_fn({
403 let mut endpoint = Anchor {
404 full_offset: FullOffset(0),
405 bias: Bias::Left,
406 version: self.version.clone(),
407 };
408 move || {
409 if let Some(item) = cursor.item() {
410 let ix = *cursor.start();
411 endpoint.full_offset = item.range.start;
412 endpoint.bias = self.start_bias;
413 let start = O::from_anchor(&endpoint, &content);
414 endpoint.full_offset = item.range.end;
415 endpoint.bias = self.end_bias;
416 let end = O::from_anchor(&endpoint, &content);
417 let value = &item.value;
418 cursor.next(&());
419 Some((ix, start..end, value))
420 } else {
421 None
422 }
423 }
424 })
425 }
426
427 pub fn from_full_offset_ranges(
428 version: clock::Global,
429 start_bias: Bias,
430 end_bias: Bias,
431 entries: impl Iterator<Item = (Range<FullOffset>, T)>,
432 ) -> Self {
433 Self {
434 version,
435 start_bias,
436 end_bias,
437 entries: SumTree::from_iter(
438 entries.map(|(range, value)| AnchorRangeMultimapEntry {
439 range: FullOffsetRange {
440 start: range.start,
441 end: range.end,
442 },
443 value,
444 }),
445 &(),
446 ),
447 }
448 }
449
450 pub fn full_offset_ranges(&self) -> impl Iterator<Item = (Range<FullOffset>, &T)> {
451 self.entries
452 .cursor::<()>()
453 .map(|entry| (entry.range.start..entry.range.end, &entry.value))
454 }
455
456 pub fn filter<'a, O, F>(
457 &'a self,
458 content: Content<'a>,
459 mut f: F,
460 ) -> impl 'a + Iterator<Item = (usize, Range<O>, &T)>
461 where
462 O: FromAnchor,
463 F: 'a + FnMut(&'a T) -> bool,
464 {
465 let mut endpoint = Anchor {
466 full_offset: FullOffset(0),
467 bias: Bias::Left,
468 version: self.version.clone(),
469 };
470 self.entries
471 .cursor::<()>()
472 .enumerate()
473 .filter_map(move |(ix, entry)| {
474 if f(&entry.value) {
475 endpoint.full_offset = entry.range.start;
476 endpoint.bias = self.start_bias;
477 let start = O::from_anchor(&endpoint, &content);
478 endpoint.full_offset = entry.range.end;
479 endpoint.bias = self.end_bias;
480 let end = O::from_anchor(&endpoint, &content);
481 Some((ix, start..end, &entry.value))
482 } else {
483 None
484 }
485 })
486 }
487}
488
489impl<T: Clone> sum_tree::Item for AnchorRangeMultimapEntry<T> {
490 type Summary = AnchorRangeMultimapSummary;
491
492 fn summary(&self) -> Self::Summary {
493 AnchorRangeMultimapSummary {
494 start: self.range.start,
495 end: self.range.end,
496 min_start: self.range.start,
497 max_end: self.range.end,
498 count: 1,
499 }
500 }
501}
502
503impl Default for AnchorRangeMultimapSummary {
504 fn default() -> Self {
505 Self {
506 start: FullOffset(0),
507 end: FullOffset::MAX,
508 min_start: FullOffset::MAX,
509 max_end: FullOffset(0),
510 count: 0,
511 }
512 }
513}
514
515impl sum_tree::Summary for AnchorRangeMultimapSummary {
516 type Context = ();
517
518 fn add_summary(&mut self, other: &Self, _: &Self::Context) {
519 self.min_start = self.min_start.min(other.min_start);
520 self.max_end = self.max_end.max(other.max_end);
521
522 #[cfg(debug_assertions)]
523 {
524 let start_comparison = self.start.cmp(&other.start);
525 assert!(start_comparison <= Ordering::Equal);
526 if start_comparison == Ordering::Equal {
527 assert!(self.end.cmp(&other.end) >= Ordering::Equal);
528 }
529 }
530
531 self.start = other.start;
532 self.end = other.end;
533 self.count += other.count;
534 }
535}
536
537impl Default for FullOffsetRange {
538 fn default() -> Self {
539 Self {
540 start: FullOffset(0),
541 end: FullOffset::MAX,
542 }
543 }
544}
545
546impl<'a> sum_tree::Dimension<'a, AnchorRangeMultimapSummary> for usize {
547 fn add_summary(&mut self, summary: &'a AnchorRangeMultimapSummary, _: &()) {
548 *self += summary.count;
549 }
550}
551
552impl<'a> sum_tree::Dimension<'a, AnchorRangeMultimapSummary> for FullOffsetRange {
553 fn add_summary(&mut self, summary: &'a AnchorRangeMultimapSummary, _: &()) {
554 self.start = summary.start;
555 self.end = summary.end;
556 }
557}
558
559impl<'a> sum_tree::SeekTarget<'a, AnchorRangeMultimapSummary, FullOffsetRange> for FullOffsetRange {
560 fn cmp(&self, cursor_location: &FullOffsetRange, _: &()) -> Ordering {
561 Ord::cmp(&self.start, &cursor_location.start)
562 .then_with(|| Ord::cmp(&cursor_location.end, &self.end))
563 }
564}
565
566pub trait AnchorRangeExt {
567 fn cmp<'a>(&self, b: &Range<Anchor>, buffer: impl Into<Content<'a>>) -> Result<Ordering>;
568 fn to_offset<'a>(&self, content: impl Into<Content<'a>>) -> Range<usize>;
569}
570
571impl AnchorRangeExt for Range<Anchor> {
572 fn cmp<'a>(&self, other: &Range<Anchor>, buffer: impl Into<Content<'a>>) -> Result<Ordering> {
573 let buffer = buffer.into();
574 Ok(match self.start.cmp(&other.start, &buffer)? {
575 Ordering::Equal => other.end.cmp(&self.end, buffer)?,
576 ord @ _ => ord,
577 })
578 }
579
580 fn to_offset<'a>(&self, content: impl Into<Content<'a>>) -> Range<usize> {
581 let content = content.into();
582 self.start.to_offset(&content)..self.end.to_offset(&content)
583 }
584}