project_note
Clone
https://git.tahinli.com/Tahinli/project_note.git
0 watching·0 forks·Rust·3.6 MiB·c49f5e7·Tahinli·1 month ago·2 commits
| 1 | //! The block structure of the body: per block its length and attributes, kept in |
| 2 | //! chunks. Lookups binary-search the chunks' prefix sums, rebuilt once after an edit, |
| 3 | //! so they cost O(log(blocks / CHUNK) + CHUNK) however long the note. |
| 4 | //! |
| 5 | //! The index follows the text only through Loro's text events (local commits and |
| 6 | //! imports alike), so it never disagrees with the doc. Lengths are exact in Unicode |
| 7 | //! scalars, Loro's event unit; UTF-16 lengths, the DOM's unit, are exact for text the |
| 8 | //! index saw inserted and recomputed from the doc for blocks that may hold astral |
| 9 | //! chars after a delete or split. |
| 10 | |
| 11 | use std::cell::{Ref, RefCell}; |
| 12 | use std::collections::HashMap; |
| 13 | |
| 14 | use loro::cursor::PosType; |
| 15 | use loro::{LoroText, TextDelta}; |
| 16 | use crate::flat::{Attrs, FlatBlock, SEP}; |
| 17 | |
| 18 | const CHUNK: usize = 256; |
| 19 | |
| 20 | #[derive(Clone, Copy, Debug)] |
| 21 | struct Entry { |
| 22 | len16: u32, |
| 23 | lenu: u32, |
| 24 | attrs: u32, |
| 25 | /// May hold astral chars (UTF-16 and Unicode lengths can differ). |
| 26 | wide: bool, |
| 27 | /// `len16` must be recomputed from the doc. |
| 28 | stale: bool, |
| 29 | } |
| 30 | |
| 31 | #[derive(Default)] |
| 32 | struct Chunk { |
| 33 | e: Vec<Entry>, |
| 34 | len16: usize, |
| 35 | lenu: usize, |
| 36 | stale: bool, |
| 37 | } |
| 38 | |
| 39 | impl Chunk { |
| 40 | fn sum(&mut self) { |
| 41 | self.len16 = self.e.iter().map(|e| e.len16 as usize).sum(); |
| 42 | self.lenu = self.e.iter().map(|e| e.lenu as usize).sum(); |
| 43 | self.stale = self.e.iter().any(|e| e.stale); |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | /// One block as the index knows it. Offsets are global; lengths include the separator. |
| 48 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 49 | pub struct Info { |
| 50 | pub index: usize, |
| 51 | pub start16: usize, |
| 52 | pub startu: usize, |
| 53 | pub len16: usize, |
| 54 | pub lenu: usize, |
| 55 | attrs: u32, |
| 56 | } |
| 57 | |
| 58 | impl Info { |
| 59 | pub fn end16(&self) -> usize { |
| 60 | self.start16 + self.len16 |
| 61 | } |
| 62 | pub fn endu(&self) -> usize { |
| 63 | self.startu + self.lenu |
| 64 | } |
| 65 | /// Offset of the separator (the end of the content). |
| 66 | pub fn sep16(&self) -> usize { |
| 67 | self.start16 + self.len16 - 1 |
| 68 | } |
| 69 | pub fn sepu(&self) -> usize { |
| 70 | self.startu + self.lenu - 1 |
| 71 | } |
| 72 | /// UTF-16 length of the content. |
| 73 | pub fn content16(&self) -> usize { |
| 74 | self.len16 - 1 |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | /// Blocks `at..at + removed` were replaced by `at..at + inserted` (indexes after the |
| 79 | /// splices before it). `edit` is the range one plain text edit changed inside a single |
| 80 | /// block, in Unicode scalars from the block start after the edit. |
| 81 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 82 | pub struct Splice { |
| 83 | pub at: usize, |
| 84 | pub removed: usize, |
| 85 | pub inserted: usize, |
| 86 | pub edit: Option<(usize, usize)>, |
| 87 | } |
| 88 | |
| 89 | pub struct BlockIndex { |
| 90 | chunks: Vec<Chunk>, |
| 91 | /// Before each chunk and after the last: (blocks, UTF-16 length, Unicode length). |
| 92 | /// Empty when stale; every change to `chunks` clears it. |
| 93 | prefix: RefCell<Vec<[usize; 3]>>, |
| 94 | pool: Vec<Attrs>, |
| 95 | ids: HashMap<Attrs, u32>, |
| 96 | /// The last block has no separator: content after the last one, which concurrent |
| 97 | /// edits can leave until the editor appends one. |
| 98 | pub open: bool, |
| 99 | } |
| 100 | |
| 101 | /// Where a block lives: chunk, entry, and the block's index and start. |
| 102 | #[derive(Clone, Copy, Debug)] |
| 103 | struct At { |
| 104 | c: usize, |
| 105 | j: usize, |
| 106 | index: usize, |
| 107 | start16: usize, |
| 108 | startu: usize, |
| 109 | } |
| 110 | |
| 111 | impl Default for BlockIndex { |
| 112 | fn default() -> Self { |
| 113 | let mut b = BlockIndex { chunks: Vec::new(), prefix: RefCell::default(), pool: Vec::new(), ids: HashMap::new(), open: false }; |
| 114 | b.intern(&Attrs::default()); |
| 115 | b |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | impl BlockIndex { |
| 120 | pub fn from_blocks(blocks: &[FlatBlock], open: bool) -> Self { |
| 121 | let mut b = BlockIndex::default(); |
| 122 | let mut entries = Vec::with_capacity(blocks.len()); |
| 123 | for f in blocks { |
| 124 | let attrs = b.intern(&f.attrs); |
| 125 | entries.push(Entry { len16: f.len16 as u32, lenu: f.lenu as u32, attrs, wide: f.len16 != f.lenu, stale: false }); |
| 126 | } |
| 127 | b.open = open; |
| 128 | b.chunks = entries |
| 129 | .chunks(CHUNK) |
| 130 | .map(|c| { |
| 131 | let mut ch = Chunk { e: c.to_vec(), ..Default::default() }; |
| 132 | ch.sum(); |
| 133 | ch |
| 134 | }) |
| 135 | .collect(); |
| 136 | b |
| 137 | } |
| 138 | |
| 139 | /// Reads the whole body. |
| 140 | pub fn read(text: &LoroText) -> Self { |
| 141 | let blocks = crate::flat::read(text); |
| 142 | let total: usize = blocks.iter().map(|b| b.lenu).sum(); |
| 143 | let open = total > 0 && !text_ends_with_sep(text); |
| 144 | BlockIndex::from_blocks(&blocks, open) |
| 145 | } |
| 146 | |
| 147 | fn intern(&mut self, a: &Attrs) -> u32 { |
| 148 | if let Some(&i) = self.ids.get(a) { |
| 149 | return i; |
| 150 | } |
| 151 | let i = self.pool.len() as u32; |
| 152 | self.pool.push(a.clone()); |
| 153 | self.ids.insert(a.clone(), i); |
| 154 | i |
| 155 | } |
| 156 | |
| 157 | fn prefix(&self) -> Ref<'_, Vec<[usize; 3]>> { |
| 158 | if self.prefix.borrow().is_empty() { |
| 159 | let mut p = self.prefix.borrow_mut(); |
| 160 | let mut acc = [0; 3]; |
| 161 | p.reserve(self.chunks.len() + 1); |
| 162 | p.push(acc); |
| 163 | for ch in &self.chunks { |
| 164 | acc = [acc[0] + ch.e.len(), acc[1] + ch.len16, acc[2] + ch.lenu]; |
| 165 | p.push(acc); |
| 166 | } |
| 167 | } |
| 168 | self.prefix.borrow() |
| 169 | } |
| 170 | |
| 171 | fn changed(&mut self) { |
| 172 | self.prefix.get_mut().clear(); |
| 173 | } |
| 174 | |
| 175 | /// The chunk holding block `i`, and the block index it starts at. |
| 176 | fn chunk_of(&self, i: usize) -> Option<(usize, [usize; 3])> { |
| 177 | let p = self.prefix(); |
| 178 | if i >= p.last()?[0] { |
| 179 | return None; |
| 180 | } |
| 181 | let c = p.partition_point(|x| x[0] <= i) - 1; |
| 182 | Some((c, p[c])) |
| 183 | } |
| 184 | |
| 185 | pub fn len(&self) -> usize { |
| 186 | self.prefix().last().map_or(0, |p| p[0]) |
| 187 | } |
| 188 | |
| 189 | pub fn is_empty(&self) -> bool { |
| 190 | self.len() == 0 |
| 191 | } |
| 192 | |
| 193 | pub fn total16(&self) -> usize { |
| 194 | self.prefix().last().map_or(0, |p| p[1]) |
| 195 | } |
| 196 | |
| 197 | pub fn totalu(&self) -> usize { |
| 198 | self.prefix().last().map_or(0, |p| p[2]) |
| 199 | } |
| 200 | |
| 201 | pub fn attrs(&self, info: &Info) -> &Attrs { |
| 202 | &self.pool[info.attrs as usize] |
| 203 | } |
| 204 | |
| 205 | fn info_at(&self, a: At) -> Info { |
| 206 | let e = self.chunks[a.c].e[a.j]; |
| 207 | Info { index: a.index, start16: a.start16, startu: a.startu, len16: e.len16 as usize, lenu: e.lenu as usize, attrs: e.attrs } |
| 208 | } |
| 209 | |
| 210 | /// Block `i`. |
| 211 | pub fn get(&self, i: usize) -> Option<Info> { |
| 212 | self.at_index(i).map(|a| self.info_at(a)) |
| 213 | } |
| 214 | |
| 215 | fn at_index(&self, i: usize) -> Option<At> { |
| 216 | let (c, [index, mut s16, mut su]) = self.chunk_of(i)?; |
| 217 | let j = i - index; |
| 218 | for e in &self.chunks[c].e[..j] { |
| 219 | s16 += e.len16 as usize; |
| 220 | su += e.lenu as usize; |
| 221 | } |
| 222 | Some(At { c, j, index: i, start16: s16, startu: su }) |
| 223 | } |
| 224 | |
| 225 | /// The block holding UTF-16 offset `off`: a separator's offset belongs to its block |
| 226 | /// (the end of its content). Offsets at or past the end give the last block. |
| 227 | pub fn find16(&self, off: usize) -> Option<Info> { |
| 228 | self.locate(off, 1).map(|a| self.info_at(a)) |
| 229 | } |
| 230 | |
| 231 | pub fn findu(&self, off: usize) -> Option<Info> { |
| 232 | self.locate(off, 2).map(|a| self.info_at(a)) |
| 233 | } |
| 234 | |
| 235 | /// The block holding offset `off` in prefix measure `k` (1: UTF-16, 2: Unicode). |
| 236 | fn locate(&self, off: usize, k: usize) -> Option<At> { |
| 237 | let el = |e: &Entry| if k == 1 { e.len16 as usize } else { e.lenu as usize }; |
| 238 | let (c, [mut index, mut s16, mut su]) = { |
| 239 | let p = self.prefix(); |
| 240 | let last = p.last()?; |
| 241 | if last[0] == 0 { |
| 242 | return None; |
| 243 | } |
| 244 | if off >= last[k] { |
| 245 | let n = last[0]; |
| 246 | drop(p); |
| 247 | return self.at_index(n - 1); |
| 248 | } |
| 249 | let c = p.partition_point(|x| x[k] <= off) - 1; |
| 250 | (c, p[c]) |
| 251 | }; |
| 252 | let mut pos = if k == 1 { s16 } else { su }; |
| 253 | for (j, e) in self.chunks[c].e.iter().enumerate() { |
| 254 | if off < pos + el(e) { |
| 255 | return Some(At { c, j, index, start16: s16, startu: su }); |
| 256 | } |
| 257 | index += 1; |
| 258 | pos += el(e); |
| 259 | s16 += e.len16 as usize; |
| 260 | su += e.lenu as usize; |
| 261 | } |
| 262 | None |
| 263 | } |
| 264 | |
| 265 | /// Blocks from `i` on, in order. |
| 266 | pub fn iter_from(&self, i: usize) -> impl Iterator<Item = Info> + '_ { |
| 267 | let mut cur = self.at_index(i); |
| 268 | std::iter::from_fn(move || { |
| 269 | let a = cur?; |
| 270 | let info = self.info_at(a); |
| 271 | let mut n = At { c: a.c, j: a.j + 1, index: a.index + 1, start16: info.end16(), startu: info.endu() }; |
| 272 | while n.c < self.chunks.len() && n.j >= self.chunks[n.c].e.len() { |
| 273 | n.c += 1; |
| 274 | n.j = 0; |
| 275 | } |
| 276 | cur = (n.c < self.chunks.len()).then_some(n); |
| 277 | Some(info) |
| 278 | }) |
| 279 | } |
| 280 | |
| 281 | /// Blocks before `i`, nearest first. |
| 282 | pub fn iter_back(&self, i: usize) -> impl Iterator<Item = Info> + '_ { |
| 283 | let mut cur = i.checked_sub(1).and_then(|k| self.at_index(k)); |
| 284 | std::iter::from_fn(move || { |
| 285 | let a = cur?; |
| 286 | let info = self.info_at(a); |
| 287 | cur = (a.index > 0).then(|| { |
| 288 | let (mut c, mut j) = (a.c, a.j); |
| 289 | while j == 0 { |
| 290 | c -= 1; |
| 291 | j = self.chunks[c].e.len(); |
| 292 | } |
| 293 | let e = self.chunks[c].e[j - 1]; |
| 294 | At { c, j: j - 1, index: a.index - 1, start16: a.start16 - e.len16 as usize, startu: a.startu - e.lenu as usize } |
| 295 | }); |
| 296 | Some(info) |
| 297 | }) |
| 298 | } |
| 299 | |
| 300 | // ----------------------------------------------------------------------- |
| 301 | // Following the text |
| 302 | // ----------------------------------------------------------------------- |
| 303 | |
| 304 | /// Applies one text event's delta. `text` is the body after the change, for the |
| 305 | /// UTF-16 lengths of blocks that may hold astral chars. |
| 306 | pub fn apply(&mut self, delta: &[TextDelta], text: &LoroText) -> Vec<Splice> { |
| 307 | let mut out: Vec<Splice> = Vec::new(); |
| 308 | let mut pos = 0usize; |
| 309 | for d in delta { |
| 310 | match d { |
| 311 | TextDelta::Retain { retain, attributes } => { |
| 312 | if let Some(attrs) = attributes.as_ref().filter(|a| !a.is_empty()) { |
| 313 | self.restyle(pos, *retain, attrs, &mut out); |
| 314 | } |
| 315 | pos += retain; |
| 316 | } |
| 317 | TextDelta::Insert { insert, attributes } => { |
| 318 | let attrs = Attrs::from_map(attributes.as_ref()); |
| 319 | self.insert(pos, insert, &attrs, &mut out); |
| 320 | pos += insert.chars().count(); |
| 321 | } |
| 322 | TextDelta::Delete { delete } => self.delete(pos, *delete, &mut out), |
| 323 | } |
| 324 | } |
| 325 | // An open last block left empty is no block. |
| 326 | if self.open && self.chunks.iter().rev().find_map(|c| c.e.last()).is_some_and(|e| e.lenu == 0) { |
| 327 | let at = self.len() - 1; |
| 328 | self.splice_entries(at, 1, Vec::new()); |
| 329 | self.open = false; |
| 330 | record(&mut out, Splice { at, removed: 1, inserted: 0, edit: None }); |
| 331 | } |
| 332 | self.fix_stale(text); |
| 333 | out |
| 334 | } |
| 335 | |
| 336 | /// Changes the attributes of separators, and marks blocks whose inline marks |
| 337 | /// changed, within `len` chars from `pos`. |
| 338 | fn restyle<S: std::hash::BuildHasher>(&mut self, pos: usize, len: usize, attrs: &HashMap<String, loro::LoroValue, S>, out: &mut Vec<Splice>) { |
| 339 | let block_keys = attrs.keys().any(|k| crate::flat::BLOCK_KEYS.contains(&k.as_str())); |
| 340 | let inline_keys = attrs.keys().any(|k| !crate::flat::BLOCK_KEYS.contains(&k.as_str())); |
| 341 | let Some(mut a) = self.locate(pos, 2) else { return }; |
| 342 | let end = pos + len; |
| 343 | loop { |
| 344 | let e = self.chunks[a.c].e[a.j]; |
| 345 | let sep = a.startu + e.lenu as usize - 1; |
| 346 | let has_sep = !(self.open && self.is_last(a)); |
| 347 | let mut dirty = inline_keys; |
| 348 | if block_keys && has_sep && sep >= pos && sep < end { |
| 349 | let mut new = self.pool[e.attrs as usize].clone(); |
| 350 | for (k, v) in attrs.iter() { |
| 351 | new.set(k, v); |
| 352 | } |
| 353 | let id = self.intern(&new); |
| 354 | if id != e.attrs { |
| 355 | self.chunks[a.c].e[a.j].attrs = id; |
| 356 | dirty = true; |
| 357 | } |
| 358 | } |
| 359 | if dirty { |
| 360 | record(out, Splice { at: a.index, removed: 1, inserted: 1, edit: None }); |
| 361 | } |
| 362 | let next = a.startu + e.lenu as usize; |
| 363 | if next >= end { |
| 364 | break; |
| 365 | } |
| 366 | match self.step(a) { |
| 367 | Some(n) => a = n, |
| 368 | None => break, |
| 369 | } |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | fn is_last(&self, a: At) -> bool { |
| 374 | a.j + 1 == self.chunks[a.c].e.len() && self.chunks[a.c + 1..].iter().all(|c| c.e.is_empty()) |
| 375 | } |
| 376 | |
| 377 | fn step(&self, a: At) -> Option<At> { |
| 378 | let e = self.chunks[a.c].e[a.j]; |
| 379 | let mut n = At { c: a.c, j: a.j + 1, index: a.index + 1, start16: a.start16 + e.len16 as usize, startu: a.startu + e.lenu as usize }; |
| 380 | while n.c < self.chunks.len() && n.j >= self.chunks[n.c].e.len() { |
| 381 | n.c += 1; |
| 382 | n.j = 0; |
| 383 | } |
| 384 | (n.c < self.chunks.len()).then_some(n) |
| 385 | } |
| 386 | |
| 387 | fn insert(&mut self, pos: usize, s: &str, attrs: &Attrs, out: &mut Vec<Splice>) { |
| 388 | if s.is_empty() { |
| 389 | return; |
| 390 | } |
| 391 | let total = self.totalu(); |
| 392 | let pieces: Vec<&str> = s.split(SEP).collect(); |
| 393 | let new_attrs = self.intern(attrs); |
| 394 | let entry = |p: &str| { |
| 395 | let (lenu, len16) = crate::flat::str_lens(p); |
| 396 | Entry { len16: len16 as u32, lenu: lenu as u32, attrs: 0, wide: len16 != lenu, stale: false } |
| 397 | }; |
| 398 | if pos >= total && !self.open { |
| 399 | // After the last separator: new blocks, the last one open unless `s` ends a block. |
| 400 | let mut es: Vec<Entry> = pieces.iter().map(|p| entry(p)).collect(); |
| 401 | let n = es.len(); |
| 402 | for (i, e) in es.iter_mut().enumerate() { |
| 403 | if i + 1 < n { |
| 404 | e.attrs = new_attrs; |
| 405 | e.len16 += 1; |
| 406 | e.lenu += 1; |
| 407 | } |
| 408 | } |
| 409 | if es.last().is_some_and(|e| e.lenu == 0) { |
| 410 | es.pop(); |
| 411 | } else { |
| 412 | self.open = true; |
| 413 | } |
| 414 | let at = self.len(); |
| 415 | let inserted = es.len(); |
| 416 | self.splice_entries(at, 0, es); |
| 417 | record(out, Splice { at, removed: 0, inserted, edit: None }); |
| 418 | return; |
| 419 | } |
| 420 | let a = self.locate(pos, 2).expect("insert inside the body"); |
| 421 | let old = self.chunks[a.c].e[a.j]; |
| 422 | let inner = pos - a.startu; |
| 423 | if pieces.len() == 1 { |
| 424 | let e = &mut self.chunks[a.c].e[a.j]; |
| 425 | let add = entry(s); |
| 426 | e.len16 += add.len16; |
| 427 | e.lenu += add.lenu; |
| 428 | e.wide |= add.wide; |
| 429 | let lo = inner; |
| 430 | let hi = inner + add.lenu as usize; |
| 431 | self.chunks[a.c].sum(); |
| 432 | self.changed(); |
| 433 | record(out, Splice { at: a.index, removed: 1, inserted: 1, edit: Some((lo, hi)) }); |
| 434 | return; |
| 435 | } |
| 436 | // The block splits: its head plus the first piece ends at the first new |
| 437 | // separator; the last piece plus its tail keeps its own separator. |
| 438 | let head16 = if old.wide { None } else { Some(inner) }; |
| 439 | let mut es: Vec<Entry> = Vec::with_capacity(pieces.len()); |
| 440 | for (i, p) in pieces.iter().enumerate() { |
| 441 | let mut e = entry(p); |
| 442 | if i + 1 < pieces.len() { |
| 443 | e.len16 += 1; |
| 444 | e.lenu += 1; |
| 445 | e.attrs = new_attrs; |
| 446 | } else { |
| 447 | e.attrs = old.attrs; |
| 448 | } |
| 449 | es.push(e); |
| 450 | } |
| 451 | let tailu = old.lenu as usize - inner; |
| 452 | { |
| 453 | let first = &mut es[0]; |
| 454 | first.lenu += inner as u32; |
| 455 | match head16 { |
| 456 | Some(h) => first.len16 += h as u32, |
| 457 | None => { |
| 458 | first.wide = true; |
| 459 | first.stale = true; |
| 460 | } |
| 461 | } |
| 462 | } |
| 463 | { |
| 464 | let last = es.last_mut().unwrap(); |
| 465 | last.lenu += tailu as u32; |
| 466 | match head16 { |
| 467 | Some(h) => last.len16 += old.len16 - h as u32, |
| 468 | None => { |
| 469 | last.wide = true; |
| 470 | last.stale = true; |
| 471 | } |
| 472 | } |
| 473 | } |
| 474 | let inserted = es.len(); |
| 475 | self.splice_entries(a.index, 1, es); |
| 476 | record(out, Splice { at: a.index, removed: 1, inserted, edit: None }); |
| 477 | } |
| 478 | |
| 479 | fn delete(&mut self, pos: usize, mut n: usize, out: &mut Vec<Splice>) { |
| 480 | let Some(a) = self.locate(pos, 2) else { return }; |
| 481 | let inner = pos - a.startu; |
| 482 | let first = self.chunks[a.c].e[a.j]; |
| 483 | if inner + n < first.lenu as usize { |
| 484 | // Within one block's content. |
| 485 | let e = &mut self.chunks[a.c].e[a.j]; |
| 486 | e.lenu -= n as u32; |
| 487 | if e.wide { |
| 488 | e.stale = true; |
| 489 | } else { |
| 490 | e.len16 -= n as u32; |
| 491 | } |
| 492 | self.chunks[a.c].sum(); |
| 493 | self.changed(); |
| 494 | record(out, Splice { at: a.index, removed: 1, inserted: 1, edit: Some((inner, inner)) }); |
| 495 | return; |
| 496 | } |
| 497 | // Spans a separator: the blocks merge into one ending in the last one's. |
| 498 | let mut merged = Entry { len16: 0, lenu: inner as u32, attrs: first.attrs, wide: first.wide, stale: first.wide }; |
| 499 | if !first.wide { |
| 500 | merged.len16 = inner as u32; |
| 501 | } |
| 502 | let mut removed = 0; |
| 503 | let (mut c, mut j) = (a.c, a.j); |
| 504 | let mut tail_open = false; |
| 505 | let mut rest_in_block = first.lenu as usize - inner; |
| 506 | let mut cur = first; |
| 507 | loop { |
| 508 | removed += 1; |
| 509 | if n < rest_in_block { |
| 510 | // The deletion ends inside `cur`: its remainder and separator stay. |
| 511 | let keep = rest_in_block - n; |
| 512 | merged.lenu += keep as u32; |
| 513 | merged.attrs = cur.attrs; |
| 514 | if cur.wide || merged.wide { |
| 515 | merged.wide = true; |
| 516 | merged.stale = true; |
| 517 | } else { |
| 518 | merged.len16 += keep as u32; |
| 519 | } |
| 520 | break; |
| 521 | } |
| 522 | n -= rest_in_block; |
| 523 | j += 1; |
| 524 | loop { |
| 525 | // Next block; whole chunks inside the deletion are skipped at once. |
| 526 | while c < self.chunks.len() && j >= self.chunks[c].e.len() { |
| 527 | c += 1; |
| 528 | j = 0; |
| 529 | } |
| 530 | if c >= self.chunks.len() || j > 0 || n < self.chunks[c].lenu { |
| 531 | break; |
| 532 | } |
| 533 | removed += self.chunks[c].e.len(); |
| 534 | n -= self.chunks[c].lenu; |
| 535 | j = self.chunks[c].e.len(); |
| 536 | } |
| 537 | if c >= self.chunks.len() { |
| 538 | // Deleted through the last separator: the head is left without one. |
| 539 | tail_open = true; |
| 540 | break; |
| 541 | } |
| 542 | cur = self.chunks[c].e[j]; |
| 543 | rest_in_block = cur.lenu as usize; |
| 544 | } |
| 545 | if tail_open { |
| 546 | // No separator, so no attributes. |
| 547 | merged.attrs = 0; |
| 548 | } |
| 549 | let es = if tail_open && merged.lenu == 0 { Vec::new() } else { vec![merged] }; |
| 550 | if tail_open { |
| 551 | self.open = !es.is_empty(); |
| 552 | } |
| 553 | let inserted = es.len(); |
| 554 | self.splice_entries(a.index, removed, es); |
| 555 | record(out, Splice { at: a.index, removed, inserted, edit: None }); |
| 556 | } |
| 557 | |
| 558 | /// Replaces `removed` entries from block `at` with `new`. |
| 559 | fn splice_entries(&mut self, at: usize, removed: usize, new: Vec<Entry>) { |
| 560 | self.changed(); |
| 561 | if self.chunks.is_empty() { |
| 562 | self.chunks.push(Chunk::default()); |
| 563 | } |
| 564 | let (mut c, mut k) = (0, 0); |
| 565 | while c + 1 < self.chunks.len() && at >= k + self.chunks[c].e.len() { |
| 566 | k += self.chunks[c].e.len(); |
| 567 | c += 1; |
| 568 | } |
| 569 | let j = at - k; |
| 570 | let take = removed.min(self.chunks[c].e.len() - j); |
| 571 | self.chunks[c].e.splice(j..j + take, new); |
| 572 | let mut left = removed - take; |
| 573 | let mut d = c + 1; |
| 574 | while left > 0 && d < self.chunks.len() { |
| 575 | let t = left.min(self.chunks[d].e.len()); |
| 576 | self.chunks[d].e.drain(..t); |
| 577 | self.chunks[d].sum(); |
| 578 | left -= t; |
| 579 | d += 1; |
| 580 | } |
| 581 | if self.chunks[c].e.len() > 2 * CHUNK { |
| 582 | let all = std::mem::take(&mut self.chunks[c].e); |
| 583 | let pieces: Vec<Chunk> = all |
| 584 | .chunks(CHUNK) |
| 585 | .map(|p| { |
| 586 | let mut ch = Chunk { e: p.to_vec(), ..Default::default() }; |
| 587 | ch.sum(); |
| 588 | ch |
| 589 | }) |
| 590 | .collect(); |
| 591 | self.chunks.splice(c..c + 1, pieces); |
| 592 | } else { |
| 593 | self.chunks[c].sum(); |
| 594 | } |
| 595 | if self.chunks[c..d.min(self.chunks.len())].iter().any(|ch| ch.e.is_empty()) { |
| 596 | self.chunks.retain(|ch| !ch.e.is_empty()); |
| 597 | if self.chunks.is_empty() { |
| 598 | self.chunks.push(Chunk::default()); |
| 599 | } |
| 600 | } |
| 601 | } |
| 602 | |
| 603 | /// Recomputes the UTF-16 lengths marked stale, from the doc. |
| 604 | fn fix_stale(&mut self, text: &LoroText) { |
| 605 | if !self.chunks.iter().any(|c| c.stale) { |
| 606 | return; |
| 607 | } |
| 608 | self.changed(); |
| 609 | let mut startu = 0; |
| 610 | for c in 0..self.chunks.len() { |
| 611 | if !self.chunks[c].stale { |
| 612 | startu += self.chunks[c].lenu; |
| 613 | continue; |
| 614 | } |
| 615 | for j in 0..self.chunks[c].e.len() { |
| 616 | let e = self.chunks[c].e[j]; |
| 617 | if e.stale { |
| 618 | let conv = |u: usize| text.convert_pos(u, PosType::Unicode, PosType::Utf16).unwrap_or(u); |
| 619 | let len16 = conv(startu + e.lenu as usize) - conv(startu); |
| 620 | let e = &mut self.chunks[c].e[j]; |
| 621 | e.len16 = len16 as u32; |
| 622 | e.wide = len16 != e.lenu as usize; |
| 623 | e.stale = false; |
| 624 | } |
| 625 | startu += e.lenu as usize; |
| 626 | } |
| 627 | self.chunks[c].sum(); |
| 628 | } |
| 629 | } |
| 630 | |
| 631 | /// Checks the index against the doc (tests). |
| 632 | #[doc(hidden)] |
| 633 | pub fn check(&self, text: &LoroText) { |
| 634 | let fresh = BlockIndex::read(text); |
| 635 | let mine: Vec<(usize, usize, Attrs)> = self.iter_from(0).map(|i| (i.len16, i.lenu, self.attrs(&i).clone())).collect(); |
| 636 | let theirs: Vec<(usize, usize, Attrs)> = fresh.iter_from(0).map(|i| (i.len16, i.lenu, fresh.attrs(&i).clone())).collect(); |
| 637 | assert_eq!(mine, theirs); |
| 638 | assert_eq!(self.open, fresh.open); |
| 639 | let fwd: Vec<Info> = self.iter_from(0).collect(); |
| 640 | let mut back: Vec<Info> = self.iter_back(self.len()).collect(); |
| 641 | back.reverse(); |
| 642 | assert_eq!(fwd, back); |
| 643 | } |
| 644 | } |
| 645 | |
| 646 | fn text_ends_with_sep(text: &LoroText) -> bool { |
| 647 | let n = text.len_unicode(); |
| 648 | n > 0 && text.slice(n - 1, n).is_ok_and(|s| s.starts_with(SEP)) |
| 649 | } |
| 650 | |
| 651 | /// Appends a splice, merging it into the previous one when they touch. |
| 652 | fn record(out: &mut Vec<Splice>, s: Splice) { |
| 653 | if let Some(last) = out.last_mut() |
| 654 | && s.at >= last.at |
| 655 | && s.at <= last.at + last.inserted |
| 656 | { |
| 657 | let ov = (s.at + s.removed).min(last.at + last.inserted) - s.at; |
| 658 | last.removed += s.removed - ov; |
| 659 | last.inserted = last.inserted - ov + s.inserted; |
| 660 | last.edit = None; |
| 661 | return; |
| 662 | } |
| 663 | out.push(s); |
| 664 | } |
| 665 | |
| 666 | #[cfg(test)] |
| 667 | mod tests { |
| 668 | use std::sync::{Arc, Mutex}; |
| 669 | |
| 670 | use loro::{ContainerTrait, LoroDoc, LoroValue}; |
| 671 | |
| 672 | use super::*; |
| 673 | use crate::flat::{KEY_KIND, KEY_WRAP}; |
| 674 | |
| 675 | struct Rng(u64); |
| 676 | impl Rng { |
| 677 | fn next(&mut self, n: usize) -> usize { |
| 678 | self.0 ^= self.0 << 13; |
| 679 | self.0 ^= self.0 >> 7; |
| 680 | self.0 ^= self.0 << 17; |
| 681 | (self.0 % n.max(1) as u64) as usize |
| 682 | } |
| 683 | } |
| 684 | |
| 685 | #[test] |
| 686 | fn follows_random_edits() { |
| 687 | let doc = LoroDoc::new(); |
| 688 | doc.config_text_style(crate::schema::text_style_config()); |
| 689 | let text = doc.get_text("body"); |
| 690 | text.insert(0, "\u{2029}").unwrap(); |
| 691 | doc.commit(); |
| 692 | let mut index = BlockIndex::read(&text); |
| 693 | let events: Arc<Mutex<Vec<Vec<TextDelta>>>> = Arc::default(); |
| 694 | let ev = events.clone(); |
| 695 | let _sub = doc.subscribe( |
| 696 | &text.id(), |
| 697 | Arc::new(move |e| { |
| 698 | for d in e.events { |
| 699 | if let loro::event::Diff::Text(delta) = d.diff { |
| 700 | ev.lock().unwrap().push(delta); |
| 701 | } |
| 702 | } |
| 703 | }), |
| 704 | ); |
| 705 | let pieces = ["a", "bc", "\u{2029}", "x\u{2029}y", "😀", "é😀\u{2029}", "\u{2029}\u{2029}", "long text here"]; |
| 706 | let mut rng = Rng(0x9e3779b97f4a7c15); |
| 707 | let mut log: Vec<String> = Vec::new(); |
| 708 | for step in 0..3000 { |
| 709 | let n = text.len_unicode(); |
| 710 | let before = format!("{:?}", text.to_delta()); |
| 711 | match rng.next(6) { |
| 712 | 0 | 1 => { |
| 713 | let at = rng.next(n + 1); |
| 714 | let p = pieces[rng.next(pieces.len())]; |
| 715 | log.push(format!("insert {at} {p:?}")); |
| 716 | text.insert(at, p).unwrap(); |
| 717 | } |
| 718 | 2 if n > 1 => { |
| 719 | let at = rng.next(n); |
| 720 | let len = 1 + rng.next((n - at).min(12)); |
| 721 | log.push(format!("delete {at} {len}")); |
| 722 | text.delete(at, len).unwrap(); |
| 723 | } |
| 724 | 3 if n > 0 => { |
| 725 | let at = rng.next(n); |
| 726 | let len = 1 + rng.next((n - at).min(20)); |
| 727 | let (key, v): (&str, LoroValue) = match rng.next(3) { |
| 728 | 0 => (KEY_KIND, "h2".into()), |
| 729 | 1 => (KEY_WRAP, "uq".into()), |
| 730 | _ => ("strong", true.into()), |
| 731 | }; |
| 732 | log.push(format!("mark {at}..{} {key} {v:?}", at + len)); |
| 733 | if rng.next(4) == 0 { |
| 734 | text.unmark(at..at + len, key).unwrap(); |
| 735 | } else { |
| 736 | text.mark(at..at + len, key, v).unwrap(); |
| 737 | } |
| 738 | } |
| 739 | _ => {} |
| 740 | } |
| 741 | doc.commit(); |
| 742 | let evs: Vec<Vec<TextDelta>> = events.lock().unwrap().drain(..).collect(); |
| 743 | for delta in &evs { |
| 744 | let before = index.len(); |
| 745 | let mut count = before; |
| 746 | for sp in index.apply(delta, &text) { |
| 747 | assert!(sp.at + sp.removed <= count, "splice past the end at step {step}"); |
| 748 | count = count - sp.removed + sp.inserted; |
| 749 | } |
| 750 | assert_eq!(count, index.len(), "splices add up at step {step}"); |
| 751 | } |
| 752 | let fresh = BlockIndex::read(&text); |
| 753 | let a: Vec<_> = index.iter_from(0).map(|i| (i.len16, i.lenu, index.attrs(&i).clone())).collect(); |
| 754 | let b: Vec<_> = fresh.iter_from(0).map(|i| (i.len16, i.lenu, fresh.attrs(&i).clone())).collect(); |
| 755 | if a != b { |
| 756 | eprintln!("BEFORE {before}\nOP {}\nEVENTS {evs:?}\nAFTER {:?}", log.last().unwrap(), text.to_delta()); |
| 757 | } |
| 758 | index.check(&text); |
| 759 | assert_eq!(index.totalu(), text.len_unicode(), "step {step}"); |
| 760 | assert_eq!(index.total16(), text.len_utf16(), "step {step}"); |
| 761 | } |
| 762 | } |
| 763 | } |