Cotton code
847 lines · 31.6 KB · RustRaw
//! One dictation, assembled: live partials that revise themselves, live//! finals that settle an utterance, second passes that correct a settled//! utterance, and the person's own edits, which no pass ever changes again.//!//! THE RULES, in order of precedence://!//! 1. Text the person edited (`touched`) is theirs: no pass changes it, and a//!    word they deleted is not put back.//! 2. Nothing is written twice and nothing heard is lost: a live hypothesis//!    is cumulative for its utterance, so the words an edit froze are dropped//!    from the hypotheses after it; an utterance a second pass settled before//!    its live final drops that final.//! 3. The second pass is the better reading: where it differs from what is//!    written (outside the person's ranges), it wins.//!//! Utterances are numbered in the order the live engine ends them. A second//! pass names its utterance by time (its span overlaps the utterance's) or,//! with no times, by order (the n-th second pass is the n-th utterance).//!//! Offsets crossing the boundary are UTF-16 code units; inside, bytes.use std::collections::BTreeSet;use super::format::{self, Options, Rules};#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Pass {    Live,    Second,}/// One engine result.#[derive(Debug, Clone, PartialEq)]pub struct Heard<'a> {    pub pass: Pass,    pub is_final: bool,    pub text: &'a str,    /// The audio it covers, ms from the session's start.    pub span: Option<(u64, u64)>,    /// The engine writes capitals only.    pub upper_case: bool,}/// Replace `[from, to)` of the text before this answer with `text`; UTF-16.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Edit {    pub from: usize,    pub to: usize,    pub text: String,}#[derive(Debug, Clone, PartialEq, Eq)]pub struct Answer {    pub settled: String,    pub tentative: String,    /// Settled text after the tentative words (`text = settled + tentative + later`):    /// an utterance a second pass settled before the live engine reached it.    pub later: String,    /// Sorted by `from`, last first; offsets in the text before this answer.    pub edits: Vec<Edit>,    /// Utterances settled live whose second pass has not come.    pub awaiting_second: usize,}#[derive(Debug, Clone, PartialEq)]struct Piece {    id: u64,    utt: u64,    text: String,    /// Byte ranges of `text` that are the person's; a zero-width range is a    /// place they deleted.    touched: Vec<(usize, usize)>,    corrected: bool,    span: Option<(u64, u64)>,}#[derive(Debug, Clone)]pub struct Session {    rules: Rules,    command: bool,    two_pass: bool,    pieces: Vec<Piece>,    next_id: u64,    tentative: String,    /// The current hypothesis as heard (after `frozen`), re-written against    /// the text before it at every answer.    tentative_raw: String,    tentative_upper: bool,    tentative_span: Option<(u64, u64)>,    /// Every word of the current utterance's latest hypothesis, for freezing.    hypothesis: Vec<String>,    live_utt: u64,    /// The words of the current utterance an edit settled, as the live engine    /// heard them: found again in each later hypothesis by what they say    /// ([`frozen_prefix`]), since a re-read may split or join them.    frozen: Vec<String>,    second_next: u64,    /// Utterances a second pass settled before their live final.    by_second: BTreeSet<u64>,    shown: String,    shown_touched: Vec<(usize, usize)>,}#[derive(Debug, Clone, PartialEq, Eq)]pub enum Refused {    /// An offset past the end of the text, or not on a character.    Range,}impl Session {    pub fn new(rules: Rules, command: bool, two_pass: bool) -> Session {        Session {            rules,            command,            two_pass,            pieces: Vec::new(),            next_id: 0,            tentative: String::new(),            tentative_raw: String::new(),            tentative_upper: false,            tentative_span: None,            hypothesis: Vec::new(),            live_utt: 0,            frozen: Vec::new(),            second_next: 0,            by_second: BTreeSet::new(),            shown: String::new(),            shown_touched: Vec::new(),        }    }    pub fn rules(&self) -> &Rules {        &self.rules    }    /// The whole text as it stands.    pub fn text(&self) -> String {        self.render()    }    /// The pieces drawn before the tentative words: every one of an    /// utterance up to the live engine's.    fn split(&self) -> usize {        self.insertion_index(self.live_utt)    }    /// The settled text before the tentative words.    pub fn settled(&self) -> String {        self.pieces[..self.split()].iter().map(|piece| piece.text.as_str()).collect()    }    /// The settled text after the tentative words: utterances a second pass    /// settled before the live engine reached them (rare; usually empty).    pub fn later(&self) -> String {        self.pieces[self.split()..].iter().map(|piece| piece.text.as_str()).collect()    }    /// The person's ranges in [`Self::text`], as byte ranges.    pub fn touched(&self) -> Vec<(usize, usize)> {        self.absolute_touched()    }    fn options(&self, upper_case: bool) -> Options {        Options { upper_case, command: self.command }    }    fn render(&self) -> String {        let mut text = self.settled();        text.push_str(&self.tentative);        text.push_str(&self.later());        text    }    /// Where each piece starts in the rendered text.    fn starts(&self) -> Vec<usize> {        let split = self.split();        let mut at = 0;        let mut out = Vec::with_capacity(self.pieces.len());        for (index, piece) in self.pieces.iter().enumerate() {            if index == split {                at += self.tentative.len();            }            out.push(at);            at += piece.text.len();        }        out    }    fn absolute_touched(&self) -> Vec<(usize, usize)> {        let mut out = Vec::new();        for (piece, at) in self.pieces.iter().zip(self.starts()) {            out.extend(piece.touched.iter().map(|(s, e)| (s + at, e + at)));        }        out    }    /// Where an utterance's pieces go: after every piece of an earlier or the    /// same utterance.    fn insertion_index(&self, utt: u64) -> usize {        self.pieces.iter().position(|piece| piece.utt > utt).unwrap_or(self.pieces.len())    }    fn text_before(&self, index: usize) -> String {        self.pieces[..index].iter().map(|piece| piece.text.as_str()).collect()    }    fn piece(&mut self, utt: u64, text: String, touched: Vec<(usize, usize)>, corrected: bool, span: Option<(u64, u64)>) -> Piece {        self.next_id += 1;        Piece { id: self.next_id, utt, text, touched, corrected, span }    }    /// The tentative tail settles as heard, a piece of the current utterance.    fn freeze_tentative(&mut self) {        if self.tentative.is_empty() {            return;        }        let text = std::mem::take(&mut self.tentative);        self.tentative_raw.clear();        let span = self.tentative_span.take();        let index = self.insertion_index(self.live_utt);        let piece = self.piece(self.live_utt, text, Vec::new(), false, span);        self.pieces.insert(index, piece);        self.frozen = std::mem::take(&mut self.hypothesis);    }    /// One engine result.    pub fn heard(&mut self, heard: &Heard<'_>) -> Answer {        match heard.pass {            Pass::Live => self.live(heard),            Pass::Second => self.second(heard),        }        self.answer()    }    fn live(&mut self, heard: &Heard<'_>) {        if self.by_second.contains(&self.live_utt) {            self.tentative.clear();            self.tentative_raw.clear();            self.tentative_span = None;            self.hypothesis.clear();            if heard.is_final {                self.by_second.remove(&self.live_utt);                self.next_utterance();            }            return;        }        let all: Vec<&str> = heard.text.split_whitespace().collect();        let words = &all[frozen_prefix(&self.frozen, &all)..];        let raw = words.join(" ");        if heard.is_final {            self.tentative.clear();            self.tentative_raw.clear();            self.hypothesis.clear();            if !raw.is_empty() {                let index = self.insertion_index(self.live_utt);                let context = self.rules.context_after(&self.text_before(index));                let text = format::format(&raw, &self.rules, context, self.options(heard.upper_case));                let span = merge_span(self.tentative_span.take(), heard.span);                let piece = self.piece(self.live_utt, text, Vec::new(), false, span);                self.pieces.insert(index, piece);            }            self.next_utterance();        } else {            self.tentative_raw = raw;            self.tentative_upper = heard.upper_case;            self.rewrite_tentative();            self.tentative_span = heard.span.or(self.tentative_span);            self.hypothesis = all.iter().map(|word| word.to_string()).collect();        }    }    /// The tentative words written against the text now before them: a    /// second pass that ended the sentence before raises their first letter.    fn rewrite_tentative(&mut self) {        self.tentative = if self.tentative_raw.is_empty() {            String::new()        } else {            let context = self.rules.context_after(&self.settled());            format::format(&self.tentative_raw, &self.rules, context, self.options(self.tentative_upper))        };    }    fn next_utterance(&mut self) {        self.live_utt += 1;        self.frozen.clear();        self.hypothesis.clear();        self.tentative_span = None;    }    /// Which utterance a second pass re-read.    fn second_target(&self, span: Option<(u64, u64)>) -> u64 {        if let Some((from, to)) = span {            let overlaps = |piece_span: Option<(u64, u64)>| piece_span.is_some_and(|(s, e)| s < to && from < e);            let hit = self                .pieces                .iter()                .filter(|piece| overlaps(piece.span))                .min_by_key(|piece| (piece.corrected, piece.utt));            if let Some(piece) = hit {                return piece.utt;            }            if overlaps(self.tentative_span) {                return self.live_utt;            }        }        self.second_next    }    fn second(&mut self, heard: &Heard<'_>) {        let utt = self.second_target(heard.span);        self.second_next = self.second_next.max(utt + 1);        if heard.text.trim().is_empty() {            return;        }        if utt >= self.live_utt {            if utt == self.live_utt {                self.freeze_tentative();            }            self.by_second.insert(utt);        }        let targets: Vec<usize> = (0..self.pieces.len()).filter(|i| self.pieces[*i].utt == utt).collect();        let first = targets.first().copied().unwrap_or_else(|| self.insertion_index(utt));        let context = self.rules.context_after(&self.text_before(first));        let new = format::format(heard.text, &self.rules, context, self.options(heard.upper_case));        if targets.is_empty() {            let piece = self.piece(utt, new, Vec::new(), true, heard.span);            self.pieces.insert(first, piece);            return;        }        let mut old = String::new();        let mut touched = Vec::new();        let mut span = None;        for index in &targets {            let piece = &self.pieces[*index];            touched.extend(piece.touched.iter().map(|(s, e)| (s + old.len(), e + old.len())));            old.push_str(&piece.text);            span = merge_span(span, piece.span);        }        let (text, touched) = align(&old, &touched, &new);        let span = merge_span(span, heard.span);        for index in targets.iter().rev() {            self.pieces.remove(*index);        }        let piece = self.piece(utt, text, touched, true, span);        self.pieces.insert(first, piece);    }    /// The person changed `[from, to)` (UTF-16, in the text as last answered)    /// to `text`, or with `None` only claimed it.    pub fn touched_range(&mut self, from: usize, to: usize, text: Option<&str>) -> Result<Answer, Refused> {        let current = self.render();        let from = byte_at(&current, from).ok_or(Refused::Range)?;        let to = byte_at(&current, to).ok_or(Refused::Range)?;        if from > to {            return Err(Refused::Range);        }        let (low, high) = (self.settled().len(), self.settled().len() + self.tentative.len());        // A point on a boundary is the text's before it, unless there is none.        let reaches_tentative = !self.tentative.is_empty()            && if from < to { from < high && to > low } else { (from > low && from <= high) || (from == low && self.split() == 0) };        if reaches_tentative {            self.freeze_tentative();        }        if self.pieces.is_empty() {            let inserted = text.unwrap_or_default().to_string();            let len = inserted.len();            let piece = self.piece(self.live_utt, inserted, vec![(0, len)], false, None);            self.pieces.push(piece);        } else {            let mut first = true;            let bounds: Vec<(usize, usize)> = self.pieces.iter().zip(self.starts()).map(|(piece, at)| (at, at + piece.text.len())).collect();            let hits: Vec<usize> = (0..bounds.len())                .filter(|i| {                    let (s, e) = bounds[*i];                    if from == to { s <= from && from <= e } else { s < to && from < e }                })                .collect();            // A point on a boundary belongs to the piece before it only.            let hits: Vec<usize> = if from == to { hits.into_iter().take(1).collect() } else { hits };            if hits.is_empty() {                let inserted = text.unwrap_or_default().to_string();                let len = inserted.len();                let index = self.insertion_index(self.live_utt);                let piece = self.piece(self.live_utt, inserted, vec![(0, len)], false, None);                self.pieces.insert(index, piece);            }            for index in hits {                let (s, _) = bounds[index];                let piece = &mut self.pieces[index];                let local_from = from.max(s) - s;                let local_to = to.min(s + piece.text.len()) - s;                match text {                    None => add_range(&mut piece.touched, (local_from, local_to)),                    Some(inserted) => {                        let inserted = if first { inserted } else { "" };                        splice(piece, local_from, local_to, inserted);                    }                }                first = false;            }            self.pieces.retain(|piece| !piece.text.is_empty() || !piece.touched.is_empty());        }        // The platform already shows the person's change: it is not an edit.        // (The tentative words are written again first, so a change of theirs        // that the person's edit causes is an edit.)        self.shown = self.render();        self.shown_touched = self.absolute_touched();        Ok(self.answer())    }    /// The microphone closed: the tentative tail settles as heard.    pub fn end(&mut self) -> Answer {        self.freeze_tentative();        self.answer()    }    fn awaiting(&self) -> usize {        if !self.two_pass {            return 0;        }        let utts: BTreeSet<u64> = self.pieces.iter().filter(|piece| !piece.corrected && piece.utt < self.live_utt && piece.utt >= self.second_next).map(|piece| piece.utt).collect();        utts.len()    }    fn answer(&mut self) -> Answer {        self.rewrite_tentative();        let text = self.render();        let touched = self.absolute_touched();        let edits = edits(&self.shown, &self.shown_touched, &text, &touched);        self.shown = text;        self.shown_touched = touched;        Answer { settled: self.settled(), tentative: self.tentative.clone(), later: self.later(), edits, awaiting_second: self.awaiting() }    }}/// How many leading words of `heard` re-read the `frozen` words: the prefix/// nearest them word by word (edit distance over words, case and punctuation/// aside), a tie going to the prefix as long as `frozen`. Counting alone lost/// a word whenever the engine re-read its first words as fewer ("seed a" →/// "sita") and doubled one when it re-read them as more.fn frozen_prefix(frozen: &[String], heard: &[&str]) -> usize {    if frozen.is_empty() {        return 0;    }    let key = |word: &str| -> String {        let letters: String = word.chars().filter(|c| c.is_alphanumeric()).flat_map(char::to_lowercase).collect();        if letters.is_empty() { word.to_string() } else { letters }    };    let frozen: Vec<String> = frozen.iter().map(|word| key(word)).collect();    let heard: Vec<String> = heard.iter().map(|word| key(word)).collect();    // row[j]: the distance between the frozen words so far and heard[..j].    let mut row: Vec<usize> = (0..=heard.len()).collect();    for (i, word) in frozen.iter().enumerate() {        let mut next = vec![i + 1; heard.len() + 1];        for j in 1..=heard.len() {            let same = usize::from(*word != heard[j - 1]);            next[j] = (row[j - 1] + same).min(row[j] + 1).min(next[j - 1] + 1);        }        row = next;    }    (0..=heard.len()).min_by_key(|&j| (row[j], j.abs_diff(frozen.len()))).unwrap_or(0)}fn merge_span(a: Option<(u64, u64)>, b: Option<(u64, u64)>) -> Option<(u64, u64)> {    match (a, b) {        (Some((s1, e1)), Some((s2, e2))) => Some((s1.min(s2), e1.max(e2))),        (a, None) => a,        (None, b) => b,    }}/// The byte offset of UTF-16 offset `units` in `text`; `None` past its end or/// inside a character.pub fn byte_at(text: &str, units: usize) -> Option<usize> {    let mut seen = 0;    for (at, c) in text.char_indices() {        if seen == units {            return Some(at);        }        if seen > units {            return None;        }        seen += c.len_utf16();    }    (seen == units).then_some(text.len())}/// The UTF-16 offset of byte `at` in `text`.pub fn units_at(text: &str, at: usize) -> usize {    text[..at].chars().map(char::len_utf16).sum()}fn add_range(ranges: &mut Vec<(usize, usize)>, range: (usize, usize)) {    ranges.push(range);    ranges.sort();    let mut merged: Vec<(usize, usize)> = Vec::new();    for (s, e) in ranges.drain(..) {        match merged.last_mut() {            Some(last) if s < last.1 || (s == last.1 && (s == e || last.0 == last.1)) => last.1 = last.1.max(e),            _ => merged.push((s, e)),        }    }    *ranges = merged;}/// `piece.text[from..to]` becomes `inserted`, which is the person's.fn splice(piece: &mut Piece, from: usize, to: usize, inserted: &str) {    piece.text.replace_range(from..to, inserted);    let delta = inserted.len() as isize - (to - from) as isize;    let shift = |at: usize| (at as isize + delta) as usize;    let mut kept = Vec::new();    let mut joined = (from, from + inserted.len());    for &(s, e) in &piece.touched {        if e < from || (e == from && s < e) {            kept.push((s, e));        } else if s > to || (s == to && s < e) {            kept.push((shift(s), shift(e)));        } else {            // Overlapping the change: it joins the person's new range.            joined = (joined.0.min(s), joined.1.max(if e >= to { shift(e) } else { joined.1 }));        }    }    kept.push(joined);    piece.touched.clear();    for range in kept {        add_range(&mut piece.touched, range);    }}/// A word with the spaces before it, or a line break run of its own.#[derive(Debug, Clone, Copy)]struct Token {    start: usize,    word: usize,    end: usize,}fn tokens(text: &str) -> Vec<Token> {    let mut out = Vec::new();    let bytes: Vec<(usize, char)> = text.char_indices().collect();    let mut i = 0;    while i < bytes.len() {        let start = bytes[i].0;        let mut j = i;        let mut newline = false;        while j < bytes.len() && bytes[j].1.is_whitespace() {            newline |= bytes[j].1 == '\n';            j += 1;        }        let at = |k: usize| if k < bytes.len() { bytes[k].0 } else { text.len() };        if newline || j == bytes.len() {            // Whitespace holding a line break is a token: "new paragraph" is a word said.            if j > i {                out.push(Token { start, word: start, end: at(j) });            }            i = j;            continue;        }        // A word, a run of punctuation, or one character of an unspaced        // script: the first one carries the spaces before it.        let mut lead = start;        while j < bytes.len() && !bytes[j].1.is_whitespace() {            let word = at(j);            let c = bytes[j].1;            let kind = |c: char| if punctuation(c) { 1 } else if super::format::unspaced(c) { 2 } else { 0 };            if kind(c) == 2 {                j += 1;            } else {                while j < bytes.len() && !bytes[j].1.is_whitespace() && kind(bytes[j].1) == kind(c) {                    j += 1;                }            }            out.push(Token { start: lead, word, end: at(j) });            lead = at(j);        }        i = j;    }    out}fn punctuation(c: char) -> bool {    super::format::ATTACH_LEFT.contains(c) || super::format::OPENERS.contains(c) || super::format::CLOSERS.contains(c) || matches!(c, '—' | '-' | '।')}const MOST_ALIGNED: usize = 600;/// `old` re-read as `new`, the person's `touched` ranges of `old` kept as/// they are: the text and its ranges after.pub fn align(old: &str, touched: &[(usize, usize)], new: &str) -> (String, Vec<(usize, usize)>) {    let a = tokens(old);    let b = tokens(new);    let key_a: Vec<&str> = a.iter().map(|t| &old[t.word..t.end]).collect();    let key_b: Vec<&str> = b.iter().map(|t| &new[t.word..t.end]).collect();    let protected: Vec<bool> = a        .iter()        .map(|t| touched.iter().any(|&(s, e)| (s < e && s < t.end && t.word < e) || (s == e && t.word < s && s < t.end)))        .collect();    let blocked_at = |index: usize| -> bool {        let low = if index == 0 { 0 } else { a[index - 1].end };        let high = if index < a.len() { a[index].word } else { old.len() };        touched.iter().any(|&(s, e)| s == e && low <= s && s <= high)    };    // The longest common run of words, by dynamic programming; a text too    // long to align word by word is one change.    let pairs = if a.len() * b.len() <= MOST_ALIGNED * MOST_ALIGNED { lcs(&key_a, &key_b) } else { Vec::new() };    let mut out = String::new();    // (old start, old end, new start) of every old token copied.    let mut copied: Vec<(usize, usize, usize)> = Vec::new();    let mut out_at = vec![0usize; a.len() + 1];    let copy = |out: &mut String, copied: &mut Vec<(usize, usize, usize)>, t: &Token| {        copied.push((t.start, t.end, out.len()));        out.push_str(&old[t.start..t.end]);    };    let (mut i, mut j) = (0, 0);    let mut steps = pairs.into_iter().chain(std::iter::once((a.len(), b.len())));    loop {        let Some((pi, pj)) = steps.next() else { break };        // The hunk old[i..pi] → new[j..pj].        for slot in out_at.iter_mut().take(pi + 1).skip(i) {            *slot = out.len();        }        let guarded: Vec<usize> = (i..pi).filter(|k| protected[*k]).collect();        let fresh = pj - j;        if guarded.is_empty() {            // A place the person deleted words from inside the change: the new            // words beyond the old count are the deleted ones, said again.            let low = if i == 0 { 0 } else { a[i - 1].end };            let high = if pi < a.len() { a[pi].word } else { old.len() };            let deleted = touched.iter().find(|&&(s, e)| s == e && low <= s && s <= high).map(|&(s, _)| s);            let surplus = fresh.saturating_sub(pi - i);            match deleted {                Some(at) if surplus > 0 => {                    let k = (i..pi).filter(|k| a[*k].end <= at).count().min(fresh);                    for t in b[j..j + k].iter().chain(&b[j + k + surplus.min(fresh - k)..pj]) {                        out.push_str(&new[t.start..t.end]);                    }                }                _ => {                    if !(i == pi && blocked_at(i)) {                        for t in &b[j..pj] {                            out.push_str(&new[t.start..t.end]);                        }                    }                }            }        } else {            // By position: each of the person's words stands where it is and            // every other old word is the new word in its place. A word of            // theirs takes the place of a new word only when the re-read has            // more words than the old ones around it, so a word they put over            // a heard one displaces its re-reading while words they inserted            // displace nothing. The new words left over follow.            let unguarded = (pi - i) - guarded.len();            let mut displacing = fresh.saturating_sub(unguarded).min(guarded.len());            let mut cursor = j;            for k in i..pi {                if protected[k] {                    out_at[k] = out.len();                    copy(&mut out, &mut copied, &a[k]);                    if displacing > 0 && cursor < pj {                        displacing -= 1;                        cursor += 1;                    }                } else if cursor < pj {                    // The new word in the old one's place, after the old one's spaces.                    out_at[k] = out.len();                    out.push_str(&old[a[k].start..a[k].word]);                    out.push_str(&new[b[cursor].word..b[cursor].end]);                    cursor += 1;                }            }            for t in &b[cursor..pj] {                out.push_str(&new[t.start..t.end]);            }        }        if pi == a.len() && pj == b.len() {            out_at[a.len()] = out.len();            break;        }        // The common word: the old one is kept as written.        out_at[pi] = out.len();        copy(&mut out, &mut copied, &a[pi]);        i = pi + 1;        j = pj + 1;    }    let map = |at: usize, end: bool| -> Option<usize> {        copied            .iter()            .find(|(s, e, _)| if end { *s < at && at <= *e } else { *s <= at && at < *e })            .map(|(s, _, n)| at - s + n)    };    let mut ranges = Vec::new();    for &(s, e) in touched {        let mapped = if s == e {            map(s, false).or_else(|| map(s, true)).or_else(|| {                let index = a.iter().position(|t| t.start >= s).unwrap_or(a.len());                Some(out_at[index])            })            .map(|at| (at, at))        } else {            map(s, false).zip(map(e, true))        };        if let Some(range) = mapped {            add_range(&mut ranges, range);        }    }    (out, ranges)}/// The index pairs of a longest common subsequence.fn lcs(a: &[&str], b: &[&str]) -> Vec<(usize, usize)> {    let (n, m) = (a.len(), b.len());    let mut table = vec![0u32; (n + 1) * (m + 1)];    let at = |i: usize, j: usize| i * (m + 1) + j;    for i in (0..n).rev() {        for j in (0..m).rev() {            table[at(i, j)] = if a[i] == b[j] { table[at(i + 1, j + 1)] + 1 } else { table[at(i + 1, j)].max(table[at(i, j + 1)]) };        }    }    let (mut i, mut j) = (0, 0);    let mut pairs = Vec::new();    while i < n && j < m {        if a[i] == b[j] {            pairs.push((i, j));            i += 1;            j += 1;        } else if table[at(i + 1, j)] >= table[at(i, j + 1)] {            i += 1;        } else {            j += 1;        }    }    pairs}fn common_prefix(a: &str, b: &str) -> usize {    let mut n = 0;    for ((i, x), y) in a.char_indices().zip(b.chars()) {        if x != y {            return i;        }        n = i + x.len_utf8();    }    n}fn common_suffix(a: &str, b: &str, limit_a: usize, limit_b: usize) -> usize {    let mut n = 0;    for (x, y) in a[limit_a..].chars().rev().zip(b[limit_b..].chars().rev()) {        if x != y {            break;        }        n += x.len_utf8();    }    n}/// `old` → `new` as edits (old's UTF-16 offsets, last first), never across a/// range of the person's that both hold unchanged.pub fn edits(old: &str, old_touched: &[(usize, usize)], new: &str, new_touched: &[(usize, usize)]) -> Vec<Edit> {    if old == new {        return Vec::new();    }    let p = common_prefix(old, new);    let s = common_suffix(old, new, p, p);    let (old_mid, new_mid) = ((p, old.len() - s), (p, new.len() - s));    let inside = |ranges: &[(usize, usize)], (lo, hi): (usize, usize)| -> Vec<(usize, usize)> {        ranges.iter().copied().filter(|&(a, b)| a < b && lo <= a && b <= hi).collect()    };    let olds = inside(old_touched, old_mid);    let news = inside(new_touched, new_mid);    let mut cuts = vec![(old_mid.0, new_mid.0)];    let mut ends = Vec::new();    if olds.len() == news.len() && olds.iter().zip(&news).all(|(o, n)| old[o.0..o.1] == new[n.0..n.1]) {        for (o, n) in olds.iter().zip(&news) {            ends.push((o.0, n.0));            cuts.push((o.1, n.1));        }    }    ends.push((old_mid.1, new_mid.1));    let mut out = Vec::new();    for ((os, ns), (oe, ne)) in cuts.into_iter().zip(ends) {        if oe < os || ne < ns {            continue;        }        let (o, n) = (&old[os..oe], &new[ns..ne]);        if o == n {            continue;        }        for (from, to, text) in hunks(o, n) {            out.push(Edit { from: units_at(old, os + from), to: units_at(old, os + to), text });        }    }    out.sort_by_key(|edit| std::cmp::Reverse(edit.from));    out}/// `o` → `n` as word-level changes `(from, to, text)` in `o`'s bytes, each/// trimmed to the characters that differ; one change when too long to align.fn hunks(o: &str, n: &str) -> Vec<(usize, usize, String)> {    let a = tokens(o);    let b = tokens(n);    let trim = |from: usize, to: usize, text: &str| -> (usize, usize, String) {        let old = &o[from..to];        let p = common_prefix(old, text);        let s = common_suffix(old, text, p, p);        (from + p, to - s, text[p..text.len() - s].to_string())    };    if a.len() * b.len() > MOST_ALIGNED * MOST_ALIGNED {        return vec![trim(0, o.len(), n)];    }    let key_a: Vec<&str> = a.iter().map(|t| &o[t.start..t.end]).collect();    let key_b: Vec<&str> = b.iter().map(|t| &n[t.start..t.end]).collect();    let mut out = Vec::new();    let (mut i, mut j) = (0, 0);    for (pi, pj) in lcs(&key_a, &key_b).into_iter().chain(std::iter::once((a.len(), b.len()))) {        if pi > i || pj > j {            let from = if i < a.len() { a[i].start } else { o.len() };            let to = if pi > i { a[pi - 1].end } else { from };            let text = if pj > j { &n[b[j].start..b[pj - 1].end] } else { "" };            out.push(trim(from, to, text));        }        i = pi + 1;        j = pj + 1;    }    // Text outside every token (spaces at the very end) is one change.    let (old_end, new_end) = (a.last().map_or(0, |t| t.end), b.last().map_or(0, |t| t.end));    if o[old_end..] != n[new_end..] {        out.push(trim(old_end, o.len(), &n[new_end..]));    }    out}/// Apply `edits` (as answered) to `text`: what a platform does.pub fn apply(text: &str, edits: &[Edit]) -> String {    let mut text = text.to_string();    for edit in edits {        let from = byte_at(&text, edit.from).expect("an edit on a character");        let to = byte_at(&text, edit.to).expect("an edit on a character");        text.replace_range(from..to, &edit.text);    }    text}#[cfg(test)]#[path = "session_tests.rs"]mod tests;