forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

tracker_texts.rs195 lines, 6.9 KiBHistoryRawDownload
1use std::ops::Range;
2
3use append_only_bytes::BytesSlice;
4
5use crate::{
6 container::richtext::{richtext_state::unicode_to_utf8_index, RichtextChunk},
7 utils::string_slice::unicode_range_to_byte_range,
8};
9
10/// Non-ASCII op text is cut into pieces of at most this many bytes, so that
11/// finding a unicode offset inside a piece scans at most this many bytes.
12const MAX_PIECE_BYTES: usize = 256;
13
14/// The text of the ops applied to a rich-text tracker.
15///
16/// The tracker's text chunks are unicode ranges in this table, which holds the
17/// ops' own [`BytesSlice`]s. Ops decoded from a change block keep their text in
18/// a buffer owned by that decode, not in the doc's string arena, so the tracker
19/// cannot address them by arena position. The table is reset with its tracker.
20/// See `context/text-arena-growth.md`.
21#[derive(Debug, Default)]
22pub(super) struct TrackerTexts {
23 /// `(unicode start, text)`, sorted by start. A piece ends where the next
24 /// one starts, the last one at `len`.
25 pieces: Vec<(u32, BytesSlice)>,
26 len: u32,
27}
28
29impl TrackerTexts {
30 pub fn clear(&mut self) {
31 self.pieces.clear();
32 self.len = 0;
33 }
34
35 #[cfg(test)]
36 pub fn len(&self) -> usize {
37 self.len as usize
38 }
39
40 /// Records the chars of `text` (`unicode_len` of them) after the first
41 /// `skip`, and returns their range.
42 pub fn push_from(&mut self, text: &BytesSlice, unicode_len: u32, skip: usize) -> Range<u32> {
43 if skip == 0 {
44 return self.push(text, unicode_len);
45 }
46
47 let byte = if text.len() == unicode_len as usize {
48 skip
49 } else {
50 unicode_to_utf8_index(as_str(text), skip).expect("skip is within the op text")
51 };
52 self.push(&text.slice_clone(byte..), unicode_len - skip as u32)
53 }
54
55 /// Records the `unicode_len` chars of `text` and returns their range.
56 pub fn push(&mut self, text: &BytesSlice, unicode_len: u32) -> Range<u32> {
57 let start = self.len;
58 let end = start
59 .checked_add(unicode_len)
60 .filter(|&end| end < RichtextChunk::MOVE_ANCHOR)
61 .expect("rich-text tracker text exceeds the u32 index space");
62 if unicode_len == 0 {
63 return start..end;
64 }
65
66 if text.len() == unicode_len as usize || text.len() <= MAX_PIECE_BYTES {
67 self.pieces.push((start, text.clone()));
68 } else {
69 let s = as_str(text);
70 let mut piece_byte = 0;
71 let mut piece_unicode = start;
72 let mut unicode = start;
73 for (byte, _) in s.char_indices() {
74 if byte - piece_byte >= MAX_PIECE_BYTES {
75 self.pieces
76 .push((piece_unicode, text.slice_clone(piece_byte..byte)));
77 piece_byte = byte;
78 piece_unicode = unicode;
79 }
80 unicode += 1;
81 }
82 assert_eq!(unicode, end, "op unicode_len does not match its text");
83 self.pieces
84 .push((piece_unicode, text.slice_clone(piece_byte..)));
85 }
86
87 self.len = end;
88 start..end
89 }
90
91 /// Calls `f(offset, text)` for the text in `range`, in order. `offset` is
92 /// the unicode offset of `text` from `range.start`. Neighboring pieces of
93 /// one buffer are passed as one slice.
94 pub fn for_each_slice(&self, range: Range<u32>, mut f: impl FnMut(usize, BytesSlice)) {
95 assert!(range.end <= self.len, "{range:?} is out of {}", self.len);
96 if range.start >= range.end {
97 return;
98 }
99
100 let mut i = self
101 .pieces
102 .partition_point(|(start, _)| *start <= range.start)
103 - 1;
104 let mut pending: Option<(usize, BytesSlice)> = None;
105 let mut cur = range.start;
106 while cur < range.end {
107 let (piece_start, piece) = &self.pieces[i];
108 let piece_end = self.pieces.get(i + 1).map_or(self.len, |(start, _)| *start);
109 let piece_len = (piece_end - piece_start) as usize;
110 let from = (cur - piece_start) as usize;
111 let to = (range.end.min(piece_end) - piece_start) as usize;
112 let slice = if from == 0 && to == piece_len {
113 piece.clone()
114 } else if piece.len() == piece_len {
115 piece.slice_clone(from..to)
116 } else {
117 let (from, to) = unicode_range_to_byte_range(as_str(piece), from, to);
118 piece.slice_clone(from..to)
119 };
120
121 let offset = (cur - range.start) as usize;
122 match &mut pending {
123 Some((_, prev)) if prev.can_merge(&slice) => prev.try_merge(&slice).unwrap(),
124 _ => {
125 if let Some((offset, prev)) = pending.replace((offset, slice)) {
126 f(offset, prev);
127 }
128 }
129 }
130
131 cur = piece_start + to as u32;
132 i += 1;
133 }
134
135 if let Some((offset, prev)) = pending {
136 f(offset, prev);
137 }
138 }
139}
140
141fn as_str(text: &BytesSlice) -> &str {
142 // SAFETY: text op content is valid UTF-8; it was decoded or created as `str`
143 unsafe { std::str::from_utf8_unchecked(text) }
144}
145
146#[cfg(test)]
147mod test {
148 use super::*;
149
150 fn collect(texts: &TrackerTexts, range: Range<u32>) -> Vec<(usize, String)> {
151 let mut ans = Vec::new();
152 texts.for_each_slice(range, |offset, s| {
153 ans.push((offset, as_str(&s).to_string()));
154 });
155 ans
156 }
157
158 #[test]
159 fn slices_across_ops_and_pieces() {
160 let mut texts = TrackerTexts::default();
161 let a = BytesSlice::from_bytes("hello".as_bytes());
162 let long = "文字".repeat(300);
163 let b = BytesSlice::from_bytes(long.as_bytes());
164 assert_eq!(texts.push(&a, 5), 0..5);
165 assert_eq!(texts.push(&b, 600), 5..605);
166 assert!(texts.pieces.len() > 2);
167
168 let all = collect(&texts, 0..605);
169 assert_eq!(all.len(), 2, "pieces of one buffer are passed merged");
170 assert_eq!(all[0], (0, "hello".to_string()));
171 assert_eq!(all[1], (5, long.clone()));
172
173 let expected: String = long.chars().skip(95).take(300).collect();
174 assert_eq!(collect(&texts, 100..400), vec![(0, expected)]);
175 assert_eq!(
176 collect(&texts, 3..7),
177 vec![(0, "lo".to_string()), (2, "文字".to_string())]
178 );
179 assert!(collect(&texts, 4..4).is_empty());
180 }
181
182 #[test]
183 fn push_from_records_only_the_suffix() {
184 let mut texts = TrackerTexts::default();
185 let ascii = BytesSlice::from_bytes("abcd".as_bytes());
186 assert_eq!(texts.push_from(&ascii, 4, 1), 0..3);
187 let wide = BytesSlice::from_bytes("文字😀x".as_bytes());
188 assert_eq!(texts.push_from(&wide, 4, 2), 3..5);
189 assert_eq!(
190 collect(&texts, 0..5),
191 vec![(0, "bcd".to_string()), (3, "😀x".to_string())]
192 );
193 assert_eq!(texts.push_from(&ascii, 4, 0), 5..9);
194 }
195}