//! The block structure of the body: per block its length and attributes, kept in //! chunks. Lookups binary-search the chunks' prefix sums, rebuilt once after an edit, //! so they cost O(log(blocks / CHUNK) + CHUNK) however long the note. //! //! The index follows the text only through Loro's text events (local commits and //! imports alike), so it never disagrees with the doc. Lengths are exact in Unicode //! scalars, Loro's event unit; UTF-16 lengths, the DOM's unit, are exact for text the //! index saw inserted and recomputed from the doc for blocks that may hold astral //! chars after a delete or split. use std::cell::{Ref, RefCell}; use std::collections::HashMap; use loro::cursor::PosType; use loro::{LoroText, TextDelta}; use crate::flat::{Attrs, FlatBlock, SEP}; const CHUNK: usize = 256; #[derive(Clone, Copy, Debug)] struct Entry { len16: u32, lenu: u32, attrs: u32, /// May hold astral chars (UTF-16 and Unicode lengths can differ). wide: bool, /// `len16` must be recomputed from the doc. stale: bool, } #[derive(Default)] struct Chunk { e: Vec, len16: usize, lenu: usize, stale: bool, } impl Chunk { fn sum(&mut self) { self.len16 = self.e.iter().map(|e| e.len16 as usize).sum(); self.lenu = self.e.iter().map(|e| e.lenu as usize).sum(); self.stale = self.e.iter().any(|e| e.stale); } } /// One block as the index knows it. Offsets are global; lengths include the separator. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Info { pub index: usize, pub start16: usize, pub startu: usize, pub len16: usize, pub lenu: usize, attrs: u32, } impl Info { pub fn end16(&self) -> usize { self.start16 + self.len16 } pub fn endu(&self) -> usize { self.startu + self.lenu } /// Offset of the separator (the end of the content). pub fn sep16(&self) -> usize { self.start16 + self.len16 - 1 } pub fn sepu(&self) -> usize { self.startu + self.lenu - 1 } /// UTF-16 length of the content. pub fn content16(&self) -> usize { self.len16 - 1 } } /// Blocks `at..at + removed` were replaced by `at..at + inserted` (indexes after the /// splices before it). `edit` is the range one plain text edit changed inside a single /// block, in Unicode scalars from the block start after the edit. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Splice { pub at: usize, pub removed: usize, pub inserted: usize, pub edit: Option<(usize, usize)>, } pub struct BlockIndex { chunks: Vec, /// Before each chunk and after the last: (blocks, UTF-16 length, Unicode length). /// Empty when stale; every change to `chunks` clears it. prefix: RefCell>, pool: Vec, ids: HashMap, /// The last block has no separator: content after the last one, which concurrent /// edits can leave until the editor appends one. pub open: bool, } /// Where a block lives: chunk, entry, and the block's index and start. #[derive(Clone, Copy, Debug)] struct At { c: usize, j: usize, index: usize, start16: usize, startu: usize, } impl Default for BlockIndex { fn default() -> Self { let mut b = BlockIndex { chunks: Vec::new(), prefix: RefCell::default(), pool: Vec::new(), ids: HashMap::new(), open: false }; b.intern(&Attrs::default()); b } } impl BlockIndex { pub fn from_blocks(blocks: &[FlatBlock], open: bool) -> Self { let mut b = BlockIndex::default(); let mut entries = Vec::with_capacity(blocks.len()); for f in blocks { let attrs = b.intern(&f.attrs); entries.push(Entry { len16: f.len16 as u32, lenu: f.lenu as u32, attrs, wide: f.len16 != f.lenu, stale: false }); } b.open = open; b.chunks = entries .chunks(CHUNK) .map(|c| { let mut ch = Chunk { e: c.to_vec(), ..Default::default() }; ch.sum(); ch }) .collect(); b } /// Reads the whole body. pub fn read(text: &LoroText) -> Self { let blocks = crate::flat::read(text); let total: usize = blocks.iter().map(|b| b.lenu).sum(); let open = total > 0 && !text_ends_with_sep(text); BlockIndex::from_blocks(&blocks, open) } fn intern(&mut self, a: &Attrs) -> u32 { if let Some(&i) = self.ids.get(a) { return i; } let i = self.pool.len() as u32; self.pool.push(a.clone()); self.ids.insert(a.clone(), i); i } fn prefix(&self) -> Ref<'_, Vec<[usize; 3]>> { if self.prefix.borrow().is_empty() { let mut p = self.prefix.borrow_mut(); let mut acc = [0; 3]; p.reserve(self.chunks.len() + 1); p.push(acc); for ch in &self.chunks { acc = [acc[0] + ch.e.len(), acc[1] + ch.len16, acc[2] + ch.lenu]; p.push(acc); } } self.prefix.borrow() } fn changed(&mut self) { self.prefix.get_mut().clear(); } /// The chunk holding block `i`, and the block index it starts at. fn chunk_of(&self, i: usize) -> Option<(usize, [usize; 3])> { let p = self.prefix(); if i >= p.last()?[0] { return None; } let c = p.partition_point(|x| x[0] <= i) - 1; Some((c, p[c])) } pub fn len(&self) -> usize { self.prefix().last().map_or(0, |p| p[0]) } pub fn is_empty(&self) -> bool { self.len() == 0 } pub fn total16(&self) -> usize { self.prefix().last().map_or(0, |p| p[1]) } pub fn totalu(&self) -> usize { self.prefix().last().map_or(0, |p| p[2]) } pub fn attrs(&self, info: &Info) -> &Attrs { &self.pool[info.attrs as usize] } fn info_at(&self, a: At) -> Info { let e = self.chunks[a.c].e[a.j]; Info { index: a.index, start16: a.start16, startu: a.startu, len16: e.len16 as usize, lenu: e.lenu as usize, attrs: e.attrs } } /// Block `i`. pub fn get(&self, i: usize) -> Option { self.at_index(i).map(|a| self.info_at(a)) } fn at_index(&self, i: usize) -> Option { let (c, [index, mut s16, mut su]) = self.chunk_of(i)?; let j = i - index; for e in &self.chunks[c].e[..j] { s16 += e.len16 as usize; su += e.lenu as usize; } Some(At { c, j, index: i, start16: s16, startu: su }) } /// The block holding UTF-16 offset `off`: a separator's offset belongs to its block /// (the end of its content). Offsets at or past the end give the last block. pub fn find16(&self, off: usize) -> Option { self.locate(off, 1).map(|a| self.info_at(a)) } pub fn findu(&self, off: usize) -> Option { self.locate(off, 2).map(|a| self.info_at(a)) } /// The block holding offset `off` in prefix measure `k` (1: UTF-16, 2: Unicode). fn locate(&self, off: usize, k: usize) -> Option { let el = |e: &Entry| if k == 1 { e.len16 as usize } else { e.lenu as usize }; let (c, [mut index, mut s16, mut su]) = { let p = self.prefix(); let last = p.last()?; if last[0] == 0 { return None; } if off >= last[k] { let n = last[0]; drop(p); return self.at_index(n - 1); } let c = p.partition_point(|x| x[k] <= off) - 1; (c, p[c]) }; let mut pos = if k == 1 { s16 } else { su }; for (j, e) in self.chunks[c].e.iter().enumerate() { if off < pos + el(e) { return Some(At { c, j, index, start16: s16, startu: su }); } index += 1; pos += el(e); s16 += e.len16 as usize; su += e.lenu as usize; } None } /// Blocks from `i` on, in order. pub fn iter_from(&self, i: usize) -> impl Iterator + '_ { let mut cur = self.at_index(i); std::iter::from_fn(move || { let a = cur?; let info = self.info_at(a); let mut n = At { c: a.c, j: a.j + 1, index: a.index + 1, start16: info.end16(), startu: info.endu() }; while n.c < self.chunks.len() && n.j >= self.chunks[n.c].e.len() { n.c += 1; n.j = 0; } cur = (n.c < self.chunks.len()).then_some(n); Some(info) }) } /// Blocks before `i`, nearest first. pub fn iter_back(&self, i: usize) -> impl Iterator + '_ { let mut cur = i.checked_sub(1).and_then(|k| self.at_index(k)); std::iter::from_fn(move || { let a = cur?; let info = self.info_at(a); cur = (a.index > 0).then(|| { let (mut c, mut j) = (a.c, a.j); while j == 0 { c -= 1; j = self.chunks[c].e.len(); } let e = self.chunks[c].e[j - 1]; At { c, j: j - 1, index: a.index - 1, start16: a.start16 - e.len16 as usize, startu: a.startu - e.lenu as usize } }); Some(info) }) } // ----------------------------------------------------------------------- // Following the text // ----------------------------------------------------------------------- /// Applies one text event's delta. `text` is the body after the change, for the /// UTF-16 lengths of blocks that may hold astral chars. pub fn apply(&mut self, delta: &[TextDelta], text: &LoroText) -> Vec { let mut out: Vec = Vec::new(); let mut pos = 0usize; for d in delta { match d { TextDelta::Retain { retain, attributes } => { if let Some(attrs) = attributes.as_ref().filter(|a| !a.is_empty()) { self.restyle(pos, *retain, attrs, &mut out); } pos += retain; } TextDelta::Insert { insert, attributes } => { let attrs = Attrs::from_map(attributes.as_ref()); self.insert(pos, insert, &attrs, &mut out); pos += insert.chars().count(); } TextDelta::Delete { delete } => self.delete(pos, *delete, &mut out), } } // An open last block left empty is no block. if self.open && self.chunks.iter().rev().find_map(|c| c.e.last()).is_some_and(|e| e.lenu == 0) { let at = self.len() - 1; self.splice_entries(at, 1, Vec::new()); self.open = false; record(&mut out, Splice { at, removed: 1, inserted: 0, edit: None }); } self.fix_stale(text); out } /// Changes the attributes of separators, and marks blocks whose inline marks /// changed, within `len` chars from `pos`. fn restyle(&mut self, pos: usize, len: usize, attrs: &HashMap, out: &mut Vec) { let block_keys = attrs.keys().any(|k| crate::flat::BLOCK_KEYS.contains(&k.as_str())); let inline_keys = attrs.keys().any(|k| !crate::flat::BLOCK_KEYS.contains(&k.as_str())); let Some(mut a) = self.locate(pos, 2) else { return }; let end = pos + len; loop { let e = self.chunks[a.c].e[a.j]; let sep = a.startu + e.lenu as usize - 1; let has_sep = !(self.open && self.is_last(a)); let mut dirty = inline_keys; if block_keys && has_sep && sep >= pos && sep < end { let mut new = self.pool[e.attrs as usize].clone(); for (k, v) in attrs.iter() { new.set(k, v); } let id = self.intern(&new); if id != e.attrs { self.chunks[a.c].e[a.j].attrs = id; dirty = true; } } if dirty { record(out, Splice { at: a.index, removed: 1, inserted: 1, edit: None }); } let next = a.startu + e.lenu as usize; if next >= end { break; } match self.step(a) { Some(n) => a = n, None => break, } } } fn is_last(&self, a: At) -> bool { a.j + 1 == self.chunks[a.c].e.len() && self.chunks[a.c + 1..].iter().all(|c| c.e.is_empty()) } fn step(&self, a: At) -> Option { let e = self.chunks[a.c].e[a.j]; 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 }; while n.c < self.chunks.len() && n.j >= self.chunks[n.c].e.len() { n.c += 1; n.j = 0; } (n.c < self.chunks.len()).then_some(n) } fn insert(&mut self, pos: usize, s: &str, attrs: &Attrs, out: &mut Vec) { if s.is_empty() { return; } let total = self.totalu(); let pieces: Vec<&str> = s.split(SEP).collect(); let new_attrs = self.intern(attrs); let entry = |p: &str| { let (lenu, len16) = crate::flat::str_lens(p); Entry { len16: len16 as u32, lenu: lenu as u32, attrs: 0, wide: len16 != lenu, stale: false } }; if pos >= total && !self.open { // After the last separator: new blocks, the last one open unless `s` ends a block. let mut es: Vec = pieces.iter().map(|p| entry(p)).collect(); let n = es.len(); for (i, e) in es.iter_mut().enumerate() { if i + 1 < n { e.attrs = new_attrs; e.len16 += 1; e.lenu += 1; } } if es.last().is_some_and(|e| e.lenu == 0) { es.pop(); } else { self.open = true; } let at = self.len(); let inserted = es.len(); self.splice_entries(at, 0, es); record(out, Splice { at, removed: 0, inserted, edit: None }); return; } let a = self.locate(pos, 2).expect("insert inside the body"); let old = self.chunks[a.c].e[a.j]; let inner = pos - a.startu; if pieces.len() == 1 { let e = &mut self.chunks[a.c].e[a.j]; let add = entry(s); e.len16 += add.len16; e.lenu += add.lenu; e.wide |= add.wide; let lo = inner; let hi = inner + add.lenu as usize; self.chunks[a.c].sum(); self.changed(); record(out, Splice { at: a.index, removed: 1, inserted: 1, edit: Some((lo, hi)) }); return; } // The block splits: its head plus the first piece ends at the first new // separator; the last piece plus its tail keeps its own separator. let head16 = if old.wide { None } else { Some(inner) }; let mut es: Vec = Vec::with_capacity(pieces.len()); for (i, p) in pieces.iter().enumerate() { let mut e = entry(p); if i + 1 < pieces.len() { e.len16 += 1; e.lenu += 1; e.attrs = new_attrs; } else { e.attrs = old.attrs; } es.push(e); } let tailu = old.lenu as usize - inner; { let first = &mut es[0]; first.lenu += inner as u32; match head16 { Some(h) => first.len16 += h as u32, None => { first.wide = true; first.stale = true; } } } { let last = es.last_mut().unwrap(); last.lenu += tailu as u32; match head16 { Some(h) => last.len16 += old.len16 - h as u32, None => { last.wide = true; last.stale = true; } } } let inserted = es.len(); self.splice_entries(a.index, 1, es); record(out, Splice { at: a.index, removed: 1, inserted, edit: None }); } fn delete(&mut self, pos: usize, mut n: usize, out: &mut Vec) { let Some(a) = self.locate(pos, 2) else { return }; let inner = pos - a.startu; let first = self.chunks[a.c].e[a.j]; if inner + n < first.lenu as usize { // Within one block's content. let e = &mut self.chunks[a.c].e[a.j]; e.lenu -= n as u32; if e.wide { e.stale = true; } else { e.len16 -= n as u32; } self.chunks[a.c].sum(); self.changed(); record(out, Splice { at: a.index, removed: 1, inserted: 1, edit: Some((inner, inner)) }); return; } // Spans a separator: the blocks merge into one ending in the last one's. let mut merged = Entry { len16: 0, lenu: inner as u32, attrs: first.attrs, wide: first.wide, stale: first.wide }; if !first.wide { merged.len16 = inner as u32; } let mut removed = 0; let (mut c, mut j) = (a.c, a.j); let mut tail_open = false; let mut rest_in_block = first.lenu as usize - inner; let mut cur = first; loop { removed += 1; if n < rest_in_block { // The deletion ends inside `cur`: its remainder and separator stay. let keep = rest_in_block - n; merged.lenu += keep as u32; merged.attrs = cur.attrs; if cur.wide || merged.wide { merged.wide = true; merged.stale = true; } else { merged.len16 += keep as u32; } break; } n -= rest_in_block; j += 1; loop { // Next block; whole chunks inside the deletion are skipped at once. while c < self.chunks.len() && j >= self.chunks[c].e.len() { c += 1; j = 0; } if c >= self.chunks.len() || j > 0 || n < self.chunks[c].lenu { break; } removed += self.chunks[c].e.len(); n -= self.chunks[c].lenu; j = self.chunks[c].e.len(); } if c >= self.chunks.len() { // Deleted through the last separator: the head is left without one. tail_open = true; break; } cur = self.chunks[c].e[j]; rest_in_block = cur.lenu as usize; } if tail_open { // No separator, so no attributes. merged.attrs = 0; } let es = if tail_open && merged.lenu == 0 { Vec::new() } else { vec![merged] }; if tail_open { self.open = !es.is_empty(); } let inserted = es.len(); self.splice_entries(a.index, removed, es); record(out, Splice { at: a.index, removed, inserted, edit: None }); } /// Replaces `removed` entries from block `at` with `new`. fn splice_entries(&mut self, at: usize, removed: usize, new: Vec) { self.changed(); if self.chunks.is_empty() { self.chunks.push(Chunk::default()); } let (mut c, mut k) = (0, 0); while c + 1 < self.chunks.len() && at >= k + self.chunks[c].e.len() { k += self.chunks[c].e.len(); c += 1; } let j = at - k; let take = removed.min(self.chunks[c].e.len() - j); self.chunks[c].e.splice(j..j + take, new); let mut left = removed - take; let mut d = c + 1; while left > 0 && d < self.chunks.len() { let t = left.min(self.chunks[d].e.len()); self.chunks[d].e.drain(..t); self.chunks[d].sum(); left -= t; d += 1; } if self.chunks[c].e.len() > 2 * CHUNK { let all = std::mem::take(&mut self.chunks[c].e); let pieces: Vec = all .chunks(CHUNK) .map(|p| { let mut ch = Chunk { e: p.to_vec(), ..Default::default() }; ch.sum(); ch }) .collect(); self.chunks.splice(c..c + 1, pieces); } else { self.chunks[c].sum(); } if self.chunks[c..d.min(self.chunks.len())].iter().any(|ch| ch.e.is_empty()) { self.chunks.retain(|ch| !ch.e.is_empty()); if self.chunks.is_empty() { self.chunks.push(Chunk::default()); } } } /// Recomputes the UTF-16 lengths marked stale, from the doc. fn fix_stale(&mut self, text: &LoroText) { if !self.chunks.iter().any(|c| c.stale) { return; } self.changed(); let mut startu = 0; for c in 0..self.chunks.len() { if !self.chunks[c].stale { startu += self.chunks[c].lenu; continue; } for j in 0..self.chunks[c].e.len() { let e = self.chunks[c].e[j]; if e.stale { let conv = |u: usize| text.convert_pos(u, PosType::Unicode, PosType::Utf16).unwrap_or(u); let len16 = conv(startu + e.lenu as usize) - conv(startu); let e = &mut self.chunks[c].e[j]; e.len16 = len16 as u32; e.wide = len16 != e.lenu as usize; e.stale = false; } startu += e.lenu as usize; } self.chunks[c].sum(); } } /// Checks the index against the doc (tests). #[doc(hidden)] pub fn check(&self, text: &LoroText) { let fresh = BlockIndex::read(text); let mine: Vec<(usize, usize, Attrs)> = self.iter_from(0).map(|i| (i.len16, i.lenu, self.attrs(&i).clone())).collect(); let theirs: Vec<(usize, usize, Attrs)> = fresh.iter_from(0).map(|i| (i.len16, i.lenu, fresh.attrs(&i).clone())).collect(); assert_eq!(mine, theirs); assert_eq!(self.open, fresh.open); let fwd: Vec = self.iter_from(0).collect(); let mut back: Vec = self.iter_back(self.len()).collect(); back.reverse(); assert_eq!(fwd, back); } } fn text_ends_with_sep(text: &LoroText) -> bool { let n = text.len_unicode(); n > 0 && text.slice(n - 1, n).is_ok_and(|s| s.starts_with(SEP)) } /// Appends a splice, merging it into the previous one when they touch. fn record(out: &mut Vec, s: Splice) { if let Some(last) = out.last_mut() && s.at >= last.at && s.at <= last.at + last.inserted { let ov = (s.at + s.removed).min(last.at + last.inserted) - s.at; last.removed += s.removed - ov; last.inserted = last.inserted - ov + s.inserted; last.edit = None; return; } out.push(s); } #[cfg(test)] mod tests { use std::sync::{Arc, Mutex}; use loro::{ContainerTrait, LoroDoc, LoroValue}; use super::*; use crate::flat::{KEY_KIND, KEY_WRAP}; struct Rng(u64); impl Rng { fn next(&mut self, n: usize) -> usize { self.0 ^= self.0 << 13; self.0 ^= self.0 >> 7; self.0 ^= self.0 << 17; (self.0 % n.max(1) as u64) as usize } } #[test] fn follows_random_edits() { let doc = LoroDoc::new(); doc.config_text_style(crate::schema::text_style_config()); let text = doc.get_text("body"); text.insert(0, "\u{2029}").unwrap(); doc.commit(); let mut index = BlockIndex::read(&text); let events: Arc>>> = Arc::default(); let ev = events.clone(); let _sub = doc.subscribe( &text.id(), Arc::new(move |e| { for d in e.events { if let loro::event::Diff::Text(delta) = d.diff { ev.lock().unwrap().push(delta); } } }), ); let pieces = ["a", "bc", "\u{2029}", "x\u{2029}y", "😀", "é😀\u{2029}", "\u{2029}\u{2029}", "long text here"]; let mut rng = Rng(0x9e3779b97f4a7c15); let mut log: Vec = Vec::new(); for step in 0..3000 { let n = text.len_unicode(); let before = format!("{:?}", text.to_delta()); match rng.next(6) { 0 | 1 => { let at = rng.next(n + 1); let p = pieces[rng.next(pieces.len())]; log.push(format!("insert {at} {p:?}")); text.insert(at, p).unwrap(); } 2 if n > 1 => { let at = rng.next(n); let len = 1 + rng.next((n - at).min(12)); log.push(format!("delete {at} {len}")); text.delete(at, len).unwrap(); } 3 if n > 0 => { let at = rng.next(n); let len = 1 + rng.next((n - at).min(20)); let (key, v): (&str, LoroValue) = match rng.next(3) { 0 => (KEY_KIND, "h2".into()), 1 => (KEY_WRAP, "uq".into()), _ => ("strong", true.into()), }; log.push(format!("mark {at}..{} {key} {v:?}", at + len)); if rng.next(4) == 0 { text.unmark(at..at + len, key).unwrap(); } else { text.mark(at..at + len, key, v).unwrap(); } } _ => {} } doc.commit(); let evs: Vec> = events.lock().unwrap().drain(..).collect(); for delta in &evs { let before = index.len(); let mut count = before; for sp in index.apply(delta, &text) { assert!(sp.at + sp.removed <= count, "splice past the end at step {step}"); count = count - sp.removed + sp.inserted; } assert_eq!(count, index.len(), "splices add up at step {step}"); } let fresh = BlockIndex::read(&text); let a: Vec<_> = index.iter_from(0).map(|i| (i.len16, i.lenu, index.attrs(&i).clone())).collect(); let b: Vec<_> = fresh.iter_from(0).map(|i| (i.len16, i.lenu, fresh.attrs(&i).clone())).collect(); if a != b { eprintln!("BEFORE {before}\nOP {}\nEVENTS {evs:?}\nAFTER {:?}", log.last().unwrap(), text.to_delta()); } index.check(&text); assert_eq!(index.totalu(), text.len_unicode(), "step {step}"); assert_eq!(index.total16(), text.len_utf16(), "step {step}"); } } }