Merge branch 'fragment-locators' into HEAD

This commit is contained in:
Max Brunsfeld 2021-12-09 14:49:04 -08:00
commit 5e516f59c0
22 changed files with 1317 additions and 1280 deletions

View file

@ -1,94 +1,36 @@
use super::{FromAnchor, FullOffset, Point, ToOffset};
use super::{Point, ToOffset};
use crate::{rope::TextDimension, BufferSnapshot};
use anyhow::Result;
use std::{
cmp::Ordering,
fmt::{Debug, Formatter},
ops::Range,
};
use sum_tree::{Bias, SumTree};
use std::{cmp::Ordering, fmt::Debug, ops::Range};
use sum_tree::Bias;
#[derive(Clone, Eq, PartialEq, Debug, Hash)]
pub struct Anchor {
pub full_offset: FullOffset,
pub timestamp: clock::Local,
pub offset: usize,
pub bias: Bias,
pub version: clock::Global,
}
#[derive(Clone)]
pub struct AnchorMap<T> {
pub(crate) version: clock::Global,
pub(crate) bias: Bias,
pub(crate) entries: Vec<(FullOffset, T)>,
}
#[derive(Clone)]
pub struct AnchorSet(pub(crate) AnchorMap<()>);
#[derive(Clone)]
pub struct AnchorRangeMap<T> {
pub(crate) version: clock::Global,
pub(crate) entries: Vec<(Range<FullOffset>, T)>,
pub(crate) start_bias: Bias,
pub(crate) end_bias: Bias,
}
#[derive(Clone)]
pub struct AnchorRangeSet(pub(crate) AnchorRangeMap<()>);
#[derive(Clone)]
pub struct AnchorRangeMultimap<T: Clone> {
pub(crate) entries: SumTree<AnchorRangeMultimapEntry<T>>,
pub(crate) version: clock::Global,
pub(crate) start_bias: Bias,
pub(crate) end_bias: Bias,
}
#[derive(Clone)]
pub(crate) struct AnchorRangeMultimapEntry<T> {
pub(crate) range: FullOffsetRange,
pub(crate) value: T,
}
#[derive(Clone, Debug)]
pub(crate) struct FullOffsetRange {
pub(crate) start: FullOffset,
pub(crate) end: FullOffset,
}
#[derive(Clone, Debug)]
pub(crate) struct AnchorRangeMultimapSummary {
start: FullOffset,
end: FullOffset,
min_start: FullOffset,
max_end: FullOffset,
count: usize,
}
impl Anchor {
pub fn min() -> Self {
Self {
full_offset: FullOffset(0),
timestamp: clock::Local::MIN,
offset: usize::MIN,
bias: Bias::Left,
version: Default::default(),
}
}
pub fn max() -> Self {
Self {
full_offset: FullOffset::MAX,
timestamp: clock::Local::MAX,
offset: usize::MAX,
bias: Bias::Right,
version: Default::default(),
}
}
pub fn cmp<'a>(&self, other: &Anchor, buffer: &BufferSnapshot) -> Result<Ordering> {
if self == other {
return Ok(Ordering::Equal);
}
let offset_comparison = if self.version == other.version {
self.full_offset.cmp(&other.full_offset)
let offset_comparison = if self.timestamp == other.timestamp {
self.offset.cmp(&other.offset)
} else {
buffer
.full_offset_for_anchor(self)
@ -122,455 +64,10 @@ impl Anchor {
}
}
impl<T> AnchorMap<T> {
pub fn version(&self) -> &clock::Global {
&self.version
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn iter<'a, D>(
&'a self,
snapshot: &'a BufferSnapshot,
) -> impl Iterator<Item = (D, &'a T)> + 'a
where
D: TextDimension,
{
snapshot
.summaries_for_anchors(
self.version.clone(),
self.bias,
self.entries.iter().map(|e| &e.0),
)
.zip(self.entries.iter().map(|e| &e.1))
}
}
impl AnchorSet {
pub fn version(&self) -> &clock::Global {
&self.0.version
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn iter<'a, D>(&'a self, content: &'a BufferSnapshot) -> impl Iterator<Item = D> + 'a
where
D: TextDimension,
{
self.0.iter(content).map(|(position, _)| position)
}
}
impl<T> AnchorRangeMap<T> {
pub fn version(&self) -> &clock::Global {
&self.version
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn from_full_offset_ranges(
version: clock::Global,
start_bias: Bias,
end_bias: Bias,
entries: Vec<(Range<FullOffset>, T)>,
) -> Self {
Self {
version,
start_bias,
end_bias,
entries,
}
}
pub fn ranges<'a, D>(
&'a self,
content: &'a BufferSnapshot,
) -> impl Iterator<Item = (Range<D>, &'a T)> + 'a
where
D: TextDimension,
{
content
.summaries_for_anchor_ranges(
self.version.clone(),
self.start_bias,
self.end_bias,
self.entries.iter().map(|e| &e.0),
)
.zip(self.entries.iter().map(|e| &e.1))
}
pub fn intersecting_ranges<'a, D, I>(
&'a self,
range: Range<(I, Bias)>,
content: &'a BufferSnapshot,
) -> impl Iterator<Item = (Range<D>, &'a T)> + 'a
where
D: TextDimension,
I: ToOffset,
{
let range = content.anchor_at(range.start.0, range.start.1)
..content.anchor_at(range.end.0, range.end.1);
let mut probe_anchor = Anchor {
full_offset: Default::default(),
bias: self.start_bias,
version: self.version.clone(),
};
let start_ix = self.entries.binary_search_by(|probe| {
probe_anchor.full_offset = probe.0.end;
probe_anchor.cmp(&range.start, &content).unwrap()
});
match start_ix {
Ok(start_ix) | Err(start_ix) => content
.summaries_for_anchor_ranges(
self.version.clone(),
self.start_bias,
self.end_bias,
self.entries[start_ix..].iter().map(|e| &e.0),
)
.zip(self.entries.iter().map(|e| &e.1)),
}
}
pub fn full_offset_ranges(&self) -> impl Iterator<Item = &(Range<FullOffset>, T)> {
self.entries.iter()
}
pub fn min_by_key<'a, D, F, K>(
&self,
content: &'a BufferSnapshot,
mut extract_key: F,
) -> Option<(Range<D>, &T)>
where
D: TextDimension,
F: FnMut(&T) -> K,
K: Ord,
{
self.entries
.iter()
.min_by_key(|(_, value)| extract_key(value))
.map(|(range, value)| (self.resolve_range(range, &content), value))
}
pub fn max_by_key<'a, D, F, K>(
&self,
content: &'a BufferSnapshot,
mut extract_key: F,
) -> Option<(Range<D>, &T)>
where
D: TextDimension,
F: FnMut(&T) -> K,
K: Ord,
{
self.entries
.iter()
.max_by_key(|(_, value)| extract_key(value))
.map(|(range, value)| (self.resolve_range(range, &content), value))
}
fn resolve_range<'a, D>(
&self,
range: &Range<FullOffset>,
content: &'a BufferSnapshot,
) -> Range<D>
where
D: TextDimension,
{
let mut anchor = Anchor {
full_offset: range.start,
bias: self.start_bias,
version: self.version.clone(),
};
let start = content.summary_for_anchor(&anchor);
anchor.full_offset = range.end;
anchor.bias = self.end_bias;
let end = content.summary_for_anchor(&anchor);
start..end
}
}
impl<T: PartialEq> PartialEq for AnchorRangeMap<T> {
fn eq(&self, other: &Self) -> bool {
self.version == other.version && self.entries == other.entries
}
}
impl<T: Eq> Eq for AnchorRangeMap<T> {}
impl<T: Debug> Debug for AnchorRangeMap<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
let mut f = f.debug_map();
for (range, value) in &self.entries {
f.key(range);
f.value(value);
}
f.finish()
}
}
impl Debug for AnchorRangeSet {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut f = f.debug_set();
for (range, _) in &self.0.entries {
f.entry(range);
}
f.finish()
}
}
impl AnchorRangeSet {
pub fn len(&self) -> usize {
self.0.len()
}
pub fn version(&self) -> &clock::Global {
self.0.version()
}
pub fn ranges<'a, D>(
&'a self,
content: &'a BufferSnapshot,
) -> impl 'a + Iterator<Item = Range<Point>>
where
D: TextDimension,
{
self.0.ranges(content).map(|(range, _)| range)
}
}
impl<T: Clone> Default for AnchorRangeMultimap<T> {
fn default() -> Self {
Self {
entries: Default::default(),
version: Default::default(),
start_bias: Bias::Left,
end_bias: Bias::Left,
}
}
}
impl<T: Clone> AnchorRangeMultimap<T> {
pub fn version(&self) -> &clock::Global {
&self.version
}
pub fn intersecting_ranges<'a, I, O>(
&'a self,
range: Range<I>,
content: &'a BufferSnapshot,
inclusive: bool,
) -> impl Iterator<Item = (usize, Range<O>, &T)> + 'a
where
I: ToOffset,
O: FromAnchor,
{
let end_bias = if inclusive { Bias::Right } else { Bias::Left };
let range = range.start.to_full_offset(&content, Bias::Left)
..range.end.to_full_offset(&content, end_bias);
let mut cursor = self.entries.filter::<_, usize>(
{
let mut endpoint = Anchor {
full_offset: FullOffset(0),
bias: Bias::Right,
version: self.version.clone(),
};
move |summary: &AnchorRangeMultimapSummary| {
endpoint.full_offset = summary.max_end;
endpoint.bias = self.end_bias;
let max_end = endpoint.to_full_offset(&content, self.end_bias);
let start_cmp = range.start.cmp(&max_end);
endpoint.full_offset = summary.min_start;
endpoint.bias = self.start_bias;
let min_start = endpoint.to_full_offset(&content, self.start_bias);
let end_cmp = range.end.cmp(&min_start);
if inclusive {
start_cmp <= Ordering::Equal && end_cmp >= Ordering::Equal
} else {
start_cmp == Ordering::Less && end_cmp == Ordering::Greater
}
}
},
&(),
);
std::iter::from_fn({
let mut endpoint = Anchor {
full_offset: FullOffset(0),
bias: Bias::Left,
version: self.version.clone(),
};
move || {
if let Some(item) = cursor.item() {
let ix = *cursor.start();
endpoint.full_offset = item.range.start;
endpoint.bias = self.start_bias;
let start = O::from_anchor(&endpoint, &content);
endpoint.full_offset = item.range.end;
endpoint.bias = self.end_bias;
let end = O::from_anchor(&endpoint, &content);
let value = &item.value;
cursor.next(&());
Some((ix, start..end, value))
} else {
None
}
}
})
}
pub fn from_full_offset_ranges(
version: clock::Global,
start_bias: Bias,
end_bias: Bias,
entries: impl Iterator<Item = (Range<FullOffset>, T)>,
) -> Self {
Self {
version,
start_bias,
end_bias,
entries: SumTree::from_iter(
entries.map(|(range, value)| AnchorRangeMultimapEntry {
range: FullOffsetRange {
start: range.start,
end: range.end,
},
value,
}),
&(),
),
}
}
pub fn full_offset_ranges(&self) -> impl Iterator<Item = (Range<FullOffset>, &T)> {
self.entries
.cursor::<()>()
.map(|entry| (entry.range.start..entry.range.end, &entry.value))
}
pub fn filter<'a, O, F>(
&'a self,
content: &'a BufferSnapshot,
mut f: F,
) -> impl 'a + Iterator<Item = (usize, Range<O>, &T)>
where
O: FromAnchor,
F: 'a + FnMut(&'a T) -> bool,
{
let mut endpoint = Anchor {
full_offset: FullOffset(0),
bias: Bias::Left,
version: self.version.clone(),
};
self.entries
.cursor::<()>()
.enumerate()
.filter_map(move |(ix, entry)| {
if f(&entry.value) {
endpoint.full_offset = entry.range.start;
endpoint.bias = self.start_bias;
let start = O::from_anchor(&endpoint, &content);
endpoint.full_offset = entry.range.end;
endpoint.bias = self.end_bias;
let end = O::from_anchor(&endpoint, &content);
Some((ix, start..end, &entry.value))
} else {
None
}
})
}
}
impl<T: Clone> sum_tree::Item for AnchorRangeMultimapEntry<T> {
type Summary = AnchorRangeMultimapSummary;
fn summary(&self) -> Self::Summary {
AnchorRangeMultimapSummary {
start: self.range.start,
end: self.range.end,
min_start: self.range.start,
max_end: self.range.end,
count: 1,
}
}
}
impl Default for AnchorRangeMultimapSummary {
fn default() -> Self {
Self {
start: FullOffset(0),
end: FullOffset::MAX,
min_start: FullOffset::MAX,
max_end: FullOffset(0),
count: 0,
}
}
}
impl sum_tree::Summary for AnchorRangeMultimapSummary {
type Context = ();
fn add_summary(&mut self, other: &Self, _: &Self::Context) {
self.min_start = self.min_start.min(other.min_start);
self.max_end = self.max_end.max(other.max_end);
#[cfg(debug_assertions)]
{
let start_comparison = self.start.cmp(&other.start);
assert!(start_comparison <= Ordering::Equal);
if start_comparison == Ordering::Equal {
assert!(self.end.cmp(&other.end) >= Ordering::Equal);
}
}
self.start = other.start;
self.end = other.end;
self.count += other.count;
}
}
impl Default for FullOffsetRange {
fn default() -> Self {
Self {
start: FullOffset(0),
end: FullOffset::MAX,
}
}
}
impl<'a> sum_tree::Dimension<'a, AnchorRangeMultimapSummary> for usize {
fn add_summary(&mut self, summary: &'a AnchorRangeMultimapSummary, _: &()) {
*self += summary.count;
}
}
impl<'a> sum_tree::Dimension<'a, AnchorRangeMultimapSummary> for FullOffsetRange {
fn add_summary(&mut self, summary: &'a AnchorRangeMultimapSummary, _: &()) {
self.start = summary.start;
self.end = summary.end;
}
}
impl<'a> sum_tree::SeekTarget<'a, AnchorRangeMultimapSummary, FullOffsetRange> for FullOffsetRange {
fn cmp(&self, cursor_location: &FullOffsetRange, _: &()) -> Ordering {
Ord::cmp(&self.start, &cursor_location.start)
.then_with(|| Ord::cmp(&cursor_location.end, &self.end))
}
}
pub trait AnchorRangeExt {
fn cmp(&self, b: &Range<Anchor>, buffer: &BufferSnapshot) -> Result<Ordering>;
fn to_offset(&self, content: &BufferSnapshot) -> Range<usize>;
fn to_point(&self, content: &BufferSnapshot) -> Range<Point>;
}
impl AnchorRangeExt for Range<Anchor> {
@ -584,4 +81,8 @@ impl AnchorRangeExt for Range<Anchor> {
fn to_offset(&self, content: &BufferSnapshot) -> Range<usize> {
self.start.to_offset(&content)..self.end.to_offset(&content)
}
fn to_point(&self, content: &BufferSnapshot) -> Range<Point> {
self.start.summary::<Point>(&content)..self.end.summary::<Point>(&content)
}
}

View file

@ -0,0 +1,83 @@
use smallvec::{smallvec, SmallVec};
use std::iter;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Locator(SmallVec<[u64; 4]>);
impl Locator {
pub fn min() -> Self {
Self(smallvec![u64::MIN])
}
pub fn max() -> Self {
Self(smallvec![u64::MAX])
}
pub fn assign(&mut self, other: &Self) {
self.0.resize(other.0.len(), 0);
self.0.copy_from_slice(&other.0);
}
pub fn between(lhs: &Self, rhs: &Self) -> Self {
let lhs = lhs.0.iter().copied().chain(iter::repeat(u64::MIN));
let rhs = rhs.0.iter().copied().chain(iter::repeat(u64::MAX));
let mut location = SmallVec::new();
for (lhs, rhs) in lhs.zip(rhs) {
let mid = lhs + ((rhs.saturating_sub(lhs)) >> 48);
location.push(mid);
if mid > lhs {
break;
}
}
Self(location)
}
pub fn len(&self) -> usize {
self.0.len()
}
}
impl Default for Locator {
fn default() -> Self {
Self::min()
}
}
#[cfg(test)]
mod tests {
use super::*;
use rand::prelude::*;
use std::mem;
#[gpui::test(iterations = 100)]
fn test_locators(mut rng: StdRng) {
let mut lhs = Default::default();
let mut rhs = Default::default();
while lhs == rhs {
lhs = Locator(
(0..rng.gen_range(1..=5))
.map(|_| rng.gen_range(0..=100))
.collect(),
);
rhs = Locator(
(0..rng.gen_range(1..=5))
.map(|_| rng.gen_range(0..=100))
.collect(),
);
}
if lhs > rhs {
mem::swap(&mut lhs, &mut rhs);
}
let middle = Locator::between(&lhs, &rhs);
assert!(middle > lhs);
assert!(middle < rhs);
for ix in 0..middle.0.len() - 1 {
assert!(
middle.0[ix] == *lhs.0.get(ix).unwrap_or(&0)
|| middle.0[ix] == *rhs.0.get(ix).unwrap_or(&0)
);
}
}
}

View file

@ -1,9 +1,15 @@
use super::Operation;
use std::{fmt::Debug, ops::Add};
use sum_tree::{Cursor, Dimension, Edit, Item, KeyedItem, SumTree, Summary};
use sum_tree::{Dimension, Edit, Item, KeyedItem, SumTree, Summary};
pub trait Operation: Clone + Debug {
fn lamport_timestamp(&self) -> clock::Lamport;
}
#[derive(Clone, Debug)]
pub struct OperationQueue(SumTree<Operation>);
struct OperationItem<T>(T);
#[derive(Clone, Debug)]
pub struct OperationQueue<T: Operation>(SumTree<OperationItem<T>>);
#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
pub struct OperationKey(clock::Lamport);
@ -20,7 +26,7 @@ impl OperationKey {
}
}
impl OperationQueue {
impl<T: Operation> OperationQueue<T> {
pub fn new() -> Self {
OperationQueue(SumTree::new())
}
@ -29,11 +35,15 @@ impl OperationQueue {
self.0.summary().len
}
pub fn insert(&mut self, mut ops: Vec<Operation>) {
pub fn insert(&mut self, mut ops: Vec<T>) {
ops.sort_by_key(|op| op.lamport_timestamp());
ops.dedup_by_key(|op| op.lamport_timestamp());
self.0
.edit(ops.into_iter().map(Edit::Insert).collect(), &());
self.0.edit(
ops.into_iter()
.map(|op| Edit::Insert(OperationItem(op)))
.collect(),
&(),
);
}
pub fn drain(&mut self) -> Self {
@ -42,8 +52,8 @@ impl OperationQueue {
clone
}
pub fn cursor(&self) -> Cursor<Operation, ()> {
self.0.cursor()
pub fn iter(&self) -> impl Iterator<Item = &T> {
self.0.cursor::<()>().map(|i| &i.0)
}
}
@ -76,22 +86,22 @@ impl<'a> Dimension<'a, OperationSummary> for OperationKey {
}
}
impl Item for Operation {
impl<T: Operation> Item for OperationItem<T> {
type Summary = OperationSummary;
fn summary(&self) -> Self::Summary {
OperationSummary {
key: OperationKey::new(self.lamport_timestamp()),
key: OperationKey::new(self.0.lamport_timestamp()),
len: 1,
}
}
}
impl KeyedItem for Operation {
impl<T: Operation> KeyedItem for OperationItem<T> {
type Key = OperationKey;
fn key(&self) -> Self::Key {
OperationKey::new(self.lamport_timestamp())
OperationKey::new(self.0.lamport_timestamp())
}
}
@ -107,21 +117,27 @@ mod tests {
assert_eq!(queue.len(), 0);
queue.insert(vec![
Operation::Test(clock.tick()),
Operation::Test(clock.tick()),
TestOperation(clock.tick()),
TestOperation(clock.tick()),
]);
assert_eq!(queue.len(), 2);
queue.insert(vec![Operation::Test(clock.tick())]);
queue.insert(vec![TestOperation(clock.tick())]);
assert_eq!(queue.len(), 3);
drop(queue.drain());
assert_eq!(queue.len(), 0);
queue.insert(vec![Operation::Test(clock.tick())]);
queue.insert(vec![TestOperation(clock.tick())]);
assert_eq!(queue.len(), 1);
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct TestOperation(clock::Lamport);
impl Operation for TestOperation {
fn lamport_timestamp(&self) -> clock::Lamport {
self.0
}
}
}

View file

@ -22,13 +22,13 @@ impl<T: Rng> Iterator for RandomCharIter<T> {
match self.0.gen_range(0..100) {
// whitespace
0..=19 => [' ', '\n', '\t'].choose(&mut self.0).copied(),
0..=5 => ['\n'].choose(&mut self.0).copied(),
// two-byte greek letters
20..=32 => char::from_u32(self.0.gen_range(('α' as u32)..('ω' as u32 + 1))),
// three-byte characters
33..=45 => ['✋', '✅', '❌', '❎', '⭐'].choose(&mut self.0).copied(),
// four-byte characters
46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.0).copied(),
// 20..=32 => char::from_u32(self.0.gen_range(('α' as u32)..('ω' as u32 + 1))),
// // three-byte characters
// 33..=45 => ['✋', '✅', '❌', '❎', '⭐'].choose(&mut self.0).copied(),
// // four-byte characters
// 46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.0).copied(),
// ascii letters
_ => Some(self.0.gen_range(b'a'..b'z' + 1).into()),
}

View file

@ -1,4 +1,5 @@
use crate::{rope::TextDimension, AnchorRangeMap, BufferSnapshot, ToOffset, ToPoint};
use crate::Anchor;
use crate::{rope::TextDimension, BufferSnapshot, ToOffset, ToPoint};
use std::{cmp::Ordering, ops::Range, sync::Arc};
use sum_tree::Bias;
@ -25,7 +26,7 @@ pub struct Selection<T> {
pub struct SelectionSet {
pub id: SelectionSetId,
pub active: bool,
pub selections: Arc<AnchorRangeMap<SelectionState>>,
pub selections: Arc<[Selection<Anchor>]>,
}
#[derive(Debug, Eq, PartialEq)]
@ -75,6 +76,21 @@ impl<T: ToOffset + ToPoint + Copy + Ord> Selection<T> {
}
}
impl Selection<Anchor> {
pub fn resolve<'a, D: 'a + TextDimension>(
&'a self,
snapshot: &'a BufferSnapshot,
) -> Selection<D> {
Selection {
id: self.id,
start: snapshot.summary_for_anchor(&self.start),
end: snapshot.summary_for_anchor(&self.end),
reversed: self.reversed,
goal: self.goal,
}
}
}
impl SelectionSet {
pub fn len(&self) -> usize {
self.selections.len()
@ -82,69 +98,70 @@ impl SelectionSet {
pub fn selections<'a, D>(
&'a self,
content: &'a BufferSnapshot,
snapshot: &'a BufferSnapshot,
) -> impl 'a + Iterator<Item = Selection<D>>
where
D: TextDimension,
{
self.selections
.ranges(content)
.map(|(range, state)| Selection {
id: state.id,
start: range.start,
end: range.end,
reversed: state.reversed,
goal: state.goal,
})
let anchors = self
.selections
.iter()
.flat_map(|selection| [&selection.start, &selection.end].into_iter());
let mut positions = snapshot.summaries_for_anchors::<D, _>(anchors);
self.selections.iter().map(move |selection| Selection {
start: positions.next().unwrap(),
end: positions.next().unwrap(),
goal: selection.goal,
reversed: selection.reversed,
id: selection.id,
})
}
pub fn intersecting_selections<'a, D, I>(
&'a self,
range: Range<(I, Bias)>,
content: &'a BufferSnapshot,
snapshot: &'a BufferSnapshot,
) -> impl 'a + Iterator<Item = Selection<D>>
where
D: TextDimension,
I: 'a + ToOffset,
{
self.selections
.intersecting_ranges(range, content)
.map(|(range, state)| Selection {
id: state.id,
start: range.start,
end: range.end,
reversed: state.reversed,
goal: state.goal,
})
let start = snapshot.anchor_at(range.start.0, range.start.1);
let end = snapshot.anchor_at(range.end.0, range.end.1);
let start_ix = match self
.selections
.binary_search_by(|probe| probe.end.cmp(&start, snapshot).unwrap())
{
Ok(ix) | Err(ix) => ix,
};
let end_ix = match self
.selections
.binary_search_by(|probe| probe.start.cmp(&end, snapshot).unwrap())
{
Ok(ix) | Err(ix) => ix,
};
self.selections[start_ix..end_ix]
.iter()
.map(|s| s.resolve(snapshot))
}
pub fn oldest_selection<'a, D>(&'a self, content: &'a BufferSnapshot) -> Option<Selection<D>>
pub fn oldest_selection<'a, D>(&'a self, snapshot: &'a BufferSnapshot) -> Option<Selection<D>>
where
D: TextDimension,
{
self.selections
.min_by_key(content, |selection| selection.id)
.map(|(range, state)| Selection {
id: state.id,
start: range.start,
end: range.end,
reversed: state.reversed,
goal: state.goal,
})
.iter()
.min_by_key(|s| s.id)
.map(|s| s.resolve(snapshot))
}
pub fn newest_selection<'a, D>(&'a self, content: &'a BufferSnapshot) -> Option<Selection<D>>
pub fn newest_selection<'a, D>(&'a self, snapshot: &'a BufferSnapshot) -> Option<Selection<D>>
where
D: TextDimension,
{
self.selections
.max_by_key(content, |selection| selection.id)
.map(|(range, state)| Selection {
id: state.id,
start: range.start,
end: range.end,
reversed: state.reversed,
goal: state.goal,
})
.iter()
.max_by_key(|s| s.id)
.map(|s| s.resolve(snapshot))
}
}

View file

@ -78,6 +78,8 @@ fn test_random_edits(mut rng: StdRng) {
TextSummary::from(&reference_string[range])
);
buffer.check_invariants();
if rng.gen_bool(0.3) {
buffer_versions.push((buffer.clone(), buffer.subscribe()));
}
@ -603,6 +605,7 @@ fn test_random_concurrent_edits(mut rng: StdRng) {
}
_ => {}
}
buffer.check_invariants();
if mutation_count == 0 && network.is_idle() {
break;
@ -629,6 +632,7 @@ fn test_random_concurrent_edits(mut rng: StdRng) {
.all_selection_ranges::<usize>()
.collect::<HashMap<_, _>>()
);
buffer.check_invariants();
}
}
@ -644,6 +648,39 @@ struct Network<T: Clone, R: rand::Rng> {
rng: R,
}
impl Buffer {
fn check_invariants(&self) {
// Ensure every fragment is ordered by locator in the fragment tree and corresponds
// to an insertion fragment in the insertions tree.
let mut prev_fragment_id = Locator::min();
for fragment in self.snapshot.fragments.items(&None) {
assert!(fragment.id > prev_fragment_id);
prev_fragment_id = fragment.id.clone();
let insertion_fragment = self
.snapshot
.insertions
.get(
&InsertionFragmentKey {
timestamp: fragment.insertion_timestamp.local(),
split_offset: fragment.insertion_offset,
},
&(),
)
.unwrap();
assert_eq!(insertion_fragment.fragment_id, fragment.id);
}
let mut cursor = self.snapshot.fragments.cursor::<Option<&Locator>>();
for insertion_fragment in self.snapshot.insertions.cursor::<()>() {
cursor.seek(&Some(&insertion_fragment.fragment_id), Bias::Left, &None);
let fragment = cursor.item().unwrap();
assert_eq!(insertion_fragment.fragment_id, fragment.id);
assert_eq!(insertion_fragment.split_offset, fragment.insertion_offset);
}
}
}
impl<T: Clone, R: rand::Rng> Network<T, R> {
fn new(rng: R) -> Self {
Network {

File diff suppressed because it is too large Load diff