OXYGENHUB

Coverage / crates/oxy-core/src/graph.rs 96.8%

1446 of 1494 lines run, 212 of 236 functions · run #386 on main · run missed

1
//! The per-file atom graph (spec §7.3), its materialization, and text conflict
2
//! detection (spec §9.1, §9.5).
3
//!
4
//! The graph is a pure function of the set of changes applied to it: inserts
5
//! add vertices and edges, deletes set a flag, and nothing is ever removed.
6
7
use crate::fasthash::{FastMap as HashMap, FastSet as HashSet};
8
use crate::hash::ChangeHash;
9
use crate::lines::{LineRef, Lines};
10
use crate::objects::AtomRange;
11
use std::collections::{BTreeMap, BTreeSet};
12
13
/// `(introducing change, index within that change for this node)`.
14
pub type AtomKey = (ChangeHash, u32);
15
16
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
17
pub enum Vertex {
18
    Start,
19
    Atom(AtomKey),
20
    End,
21
}
22
23
/// Transitive dependency test between changes; `depends_on(a, a)` is true.
24
pub trait DepOracle {
25
    fn depends_on(&self, a: &ChangeHash, b: &ChangeHash) -> bool;
26
}
27
28
/// Another oracle's answers, each asked once: rendering one file asks about
29
/// the same few pairs over and over (a change deleting a block of lines
30
/// another inserted), and in a long history each answer is a walk through
31
/// thousands of changes (oxygen#96).
32
struct MemoDeps<'a> {
33
    inner: &'a dyn DepOracle,
34
    known: std::cell::RefCell<crate::fasthash::FastMap<(ChangeHash, ChangeHash), bool>>,
35
}
36
37
impl DepOracle for MemoDeps<'_> {
384743×
    fn depends_on(&self, a: &ChangeHash, b: &ChangeHash) -> bool {
394743×
        if let Some(v) = self.known.borrow().get(&(*a, *b)) {
402435×
            return *v;
412308×
        }
422308×
        let v = self.inner.depends_on(a, b);
432308×
        self.known.borrow_mut().insert((*a, *b), v);
442308×
        v
454743×
    }
46
}
47
48
/// No change depends on any other: every pair commutes.
49
pub struct NoDeps;
50
impl DepOracle for NoDeps {
514×
    fn depends_on(&self, a: &ChangeHash, b: &ChangeHash) -> bool {
524×
        a == b
534×
    }
54
}
55
56
#[derive(Default, Clone, Debug)]
57
struct AtomInfo {
58
    /// `None` until the introducing change has been applied; a line of the
59
    /// insert's shared buffer.
60
    content: Option<LineRef>,
61
    deleted_by: BTreeSet<ChangeHash>,
62
}
63
64
#[derive(Clone, Debug)]
65
pub struct FileGraph {
66
    atoms: HashMap<AtomKey, AtomInfo>,
67
    /// Every vertex, with its direct successors.
68
    succ: HashMap<Vertex, Edges>,
69
    /// The live atoms' order, once known to be the graph's only one.
70
    order: OrderSlot,
71
}
72
73
/// A file graph's live atoms in order, when the graph orders them one way
74
/// only: found by [`FileGraph::materialize`] and brought up to date by
75
/// [`Order::splice`] as a change's edits apply, so a long-lived file
76
/// renders in time that follows its live lines rather than every line it
77
/// ever had. Any other change to the graph drops it.
78
#[derive(Debug)]
79
pub struct Order {
80
    atoms: Vec<AtomKey>,
81
    /// Atoms deleted since the order was last confirmed: it holds while
82
    /// none of them is a ghost (spec §9.1), which only a render can ask,
83
    /// since it needs to know how the changes depend on each other.
84
    unchecked: Vec<AtomKey>,
85
    confirmed: std::sync::atomic::AtomicBool,
86
}
87
88
/// Holds a graph's [`Order`]; filled in by a render, which only reads the
89
/// graph.
90
#[derive(Debug, Default)]
91
struct OrderSlot(std::sync::Mutex<Option<std::sync::Arc<Order>>>);
92
93
impl OrderSlot {
9427606×
    fn get(&self) -> Option<std::sync::Arc<Order>> {
9527606×
        self.0.lock().unwrap_or_else(|e| e.into_inner()).clone()
9627606×
    }
971798×
    fn set(&self, o: Option<std::sync::Arc<Order>>) {
981798×
        *self.0.lock().unwrap_or_else(|e| e.into_inner()) = o;
991798×
    }
10066768×
    fn take(&mut self) -> Option<std::sync::Arc<Order>> {
10166768×
        self.0.get_mut().unwrap_or_else(|e| e.into_inner()).take()
10266768×
    }
103
}
104
105
impl Clone for OrderSlot {
1067×
    fn clone(&self) -> Self {
1077×
        OrderSlot(std::sync::Mutex::new(self.get()))
1087×
    }
109
}
110
111
impl Order {
1121788×
    fn known(atoms: Vec<AtomKey>) -> Order {
1131788×
        Order {
1141788×
            atoms,
1151788×
            unchecked: Vec::new(),
1161788×
            confirmed: std::sync::atomic::AtomicBool::new(true),
1171788×
        }
1181788×
    }
119
120
    /// The order after change `h` inserts the runs `inserts` (after,
121
    /// before, first index, count) and deletes `deleted`, as its edits
122
    /// apply; `None` where that is not certain to be the graph's only
123
    /// order: an anchor not in the order, live lines between an insert's
124
    /// anchors, or two inserts with nothing kept between them.
125523×
    fn splice(
126523×
        &self,
127523×
        h: ChangeHash,
128523×
        inserts: &[(Vertex, Vertex, u32, u32)],
129523×
        deleted: &[AtomKey],
130523×
    ) -> Option<std::sync::Arc<Order>> {
131523×
        let mut want: HashSet<AtomKey> = deleted.iter().copied().collect();
132568×
        for (a, b, _, _) in inserts {
1331136×
            for v in [a, b] {
1341136×
                if let Vertex::Atom(k) = v {
135933×
                    want.insert(*k);
136933×
                }
137
            }
138
        }
139523×
        let mut pos: HashMap<AtomKey, usize> = HashMap::default();
1402842×
        for (i, k) in self.atoms.iter().enumerate() {
1412842×
            if want.contains(k) {
1421272×
                pos.insert(*k, i);
1431570×
            }
144
        }
145523×
        let len = self.atoms.len();
146523×
        let mut gone = vec![false; len];
147523×
        let mut unchecked = if self.confirmed.load(std::sync::atomic::Ordering::Relaxed) {
148523×
            Vec::new()
149
        } else {
1500×
            self.unchecked.clone()
151
        };
152727×
        for k in deleted {
153727×
            if k.0 == h {
1540×
                return None;
155727×
            }
156727×
            if let Some(&i) = pos.get(k) {
157704×
                if !gone[i] {
158704×
                    gone[i] = true;
159704×
                    unchecked.push(*k);
160704×
                }
16123×
            }
162
        }
163
        // Each run goes in the gap its anchors leave (slot `i`: before
164
        // `atoms[i]`), which must hold nothing that stays.
165523×
        let mut slots: Vec<(usize, usize, u32, u32)> = Vec::with_capacity(inserts.len());
166549×
        for &(a, b, first, count) in inserts {
167549×
            let from = match a {
168133×
                Vertex::Start => 0,
169416×
                Vertex::Atom(k) => pos.get(&k)? + 1,
1700×
                Vertex::End => return None,
171
            };
172538×
            let to = match b {
17366×
                Vertex::End => len,
174472×
                Vertex::Atom(k) => *pos.get(&k)?,
1750×
                Vertex::Start => return None,
176
            };
177531×
            if from > to || gone[from..to].iter().any(|g| !g) {
1785×
                return None;
179526×
            }
180526×
            slots.push((from, to, first, count));
181
        }
182
        // Runs one after another need a kept line between them, or the
183
        // graph would not say which comes first.
184500×
        slots.sort_unstable();
185500×
        for w in slots.windows(2) {
186158×
            let (end, next) = (w[0].1, w[1].0);
187301×
            if end >= next || !gone[end..next].iter().any(|g| !g) {
1880×
                return None;
189158×
            }
190
        }
191525×
        let added: usize = slots.iter().map(|s| s.3 as usize).sum();
192500×
        let mut atoms = Vec::with_capacity(len + added);
193500×
        let mut slots = slots.into_iter().peekable();
1943130×
        let mut runs_at = |i: usize, atoms: &mut Vec<AtomKey>| {
1953655×
            while let Some(&(from, _, first, count)) = slots.peek() {
1961787×
                if from != i {
1971262×
                    break;
198525×
                }
199770×
                atoms.extend((first..first + count).map(|j| (h, j)));
200525×
                slots.next();
201
            }
2023130×
        };
2032630×
        for (i, (k, g)) in self.atoms.iter().zip(&gone).enumerate() {
2042630×
            runs_at(i, &mut atoms);
2052630×
            if !g {
2061963×
                atoms.push(*k);
2071963×
            }
208
        }
209500×
        runs_at(len, &mut atoms);
210500×
        let confirmed = unchecked.is_empty();
211500×
        Some(std::sync::Arc::new(Order {
212500×
            atoms,
213500×
            unchecked,
214500×
            confirmed: std::sync::atomic::AtomicBool::new(confirmed),
215500×
        }))
216523×
    }
217
}
218
219
/// A vertex's direct successors, sorted and without repeats. Nearly every
220
/// vertex has one, which is kept inline without an allocation.
221
#[derive(Clone, Debug, Default, PartialEq, Eq)]
222
enum Edges {
223
    #[default]
224
    None,
225
    One(Vertex),
226
    Many(Vec<Vertex>),
227
}
228
229
impl Edges {
230244847×
    fn insert(&mut self, v: Vertex) {
23132492×
        match self {
232210571×
            Edges::None => *self = Edges::One(v),
23332492×
            Edges::One(a) if *a == v => {}
23432492×
            Edges::One(a) => {
23532492×
                let a = *a;
23632492×
                *self = Edges::Many(if a < v { vec![a, v] } else { vec![v, a] });
237
            }
2381784×
            Edges::Many(list) => {
2391784×
                if let Err(i) = list.binary_search(&v) {
2401784×
                    list.insert(i, v);
2411784×
                }
242
            }
243
        }
244244847×
    }
245
246964007×
    fn as_slice(&self) -> &[Vertex] {
247964007×
        match self {
2484840×
            Edges::None => &[],
249705792×
            Edges::One(v) => std::slice::from_ref(v),
250253375×
            Edges::Many(list) => list,
251
        }
252964007×
    }
253
254698837×
    fn iter(&self) -> std::slice::Iter<'_, Vertex> {
255698837×
        self.as_slice().iter()
256698837×
    }
257
}
258
259
impl Default for FileGraph {
26026306×
    fn default() -> Self {
26126306×
        Self::new()
26226306×
    }
263
}
264
265
/// One piece of a materialized file.
266
#[derive(Clone, Debug, PartialEq, Eq)]
267
pub enum Segment {
268
    Lines(Vec<AtomKey>),
269
    /// Order conflict: alternatives that cannot be ordered against each other.
270
    Conflict(Vec<Vec<AtomKey>>),
271
    /// Delete/insert conflict: `inserted` was anchored to `deleted` by a change
272
    /// that commutes with the deletion.
273
    Zombie {
274
        deleted: Vec<AtomKey>,
275
        inserted: Vec<AtomKey>,
276
    },
277
}
278
279
#[derive(Clone, Debug, PartialEq, Eq, Default)]
280
pub struct Materialized {
281
    pub segments: Vec<Segment>,
282
}
283
284
impl Materialized {
28533200×
    pub fn is_conflicted(&self) -> bool {
28633200×
        self.segments
28733200×
            .iter()
28833200×
            .any(|s| !matches!(s, Segment::Lines(_)))
28933200×
    }
29025732×
    pub fn conflict_count(&self) -> usize {
29125732×
        self.segments
29225732×
            .iter()
29326390×
            .filter(|s| !matches!(s, Segment::Lines(_)))
29425732×
            .count()
29525732×
    }
296
    /// Every live atom in materialized order, conflict sides concatenated.
2971330×
    pub fn live_atoms(&self) -> Vec<AtomKey> {
2981330×
        let mut out = Vec::new();
2991366×
        for s in &self.segments {
3001366×
            match s {
3011322×
                Segment::Lines(a) => out.extend(a),
30230×
                Segment::Conflict(sides) => sides.iter().for_each(|x| out.extend(x)),
30329×
                Segment::Zombie { inserted, .. } => out.extend(inserted),
304
            }
305
        }
3061330×
        out
3071330×
    }
308
}
309
310
impl FileGraph {
31126376×
    pub fn new() -> Self {
31226376×
        let mut g = FileGraph {
31326376×
            atoms: HashMap::default(),
31426376×
            succ: HashMap::default(),
31526376×
            order: OrderSlot::default(),
31626376×
        };
31726376×
        g.edge(Vertex::Start, Vertex::End);
31826376×
        g
31926376×
    }
320
32131550×
    fn edge(&mut self, a: Vertex, b: Vertex) {
32231550×
        self.succ.entry(a).or_default().insert(b);
32331550×
        self.succ.entry(b).or_default();
32431550×
    }
325
326
    /// Apply an `Insert` by `change` whose first new atom has index `first_index`.
3271042×
    pub fn insert(
3281042×
        &mut self,
3291042×
        change: ChangeHash,
3301042×
        first_index: u32,
3311042×
        after: Vertex,
3321042×
        before: Vertex,
3331042×
        lines: &Lines,
3341042×
    ) {
3351042×
        self.insert_owned(change, first_index, after, before, lines.clone());
3361042×
    }
337
338
    /// [`FileGraph::insert`] taking the lines, so loading a state moves
339
    /// them in rather than copying. Each new atom's entry is made once, as
340
    /// the source of the next edge, and the chain's ends are ensured last.
34133562×
    pub fn insert_owned(
34233562×
        &mut self,
34333562×
        change: ChangeHash,
34433562×
        first_index: u32,
34533562×
        after: Vertex,
34633562×
        before: Vertex,
34733562×
        lines: Lines,
34833562×
    ) {
34933562×
        self.order.take();
35033562×
        self.atoms.reserve(lines.len());
35133562×
        self.succ.reserve(lines.len() + 1);
35233562×
        let mut prev = after;
353179735×
        for i in 0..lines.len() {
354179735×
            let key = (change, first_index + i as u32);
355179735×
            self.atoms.entry(key).or_default().content =
356179735×
                Some(LineRef::new(lines.clone(), i as u32));
357179735×
            let v = Vertex::Atom(key);
358179735×
            self.succ.entry(prev).or_default().insert(v);
359179735×
            prev = v;
360179735×
        }
36133562×
        self.succ.entry(prev).or_default().insert(before);
36233562×
        self.succ.entry(before).or_default();
36333562×
    }
364
365
    /// Apply a `Delete` of `range` by change `by`.
3665660×
    pub fn delete(&mut self, by: ChangeHash, range: &AtomRange) {
3675660×
        self.order.take();
3686058×
        for i in range.from..range.to {
3696058×
            self.atoms
3706058×
                .entry((range.change, i))
3716058×
                .or_default()
3726058×
                .deleted_by
3736058×
                .insert(by);
3746058×
        }
3755660×
    }
376
377478423×
    pub fn is_live(&self, k: &AtomKey) -> bool {
378478423×
        self.atoms
379478423×
            .get(k)
380478423×
            .is_some_and(|a| a.content.is_some() && a.deleted_by.is_empty())
381478423×
    }
382
383165508×
    pub fn content(&self, k: &AtomKey) -> Option<&[u8]> {
384165508×
        self.atoms
385165508×
            .get(k)
386165508×
            .and_then(|a| a.content.as_ref().map(LineRef::bytes))
387165508×
    }
388
389269×
    pub fn deleters(&self, k: &AtomKey) -> impl Iterator<Item = &ChangeHash> {
390269×
        self.atoms
391269×
            .get(k)
392269×
            .into_iter()
393269×
            .flat_map(|a| a.deleted_by.iter())
394269×
    }
395
396
    /// Whether the conflict at `m.segments[i]` is an adjacent insertion
397
    /// (oxygen#121): its sides only add lines between two lines that were
398
    /// next to each other, so keeping every side repeats nothing. It is not
399
    /// when a line there was deleted by a change only some sides build on:
400
    /// two changes that each replaced the same line conflict the same way,
401
    /// and keeping both would keep two versions of it. A line deleted in
402
    /// history every side shares does not count.
4036×
    pub fn adjacent_insertion(&self, m: &Materialized, i: usize, deps: &dyn DepOracle) -> bool {
4046×
        let Some(Segment::Conflict(sides)) = m.segments.get(i) else {
4050×
            return false;
406
        };
4076×
        let before = match i.checked_sub(1).map(|j| &m.segments[j]) {
4080×
            None => Vertex::Start,
4096×
            Some(Segment::Lines(a)) => match a.last() {
4106×
                Some(k) => Vertex::Atom(*k),
4110×
                None => return false,
412
            },
4130×
            Some(_) => return false,
414
        };
4156×
        let on_side: HashSet<AtomKey> = sides.iter().flatten().copied().collect();
4166×
        let side_changes: Vec<BTreeSet<ChangeHash>> = sides
4176×
            .iter()
41812×
            .map(|s| s.iter().map(|a| a.0).collect())
4196×
            .collect();
4206×
        let shared = |d: &ChangeHash| {
4212×
            side_changes
4222×
                .iter()
4234×
                .all(|s| s.iter().any(|c| deps.depends_on(c, d)))
4242×
        };
425
        // From the line before, through the sides' lines and deleted ones,
426
        // up to the next live line.
4276×
        let mut seen: HashSet<AtomKey> = HashSet::default();
4286×
        let mut todo = vec![before];
42918×
        while let Some(v) = todo.pop() {
43026×
            for &w in self.succ.get(&v).map(Edges::as_slice).unwrap_or(&[]) {
43126×
                let Vertex::Atom(k) = w else { continue };
43226×
                if !seen.insert(k) {
4338×
                    continue;
43418×
                }
43518×
                if !on_side.contains(&k) {
4366×
                    if self.is_live(&k) {
4374×
                        continue;
4382×
                    }
4392×
                    if self.deleters(&k).any(|d| !shared(d)) {
4402×
                        return false;
4410×
                    }
44212×
                }
44312×
                todo.push(w);
444
            }
445
        }
4464×
        true
4476×
    }
448
449
    /// Number of atoms introduced by `change` in this graph (for index bookkeeping).
45056×
    pub fn atom_count(&self) -> usize {
45156×
        self.atoms.len()
45256×
    }
453
454
    /// The changes that inserted a live atom directly after `k`. A change
455
    /// that deletes `k` must depend on them (spec §8.1), or `is_ghost`
456
    /// reads the deletion as concurrent with those insertions.
457
    /// Every atom on some path from `first` to `last`, both included, live
458
    /// or deleted (spec §8): the atoms a range of lines is made of, and
459
    /// those that were deleted from between them. Empty when `last` does
460
    /// not follow `first`.
4613×
    pub fn between(&self, first: &AtomKey, last: &AtomKey) -> Vec<AtomKey> {
4623×
        let (from, to) = (Vertex::Atom(*first), Vertex::Atom(*last));
4633×
        let mut ahead: HashSet<Vertex> = HashSet::default();
4643×
        let mut stack = vec![from];
46529×
        while let Some(v) = stack.pop() {
46626×
            if ahead.insert(v) {
46721×
                stack.extend(
46821×
                    self.succ
46921×
                        .get(&v)
47021×
                        .map(|e| e.as_slice())
47121×
                        .unwrap_or(&[])
47221×
                        .iter()
47321×
                        .copied(),
474
                );
4755×
            }
476
        }
4773×
        if !ahead.contains(&to) {
4780×
            return vec![];
4793×
        }
4803×
        let mut pred: HashMap<Vertex, Vec<Vertex>> = HashMap::default();
48128×
        for (u, es) in &self.succ {
48228×
            if ahead.contains(u) {
48323×
                for w in es.iter() {
48423×
                    pred.entry(*w).or_default().push(*u);
48523×
                }
4867×
            }
487
        }
4883×
        let mut behind: HashSet<Vertex> = HashSet::default();
4893×
        let mut stack = vec![to];
49015×
        while let Some(v) = stack.pop() {
49112×
            if behind.insert(v) {
49210×
                stack.extend(pred.get(&v).into_iter().flatten().copied());
49310×
            }
494
        }
4953×
        let mut out: Vec<AtomKey> = ahead
4963×
            .intersection(&behind)
49710×
            .filter_map(|v| match v {
49810×
                Vertex::Atom(k) if self.atoms.contains_key(k) => Some(*k),
4990×
                _ => None,
50010×
            })
5013×
            .collect();
5023×
        out.sort();
5033×
        out
5043×
    }
505
506
    /// The changes that inserted or deleted any of `atoms`.
5073×
    pub fn touching(&self, atoms: &[AtomKey]) -> BTreeSet<ChangeHash> {
5083×
        let mut out = BTreeSet::new();
50910×
        for k in atoms {
51010×
            out.insert(k.0);
51110×
            if let Some(info) = self.atoms.get(k) {
51210×
                out.extend(info.deleted_by.iter().copied());
51310×
            }
514
        }
5153×
        out
5163×
    }
517
5181224×
    pub fn live_successor_changes(&self, k: &AtomKey) -> Vec<ChangeHash> {
5191224×
        self.succ
5201224×
            .get(&Vertex::Atom(*k))
5211224×
            .map(|ss| {
5221223×
                ss.iter()
5231223×
                    .filter_map(|s| match s {
524938×
                        Vertex::Atom(y) if self.is_live(y) => Some(y.0),
525418×
                        _ => None,
5261268×
                    })
5271223×
                    .collect()
5281223×
            })
5291224×
            .unwrap_or_default()
5301224×
    }
531
532361924×
    fn is_ghost(&self, k: &AtomKey, info: &AtomInfo, deps: &dyn DepOracle) -> bool {
533
        // A deleted atom is a ghost when a live direct successor was inserted
534
        // by a change that commutes with every deleter: neither depends on
535
        // the other (spec §9.1, delete/insert). If the inserter came after the
536
        // deletion, or the deleter saw the insertion, there is no conflict.
537361924×
        self.succ.get(&Vertex::Atom(*k)).is_some_and(|ss| {
538476642×
            ss.iter().any(|s| match s {
539476642×
                Vertex::Atom(y) if self.is_live(y) => !info
5404713×
                    .deleted_by
5414713×
                    .iter()
5424817×
                    .any(|d| deps.depends_on(d, &y.0) || deps.depends_on(&y.0, d)),
543502138×
                _ => false,
544506851×
            })
545361924×
        })
546361924×
    }
547
548
    /// Successors of `v` in the graph with non-kept vertices contracted away.
5499526×
    fn reduced_succ(
5509526×
        &self,
5519526×
        v: Vertex,
5529526×
        kept: &HashSet<Vertex>,
5539526×
        memo: &mut HashMap<Vertex, BTreeSet<Vertex>>,
5549526×
    ) -> BTreeSet<Vertex> {
5559526×
        let direct = self.succ.get(&v).map(Edges::as_slice).unwrap_or_default();
556
        // The common case, a successor that is itself kept: nothing to
557
        // contract.
5589873×
        if direct.iter().all(|s| kept.contains(s)) {
5595498×
            return direct.iter().copied().collect();
5604028×
        }
5614028×
        let mut out = BTreeSet::new();
5624028×
        let mut stack: Vec<Vertex> = direct.to_vec();
5634028×
        let mut seen = HashSet::default();
564503038×
        while let Some(s) = stack.pop() {
565499010×
            if kept.contains(&s) {
56634242×
                out.insert(s);
567464768×
            } else if seen.insert(s) {
568319758×
                if let Some(m) = memo.get(&s) {
5690×
                    out.extend(m.iter().copied());
570319758×
                } else if let Some(next) = self.succ.get(&s) {
571319758×
                    stack.extend(next.iter().copied());
572319758×
                }
573145010×
            }
574
        }
5754028×
        out
5769526×
    }
577
578
    /// The atoms in order when the graph is one chain from Start to End with
579
    /// nothing deleted: a file only ever inserted into in sequence, as every
580
    /// file of a fresh commit or a clone is. Such a graph has no conflict.
581
    /// An edge to End besides the chain's next atom (Start's own, or an
582
    /// append's anchor) orders nothing, since End is last anyway.
58325846×
    fn as_chain(&self) -> Option<Vec<AtomKey>> {
58425846×
        if self
58525846×
            .atoms
58625846×
            .values()
587118907×
            .any(|a| a.content.is_none() || !a.deleted_by.is_empty())
588
        {
5892073×
            return None;
59023773×
        }
59123773×
        let mut order = Vec::with_capacity(self.atoms.len());
59223773×
        let mut v = Vertex::Start;
593
        loop {
594134155×
            let succ = self.succ.get(&v)?.as_slice();
595159568×
            let mut atoms = succ.iter().filter(|s| **s != Vertex::End);
596134155×
            match (atoms.next(), atoms.next()) {
59723378×
                (None, _) if succ.contains(&Vertex::End) => break,
598110382×
                (Some(Vertex::Atom(k)), None) if order.len() < self.atoms.len() => {
599110382×
                    order.push(*k);
600110382×
                    v = Vertex::Atom(*k);
601110382×
                }
602395×
                _ => return None,
603
            }
604
        }
60523378×
        (order.len() == self.atoms.len()).then_some(order)
60625846×
    }
607
608
    /// Order the live atoms and locate conflicts.
60927141×
    pub fn materialize(&self, deps: &dyn DepOracle) -> Materialized {
61027141×
        let deps = &MemoDeps {
61127141×
            inner: deps,
61227141×
            known: Default::default(),
61327141×
        };
61427141×
        let lines = |order: Vec<AtomKey>| Materialized {
61526465×
            segments: if order.is_empty() {
616179×
                vec![]
617
            } else {
61826286×
                vec![Segment::Lines(order)]
619
            },
62026465×
        };
621
        use std::sync::atomic::Ordering::Relaxed;
622
        // Which way it went, and how long it took (`OXY_TIMINGS`).
62327141×
        let started = crate::timing::enabled().then(std::time::Instant::now);
62427141×
        let took = |name: &'static str| {
62527141×
            if let Some(t) = started {
6260×
                crate::timing::add(name, t.elapsed());
62727141×
            }
62827141×
        };
62927141×
        if let Some(o) = self.order.get() {
6301311×
            let holds = o.confirmed.load(Relaxed)
631616×
                || o.unchecked.iter().all(|k| {
632616×
                    self.atoms
633616×
                        .get(k)
634616×
                        .is_none_or(|info| !self.is_ghost(k, info, deps))
635616×
                });
6361311×
            if holds {
6371301×
                o.confirmed.store(true, Relaxed);
6381301×
                took("graph: kept order");
6391301×
                return lines(o.atoms.clone());
64010×
            }
64110×
            self.order.set(None);
64225830×
        }
643
        // A chain (nothing ever deleted) is quick to walk, and a fresh tree
644
        // is all chains: no order is kept for one.
64525840×
        if let Some(order) = self.as_chain() {
64623376×
            took("graph: chain");
64723376×
            return lines(order);
6482464×
        }
6492464×
        if let Some(order) = self.as_order(deps) {
6501788×
            self.order
6511788×
                .set(Some(std::sync::Arc::new(Order::known(order.clone()))));
6521788×
            took("graph: single order");
6531788×
            return lines(order);
654676×
        }
655676×
        let m = self.materialize_general(deps);
656676×
        took("graph: general");
657676×
        m
65827141×
    }
659
660
    /// Take the kept order, to [`Order::splice`] it once a change's edits
661
    /// have applied (they drop it).
66227546×
    pub fn take_order(&mut self) -> Option<std::sync::Arc<Order>> {
66327546×
        self.order.take()
66427546×
    }
665
666
    /// Keep `order` (taken before change `h`'s edits applied) spliced by
667
    /// them: `inserts` (after, before, first index, count) and `deleted`.
668
    /// Changes may apply in any order, so a line may arrive already
669
    /// deleted by a change applied before it: then the order is dropped.
670524×
    pub fn keep_spliced(
671524×
        &mut self,
672524×
        order: std::sync::Arc<Order>,
673524×
        h: ChangeHash,
674524×
        inserts: &[(Vertex, Vertex, u32, u32)],
675524×
        deleted: &[AtomKey],
676524×
    ) {
677524×
        let live = inserts
678524×
            .iter()
679837×
            .all(|&(_, _, first, count)| (first..first + count).all(|i| self.is_live(&(h, i))));
680524×
        let spliced = if live {
681523×
            order.splice(h, inserts, deleted)
682
        } else {
6831×
            None
684
        };
685524×
        *self.order.0.get_mut().unwrap_or_else(|e| e.into_inner()) = spliced;
686524×
    }
687
688
    /// The live atoms in order when, with the dead ones contracted away,
689
    /// the graph orders them one way only: no deleted atom is a ghost, and
690
    /// at every step of the topological sort one vertex is next. A file
691
    /// edited without concurrent edits is such a graph, however long its
692
    /// history. `None` otherwise, for [`FileGraph::materialize_general`]
693
    /// to find the conflicts; where this answers, it gives the same order.
6942466×
    fn as_order(&self, deps: &dyn DepOracle) -> Option<Vec<AtomKey>> {
695
        // Kept vertices by dense index: Start, End, then the live atoms.
6962466×
        let mut index: HashMap<Vertex, u32> =
6972466×
            HashMap::with_capacity_and_hasher(self.atoms.len() + 2, Default::default());
6982466×
        let mut verts: Vec<Vertex> = Vec::with_capacity(self.atoms.len() + 2);
6992466×
        verts.extend([Vertex::Start, Vertex::End]);
7002466×
        index.insert(Vertex::Start, 0);
7012466×
        index.insert(Vertex::End, 1);
702104470×
        for (k, info) in &self.atoms {
703104470×
            if info.content.is_none() {
7040×
                continue;
705104470×
            }
706104470×
            if info.deleted_by.is_empty() {
70751017×
                index.insert(Vertex::Atom(*k), verts.len() as u32);
70851017×
                verts.push(Vertex::Atom(*k));
70953453×
            } else if self.is_ghost(k, info, deps) {
710355×
                return None;
71153098×
            }
712
        }
713
        // Each kept vertex's successors, contracting the others: what a
714
        // contracted vertex reaches is worked out once (post-order).
7152111×
        let mut reach: HashMap<Vertex, Vec<u32>> = HashMap::default();
71610794×
        let contracted = |v: Vertex, reach: &mut HashMap<Vertex, Vec<u32>>| {
71710794×
            let mut stack: Vec<(Vertex, bool)> = vec![(v, false)];
71887951×
            while let Some((x, done)) = stack.pop() {
71977157×
                if reach.contains_key(&x) {
7209961×
                    continue;
72167196×
                }
72267196×
                let next = self.succ.get(&x).map(Edges::as_slice).unwrap_or_default();
72367196×
                if !done {
72433598×
                    stack.push((x, true));
72545560×
                    for s in next {
72645560×
                        if !index.contains_key(s) && !reach.contains_key(s) {
72732765×
                            stack.push((*s, false));
72832765×
                        }
729
                    }
73033598×
                    continue;
73133598×
                }
73233598×
                let mut out: Vec<u32> = Vec::new();
73345560×
                for s in next {
73445560×
                    match index.get(s) {
7355508×
                        Some(i) => out.push(*i),
73640052×
                        None => out.extend(reach.get(s).into_iter().flatten()),
737
                    }
738
                }
73933598×
                out.sort_unstable();
74033598×
                out.dedup();
74133598×
                reach.insert(x, out);
742
            }
74310794×
        };
744
        // Successors of vertex `i`: `succ[starts[i]..starts[i + 1]]`.
7452111×
        let mut succ: Vec<u32> = Vec::with_capacity(verts.len() * 2);
7462111×
        let mut starts: Vec<usize> = Vec::with_capacity(verts.len() + 1);
7472111×
        let mut indeg: Vec<u32> = vec![0; verts.len()];
74854258×
        for v in &verts {
74954258×
            let from = succ.len();
75054258×
            starts.push(from);
75163499×
            for s in self.succ.get(v).map(Edges::as_slice).unwrap_or_default() {
75263499×
                match index.get(s) {
75352705×
                    Some(i) => succ.push(*i),
75410794×
                    None => {
75510794×
                        contracted(*s, &mut reach);
75610794×
                        succ.extend(reach.get(s).into_iter().flatten());
75710794×
                    }
758
                }
759
            }
76054258×
            if succ.len() - from > 1 {
7615906×
                succ[from..].sort_unstable();
7625906×
                let mut kept = from;
76317530×
                for i in from..succ.len() {
76417530×
                    if i == from || succ[i] != succ[kept - 1] {
76512438×
                        succ[kept] = succ[i];
76612438×
                        kept += 1;
76712438×
                    }
768
                }
7695906×
                succ.truncate(kept);
77048352×
            }
77158679×
            for &w in &succ[from..] {
77258679×
                indeg[w as usize] += 1;
77358679×
            }
774
        }
7752111×
        starts.push(succ.len());
776
        // Kahn's algorithm, giving up where two vertices are ready at once.
7772111×
        let mut ready: Vec<u32> = (0..verts.len() as u32)
77854258×
            .filter(|&i| indeg[i as usize] == 0)
7792111×
            .collect();
7802111×
        let mut order: Vec<AtomKey> = Vec::with_capacity(verts.len());
7812111×
        let mut seen = 0;
78254759×
        while let Some(v) = ready.pop() {
78352970×
            if !ready.is_empty() {
7840×
                return None;
78552970×
            }
78652970×
            seen += 1;
78752970×
            if let Vertex::Atom(k) = verts[v as usize] {
78849070×
                order.push(k);
78949070×
            }
79057584×
            for &w in &succ[starts[v as usize]..starts[v as usize + 1]] {
79157584×
                indeg[w as usize] -= 1;
79257584×
                if indeg[w as usize] == 0 {
79351503×
                    ready.push(w);
79451503×
                }
795
            }
79652970×
            if ready.len() > 1 {
797322×
                return None;
79852648×
            }
799
        }
8001789×
        (seen == verts.len()).then_some(order)
8012466×
    }
802
803
    /// [`FileGraph::materialize`] for any graph: contraction, then a
804
    /// topological order with conflict regions.
8051170×
    fn materialize_general(&self, deps: &dyn DepOracle) -> Materialized {
806
        // 1. Vertices that survive contraction: live atoms, ghosts, Start, End.
8071170×
        let mut kept: HashSet<Vertex> = HashSet::default();
8081170×
        let mut ghosts: HashSet<AtomKey> = HashSet::default();
8091170×
        kept.insert(Vertex::Start);
8101170×
        kept.insert(Vertex::End);
811314617×
        for (k, info) in &self.atoms {
812314617×
            if info.content.is_none() {
8130×
                continue;
814314617×
            }
815314617×
            if info.deleted_by.is_empty() {
8166762×
                kept.insert(Vertex::Atom(*k));
817307855×
            } else if self.is_ghost(k, info, deps) {
818424×
                kept.insert(Vertex::Atom(*k));
819424×
                ghosts.insert(*k);
820307431×
            }
821
        }
822
823
        // 2. Reduced graph over kept vertices.
8241170×
        let mut memo = HashMap::default();
8251170×
        let mut rsucc: HashMap<Vertex, BTreeSet<Vertex>> = HashMap::default();
8261170×
        let mut indeg: HashMap<Vertex, usize> = HashMap::default();
8279526×
        for &u in &kept {
8289526×
            indeg.entry(u).or_insert(0);
8299526×
            let rs = self.reduced_succ(u, &kept, &mut memo);
83014301×
            for &w in &rs {
83114301×
                *indeg.entry(w).or_insert(0) += 1;
83214301×
            }
8339526×
            rsucc.insert(u, rs);
834
        }
835
836
        // 3. Kahn's algorithm with side labelling for conflict regions.
8371170×
        let mut ready: BTreeSet<Vertex> = indeg
8381170×
            .iter()
8399526×
            .filter(|(_, &d)| d == 0)
8401170×
            .map(|(v, _)| *v)
8411170×
            .collect();
8421170×
        let mut side: HashMap<Vertex, u32> = HashMap::default();
8431170×
        let mut joins: HashSet<Vertex> = HashSet::default();
8441170×
        let mut next_side = 0u32;
8451170×
        let mut plain: Vec<Vertex> = Vec::new();
8461170×
        let mut conflict: Option<BTreeMap<u32, Vec<Vertex>>> = None;
8471170×
        let mut segments: Vec<Segment> = Vec::new();
848
8491637×
        let flush_plain = |plain: &mut Vec<Vertex>, segments: &mut Vec<Segment>| {
8501637×
            let atoms: Vec<AtomKey> = plain
8511637×
                .iter()
8528324×
                .filter_map(|v| {
8538324×
                    if let Vertex::Atom(k) = v {
8545984×
                        Some(*k)
855
                    } else {
8562340×
                        None
857
                    }
8588324×
                })
8591637×
                .collect();
8601637×
            plain.clear();
8611637×
            if !atoms.is_empty() {
8621361×
                segments.extend(split_zombies(atoms, &ghosts));
8631361×
            }
8641637×
        };
8651170×
        let finish_conflict = |c: BTreeMap<u32, Vec<Vertex>>, segments: &mut Vec<Segment>| {
866467×
            let sides: Vec<Vec<AtomKey>> = c
867467×
                .into_values()
868934×
                .map(|vs| {
869934×
                    vs.into_iter()
8701202×
                        .filter_map(|v| match v {
8711202×
                            Vertex::Atom(k) if !ghosts.contains(&k) => Some(k),
87239×
                            _ => None,
8731202×
                        })
874934×
                        .collect::<Vec<_>>()
875934×
                })
876934×
                .filter(|s| !s.is_empty())
877467×
                .collect();
878467×
            match sides.len() {
8790×
                0 => {}
8800×
                1 => segments.push(Segment::Lines(sides.into_iter().next().unwrap())),
881467×
                _ => segments.push(Segment::Conflict(sides)),
882
            }
883467×
        };
884
88510696×
        while !ready.is_empty() {
8869526×
            if ready.len() >= 2 {
887527×
                if conflict.is_none() {
888467×
                    flush_plain(&mut plain, &mut segments);
889467×
                    conflict = Some(BTreeMap::new());
890467×
                }
8911054×
                for r in &ready {
8921054×
                    if !side.contains_key(r) {
893934×
                        side.insert(*r, next_side);
894934×
                        next_side += 1;
895934×
                    }
896
                }
8978999×
            }
8989526×
            let v = ready.pop_first().unwrap();
8999526×
            let my_side = side.get(&v).copied();
9009526×
            match (&mut conflict, my_side) {
9011202×
                (Some(c), Some(s)) => c.entry(s).or_default().push(v),
902467×
                (Some(_), None) => {
903467×
                    let c = conflict.take().unwrap();
904467×
                    finish_conflict(c, &mut segments);
905467×
                    plain.push(v);
906467×
                }
9077857×
                (None, _) => plain.push(v),
908
            }
90914301×
            for &w in &rsucc[&v] {
91014301×
                let d = indeg.get_mut(&w).unwrap();
91114301×
                *d -= 1;
91214301×
                if conflict.is_some() && !joins.contains(&w) {
9131322×
                    match (my_side, side.get(&w).copied()) {
914788×
                        (Some(s), None) => {
915788×
                            side.insert(w, s);
916788×
                        }
917534×
                        (Some(s), Some(t)) if s != t => {
918520×
                            side.remove(&w);
919520×
                            joins.insert(w);
920520×
                        }
9210×
                        (None, Some(_)) => {
9220×
                            side.remove(&w);
9230×
                            joins.insert(w);
9240×
                        }
92514×
                        _ => {}
926
                    }
92712979×
                }
92814301×
                if *d == 0 {
9298356×
                    ready.insert(w);
9308356×
                }
931
            }
932
        }
9331170×
        if let Some(c) = conflict.take() {
9340×
            finish_conflict(c, &mut segments);
9351170×
        }
9361170×
        flush_plain(&mut plain, &mut segments);
9371170×
        Materialized { segments }
9381170×
    }
939
940
    /// Render a materialization to bytes with conflict markers (spec §9.5).
941
    /// `label` gives the short description of a change for marker headers.
94225731×
    pub fn render(&self, m: &Materialized, label: &dyn Fn(&ChangeHash) -> String) -> Vec<u8> {
94325731×
        let total = m.conflict_count();
94425731×
        let mut n = 0;
94525731×
        let mut out: Vec<u8> = Vec::new();
94627006×
        let push_atoms = |out: &mut Vec<u8>, atoms: &[AtomKey]| {
947165348×
            for a in atoms {
948165348×
                if let Some(c) = self.content(a) {
949165348×
                    out.extend_from_slice(c);
950165348×
                }
951
            }
95227006×
        };
95325731×
        let newline_if_needed = |out: &mut Vec<u8>| {
9541857×
            if !out.is_empty() && *out.last().unwrap() != b'\n' {
9550×
                out.push(b'\n');
9561857×
            }
9571857×
        };
95826387×
        for seg in &m.segments {
95926387×
            match seg {
96025768×
                Segment::Lines(a) => push_atoms(&mut out, a),
961352×
                Segment::Conflict(sides) => {
962352×
                    n += 1;
963352×
                    let k = sides.len();
964704×
                    for (i, s) in sides.iter().enumerate() {
965704×
                        newline_if_needed(&mut out);
966704×
                        let who = s.first().map(|a| label(&a.0)).unwrap_or_default();
967704×
                        let marker = if i == 0 { "<<<<<<<" } else { "=======" };
968704×
                        out.extend_from_slice(
969704×
                            format!("{marker} oxy conflict {n} of {total}, side {} of {k}: change {who}\n", i + 1).as_bytes(),
970
                        );
971704×
                        push_atoms(&mut out, s);
972
                    }
973352×
                    newline_if_needed(&mut out);
974352×
                    out.extend_from_slice(
975352×
                        format!(">>>>>>> oxy conflict {n} of {total} end\n").as_bytes(),
976
                    );
977
                }
978267×
                Segment::Zombie { deleted, inserted } => {
979267×
                    n += 1;
980267×
                    newline_if_needed(&mut out);
981267×
                    let deleter = deleted
982267×
                        .first()
983267×
                        .and_then(|a| self.deleters(a).next().copied())
984267×
                        .map(|d| label(&d))
985267×
                        .unwrap_or_default();
986267×
                    let inserter = inserted.first().map(|a| label(&a.0)).unwrap_or_default();
987267×
                    out.extend_from_slice(
988267×
                        format!("<<<<<<< oxy conflict {n} of {total}, side 1 of 2: deleted by change {deleter}\n-------\n").as_bytes(),
989
                    );
990267×
                    push_atoms(&mut out, deleted);
991267×
                    newline_if_needed(&mut out);
992267×
                    out.extend_from_slice(
993267×
                        format!(
994267×
                            "======= oxy conflict {n} of {total}, side 2 of 2: change {inserter}\n"
995267×
                        )
996267×
                        .as_bytes(),
997
                    );
998267×
                    push_atoms(&mut out, inserted);
999267×
                    newline_if_needed(&mut out);
1000267×
                    out.extend_from_slice(
1001267×
                        format!(">>>>>>> oxy conflict {n} of {total} end\n").as_bytes(),
1002
                    );
1003
                }
1004
            }
1005
        }
100625731×
        out
100725731×
    }
1008
}
1009
101035216×
fn vertex_value(v: &Vertex) -> crate::cbor::Value {
1011
    use crate::cbor::Value;
101235216×
    match v {
10133433×
        Vertex::Start => Value::Uint(0),
10143544×
        Vertex::End => Value::Uint(1),
101528239×
        Vertex::Atom((c, i)) => {
101628239×
            Value::Array(vec![Value::Bytes(c.0.to_vec()), Value::Uint(*i as u64)])
1017
        }
1018
    }
101935216×
}
1020
102110348×
fn vertex_from(v: &crate::cbor::Value) -> Result<Vertex, crate::objects::ObjectError> {
1022
    use crate::cbor::Value;
1023
    use crate::objects::ObjectError;
10248696×
    match v {
1025727×
        Value::Uint(0) => Ok(Vertex::Start),
1026925×
        Value::Uint(1) => Ok(Vertex::End),
10278696×
        Value::Array(a) if a.len() == 2 => Ok(Vertex::Atom((
10288696×
            crate::objects::oref(&a[0], "vertex")?,
10298696×
            crate::objects::u32_(&a[1], "vertex")?,
1030
        ))),
10310×
        _ => Err(ObjectError::Schema(
10320×
            "vertex: expected 0, 1, or [hash, index]".into(),
10330×
        )),
1034
    }
103510348×
}
1036
1037
impl FileGraph {
1038
    /// Serialize for a checkpoint: `{0: atoms [[hash, index, content|null, [deleters]]], 1: edges [[from, to]]}`.
10391553×
    pub fn to_value(&self) -> crate::cbor::Value {
1040
        use crate::cbor::Value;
10411553×
        let mut atoms: Vec<(&AtomKey, &AtomInfo)> = self.atoms.iter().collect();
10421553×
        atoms.sort_by_key(|(k, _)| **k);
10431553×
        let mut edges: Vec<(Vertex, Vertex)> = self
10441553×
            .succ
10451553×
            .iter()
104617608×
            .flat_map(|(a, bs)| bs.iter().map(move |b| (*a, *b)))
10471553×
            .collect();
10481553×
        edges.sort();
10491553×
        Value::map([
1050
            (
1051
                0,
1052
                Value::Array(
10531553×
                    atoms
10541553×
                        .into_iter()
105512805×
                        .map(|((c, i), info)| {
105612805×
                            Value::Array(vec![
105712805×
                                Value::Bytes(c.0.to_vec()),
105812805×
                                Value::Uint(*i as u64),
105912805×
                                info.content
106012805×
                                    .as_ref()
106112805×
                                    .map(|b| Value::Bytes(b.bytes().to_vec()))
106212805×
                                    .unwrap_or(Value::Null),
1063
                                Value::Array(
106412805×
                                    info.deleted_by
106512805×
                                        .iter()
106612805×
                                        .map(|d| Value::Bytes(d.0.to_vec()))
106712805×
                                        .collect(),
1068
                                ),
1069
                            ])
107012805×
                        })
10711553×
                        .collect(),
1072
                ),
1073
            ),
1074
            (
1075
                1,
1076
                Value::Array(
10771553×
                    edges
10781553×
                        .iter()
107917608×
                        .map(|(a, b)| Value::Array(vec![vertex_value(a), vertex_value(b)]))
10801553×
                        .collect(),
1081
                ),
1082
            ),
1083
        ])
10841553×
    }
1085
1086341×
    pub fn from_value(v: &crate::cbor::Value) -> Result<FileGraph, crate::objects::ObjectError> {
1087
        use crate::objects::{array, bytes, field, map, oref, u32_, ObjectError};
1088341×
        let m = map(v, "file graph")?;
1089341×
        let mut g = FileGraph {
1090341×
            atoms: HashMap::default(),
1091341×
            succ: HashMap::default(),
1092341×
            order: OrderSlot::default(),
1093341×
        };
1094341×
        let atoms = array(field(m, 0, "atoms")?, "atoms")?;
1095
        // Every atom's line in one buffer.
1096341×
        let mut texts: Vec<&[u8]> = Vec::new();
10974117×
        for a in atoms {
10984117×
            let e = array(a, "atom")?;
10994117×
            if e.len() == 4 && !e[2].is_null() {
11004117×
                texts.push(bytes(&e[2], "atom content")?);
11010×
            }
1102
        }
1103341×
        let all: Lines = texts.into_iter().collect();
1104341×
        let mut next = 0u32;
11054117×
        for a in atoms {
11064117×
            let e = array(a, "atom")?;
11074117×
            if e.len() != 4 {
11080×
                return Err(ObjectError::Schema("atom: expected 4 fields".into()));
11094117×
            }
11104117×
            let key = (oref(&e[0], "atom change")?, u32_(&e[1], "atom index")?);
11114117×
            let content = if e[2].is_null() {
11120×
                None
1113
            } else {
11144117×
                next += 1;
11154117×
                Some(LineRef::new(all.clone(), next - 1))
1116
            };
11174117×
            let deleted_by = array(&e[3], "deleters")?
11184117×
                .iter()
11194117×
                .map(|d| oref(d, "deleter"))
11204117×
                .collect::<Result<BTreeSet<_>, _>>()?;
11214117×
            g.atoms.insert(
11224117×
                key,
11234117×
                AtomInfo {
11244117×
                    content,
11254117×
                    deleted_by,
11264117×
                },
1127
            );
1128
        }
11295174×
        for e in array(field(m, 1, "edges")?, "edges")? {
11305174×
            let pair = array(e, "edge")?;
11315174×
            if pair.len() != 2 {
11320×
                return Err(ObjectError::Schema("edge: expected [from, to]".into()));
11335174×
            }
11345174×
            g.edge(vertex_from(&pair[0])?, vertex_from(&pair[1])?);
1135
        }
1136341×
        Ok(g)
1137341×
    }
1138
}
1139
1140
/// Split a plain run into `Lines` and `Zombie` segments around ghost atoms.
11411361×
fn split_zombies(atoms: Vec<AtomKey>, ghosts: &HashSet<AtomKey>) -> Vec<Segment> {
11421361×
    let mut out = Vec::new();
11431361×
    let mut lines: Vec<AtomKey> = Vec::new();
11441361×
    let mut i = 0;
11456910×
    while i < atoms.len() {
11465549×
        if !ghosts.contains(&atoms[i]) {
11475164×
            lines.push(atoms[i]);
11485164×
            i += 1;
11495164×
            continue;
1150385×
        }
1151385×
        if !lines.is_empty() {
1152230×
            out.push(Segment::Lines(std::mem::take(&mut lines)));
1153230×
        }
1154385×
        let mut deleted = Vec::new();
1155770×
        while i < atoms.len() && ghosts.contains(&atoms[i]) {
1156385×
            deleted.push(atoms[i]);
1157385×
            i += 1;
1158385×
        }
1159385×
        let mut inserted = Vec::new();
1160385×
        if i < atoms.len() {
1161358×
            let ch = atoms[i].0;
1162793×
            while i < atoms.len() && atoms[i].0 == ch && !ghosts.contains(&atoms[i]) {
1163435×
                inserted.push(atoms[i]);
1164435×
                i += 1;
1165435×
            }
116627×
        }
1167385×
        out.push(Segment::Zombie { deleted, inserted });
1168
    }
11691361×
    if !lines.is_empty() {
11701160×
        out.push(Segment::Lines(lines));
11711160×
    }
11721361×
    out
11731361×
}
1174
1175
#[cfg(test)]
1176
mod tests {
1177
    use super::*;
1178
    use crate::hash::ObjectRef;
1179
1180156×
    fn h(n: u8) -> ChangeHash {
1181156×
        ObjectRef([n; 32])
1182156×
    }
1183792×
    fn lines(v: &[&str]) -> Lines {
11841741×
        v.iter().map(|s| s.as_bytes()).collect()
1185792×
    }
118666×
    fn text(g: &FileGraph, m: &Materialized) -> String {
1187208×
        String::from_utf8(g.render(m, &|c| c.short(4))).unwrap()
118866×
    }
1189
1190
    struct Deps(HashMap<ChangeHash, Vec<ChangeHash>>);
1191
    impl DepOracle for Deps {
11921705×
        fn depends_on(&self, a: &ChangeHash, b: &ChangeHash) -> bool {
11931705×
            if a == b {
11940×
                return true;
11951705×
            }
11961705×
            let mut stack = vec![*a];
11971705×
            let mut seen = HashSet::default();
119850101×
            while let Some(x) = stack.pop() {
119949787×
                if let Some(ds) = self.0.get(&x) {
12007887494×
                    for d in ds {
12017887494×
                        if d == b {
12021391×
                            return true;
12037886103×
                        }
12047886103×
                        if seen.insert(*d) {
1205362101×
                            stack.push(*d);
12067524002×
                        }
1207
                    }
1208314×
                }
1209
            }
1210314×
            false
12111705×
        }
1212
    }
1213
1214
    /// Linear history: each change depends on every earlier one.
1215
    struct Linear;
1216
    impl DepOracle for Linear {
121749×
        fn depends_on(&self, a: &ChangeHash, b: &ChangeHash) -> bool {
121849×
            a.0[..2] >= b.0[..2]
121949×
        }
1220
    }
1221
1222
    /// A file of `n` lines edited `revs` times, `per` lines replaced each
1223
    /// time, as a long-lived file is: most atoms dead, one live chain.
12241×
    fn edited_file(n: usize, revs: usize, per: usize) -> FileGraph {
1225401×
        let hn = |i: usize| {
1226401×
            let mut b = [0u8; 32];
1227401×
            b[..2].copy_from_slice(&(i as u16).to_be_bytes());
1228401×
            ObjectRef(b)
1229401×
        };
12301×
        let mut g = FileGraph::new();
1231500×
        let first: Vec<String> = (0..n).map(|i| format!("line {i}\n")).collect();
12321×
        let first: Vec<&str> = first.iter().map(String::as_str).collect();
12331×
        g.insert(hn(1), 0, Vertex::Start, Vertex::End, &lines(&first));
123410×
        for r in 2..revs + 2 {
123510×
            let order = g.materialize(&Linear).live_atoms();
123610×
            let step = order.len() / per;
1237200×
            for j in 0..per {
1238200×
                let at = j * step + (r % step.max(1));
1239200×
                let k = order[at];
1240200×
                g.delete(
1241200×
                    hn(r),
1242200×
                    &AtomRange {
1243200×
                        change: k.0,
1244200×
                        from: k.1,
1245200×
                        to: k.1 + 1,
1246200×
                    },
1247
                );
1248200×
                let after = if at == 0 {
12490×
                    Vertex::Start
1250
                } else {
1251200×
                    Vertex::Atom(order[at - 1])
1252
                };
1253200×
                let before = order
1254200×
                    .get(at + 1)
1255200×
                    .map(|k| Vertex::Atom(*k))
1256200×
                    .unwrap_or(Vertex::End);
1257200×
                g.insert(hn(r), j as u32, after, before, &lines(&["new\n"]));
1258
            }
1259
        }
12601×
        g
12611×
    }
1262
1263
    /// The single-order shortcut gives what the general algorithm gives.
1264
    #[test]
12651×
    fn the_order_shortcut_agrees_with_the_general_order() {
12661×
        let g = edited_file(500, 10, 20);
12671×
        assert!(g.as_chain().is_none());
12681×
        let fast = g.as_order(&Linear).expect("a single order");
12691×
        assert_eq!(
12701×
            Materialized {
12711×
                segments: vec![Segment::Lines(fast)]
12721×
            },
12731×
            g.materialize_general(&Linear)
1274
        );
1275
        // Two changes inserting at one place concurrently: a conflict,
1276
        // which the shortcut leaves to the general algorithm.
12771×
        let mut g = FileGraph::new();
12781×
        g.insert(h(1), 0, Vertex::Start, Vertex::End, &lines(&["a\n"]));
12791×
        let a = Vertex::Atom((h(1), 0));
12801×
        g.insert(h(2), 0, a, Vertex::End, &lines(&["b\n"]));
12811×
        g.insert(h(3), 0, a, Vertex::End, &lines(&["c\n"]));
12821×
        assert!(g.as_order(&NoDeps).is_none());
12831×
        assert!(g.materialize(&NoDeps).is_conflicted());
12841×
    }
1285
1286
    /// Applied as the state applies a change's edits: the kept order is
1287
    /// spliced by them.
1288491×
    fn apply_spliced(
1289491×
        g: &mut FileGraph,
1290491×
        h: ChangeHash,
1291491×
        inserts: &[(Vertex, Vertex, usize)],
1292491×
        deleted: &[AtomKey],
1293491×
    ) {
1294491×
        let order = g.take_order();
1295491×
        let mut runs = Vec::new();
1296491×
        let mut next = 0u32;
1297554×
        for (i, &(a, b, n)) in inserts.iter().enumerate() {
1298947×
            let text: Vec<String> = (0..n).map(|j| format!("{i}.{j}\n")).collect();
1299554×
            let text: Vec<&str> = text.iter().map(String::as_str).collect();
1300554×
            g.insert(h, next, a, b, &lines(&text));
1301554×
            runs.push((a, b, next, n as u32));
1302554×
            next += n as u32;
1303
        }
13041003×
        for k in deleted {
13051003×
            g.delete(
13061003×
                h,
13071003×
                &AtomRange {
13081003×
                    change: k.0,
13091003×
                    from: k.1,
13101003×
                    to: k.1 + 1,
13111003×
                },
13121003×
            );
13131003×
        }
1314491×
        if let Some(o) = order {
1315458×
            g.keep_spliced(o, h, &runs, deleted);
1316458×
        }
1317491×
    }
1318
1319
    /// Edits as a diff makes them from the order `l`: hunks with a kept
1320
    /// line between them, each deleting some lines and inserting some.
1321457×
    fn random_edits(
1322457×
        l: &[AtomKey],
1323457×
        rnd: &mut impl FnMut(usize) -> usize,
1324457×
    ) -> (Vec<(Vertex, Vertex, usize)>, Vec<AtomKey>) {
1325457×
        let (mut inserts, mut deleted) = (Vec::new(), Vec::new());
1326457×
        let mut i = rnd(3);
13271247×
        while i <= l.len() {
1328790×
            let del = rnd(3).min(l.len() - i);
1329790×
            let add = rnd(3);
1330790×
            let after = if i == 0 {
1331169×
                Vertex::Start
1332
            } else {
1333621×
                Vertex::Atom(l[i - 1])
1334
            };
1335790×
            let before = l.get(i).map(|k| Vertex::Atom(*k)).unwrap_or(Vertex::End);
1336790×
            deleted.extend(&l[i..i + del]);
1337790×
            if add > 0 {
1338522×
                inserts.push((after, before, add));
1339522×
            }
1340790×
            i += del + 1 + rnd(6);
1341
        }
1342457×
        (inserts, deleted)
1343457×
    }
1344
1345
    /// The kept order, spliced change by change, is what the general
1346
    /// algorithm finds, through sequential edits and through concurrent
1347
    /// ones that leave conflicts and ghosts (where it must stand aside).
1348
    #[test]
13491×
    fn the_kept_order_follows_edits() {
1350490×
        let hn = |i: usize| {
1351490×
            let mut b = [0u8; 32];
1352490×
            b[..2].copy_from_slice(&(i as u16).to_be_bytes());
1353490×
            ObjectRef(b)
1354490×
        };
13551×
        let mut seed = 7u64;
13562827×
        let mut rnd = move |n: usize| {
13572827×
            seed = seed
13582827×
                .wrapping_mul(6364136223846793005)
13592827×
                .wrapping_add(1442695040888963407);
13602827×
            ((seed >> 33) as usize) % n.max(1)
13612827×
        };
13621×
        let mut deps = Deps(HashMap::default());
13631×
        let mut g = FileGraph::new();
136440×
        let first: Vec<String> = (0..40).map(|i| format!("{i}\n")).collect();
13651×
        let first: Vec<&str> = first.iter().map(String::as_str).collect();
13661×
        g.insert(hn(1), 0, Vertex::Start, Vertex::End, &lines(&first));
13671×
        let mut known: Vec<ChangeHash> = vec![hn(1)];
13681×
        let mut c = 2;
13691×
        let (mut spliced, mut conflicted) = (0, 0);
1370400×
        for step in 0..400 {
1371400×
            let l = g.materialize(&deps).live_atoms();
1372
            // Now and then two changes from the same base, neither knowing
1373
            // the other.
1374400×
            let pair = step % 7 == 3;
1375400×
            let base = known.clone();
1376400×
            for _ in 0..if pair { 2 } else { 1 } {
1377457×
                let h = hn(c);
1378457×
                c += 1;
1379457×
                let (inserts, deleted) = random_edits(&l, &mut rnd);
1380457×
                deps.0.insert(h, base.clone());
1381457×
                apply_spliced(&mut g, h, &inserts, &deleted);
1382457×
                known.push(h);
1383457×
                if g.order.get().is_some() {
1384433×
                    spliced += 1;
1385433×
                }
1386457×
                let m = g.materialize(&deps);
1387457×
                assert_eq!(m, g.materialize_general(&deps), "step {step}");
1388457×
                if m.is_conflicted() {
138931×
                    conflicted += 1;
1390426×
                }
1391
            }
1392
            // A change that knows everything settles any conflict by
1393
            // rewriting the file.
1394400×
            if g.materialize(&deps).is_conflicted() {
139531×
                let h = hn(c);
139631×
                c += 1;
139731×
                let all = g.materialize(&deps).live_atoms();
139831×
                deps.0.insert(h, known.clone());
139931×
                apply_spliced(&mut g, h, &[(Vertex::Start, Vertex::End, 5)], &all);
140031×
                known.push(h);
140131×
                assert_eq!(g.materialize(&deps), g.materialize_general(&deps));
1402369×
            }
1403
        }
14041×
        assert!(
14051×
            spliced > 100 && conflicted > 0,
1406
            "{spliced} spliced, {conflicted} conflicted"
1407
        );
14081×
    }
1409
1410
    /// A change applied before the one whose line it deletes (as a merge
1411
    /// adds the other side, newest first): the line arrives dead, and the
1412
    /// kept order must not take it in.
1413
    #[test]
14141×
    fn the_kept_order_takes_no_line_that_arrives_deleted() {
14151×
        let mut deps = Deps(HashMap::default());
14161×
        let mut g = FileGraph::new();
14171×
        g.insert(
14181×
            h(1),
1419
            0,
14201×
            Vertex::Start,
14211×
            Vertex::End,
14221×
            &lines(&["a\n", "b\n", "c\n"]),
1423
        );
1424
        // A deletion, so the order is kept rather than walked as a chain.
14251×
        apply_spliced(&mut g, h(2), &[], &[(h(1), 2)]);
14261×
        deps.0.insert(h(2), vec![h(1)]);
14271×
        let _ = g.materialize(&deps);
14281×
        assert!(g.order.get().is_some());
14291×
        let (a, b) = (Vertex::Atom((h(1), 0)), Vertex::Atom((h(1), 1)));
1430
        // h(3) inserts x between a and b; h(4) deletes it. h(4) first.
14311×
        deps.0.insert(h(3), vec![h(2)]);
14321×
        deps.0.insert(h(4), vec![h(3)]);
14331×
        apply_spliced(&mut g, h(4), &[], &[(h(3), 0)]);
14341×
        apply_spliced(&mut g, h(3), &[(a, b, 1)], &[]);
14351×
        let m = g.materialize(&deps);
14361×
        assert_eq!(m, g.materialize_general(&deps));
14371×
        assert_eq!(text(&g, &m), "a\nb\n");
14381×
    }
1439
1440
    /// How long rendering a long-lived file takes (run by hand, in release).
1441
    #[test]
1442
    #[ignore]
14430×
    fn bench_materialize_edited_file() {
14440×
        let g = edited_file(20_000, 50, 100);
14450×
        let t = std::time::Instant::now();
14460×
        let mut n = 0;
14470×
        for _ in 0..20 {
14480×
            n += g.materialize(&Linear).live_atoms().len();
14490×
        }
14500×
        eprintln!(
1451
            "materialize: {:.2} ms each ({n} atoms)",
14520×
            t.elapsed().as_secs_f64() * 1000.0 / 20.0
1453
        );
14540×
    }
1455
1456
    /// The chain shortcut agrees with the general algorithm wherever it
1457
    /// applies, and stands aside wherever it does not.
1458
    #[test]
14591×
    fn the_chain_shortcut_agrees_with_the_general_order() {
14601×
        let mut g = FileGraph::new();
14611×
        g.insert(
14621×
            h(1),
1463
            0,
14641×
            Vertex::Start,
14651×
            Vertex::End,
14661×
            &lines(&["a\n", "b\n", "c\n"]),
1467
        );
14681×
        assert!(g.as_chain().is_some());
14691×
        assert_eq!(g.materialize(&NoDeps), g.materialize_general(&NoDeps));
1470
        // Appended after the last line: still a chain.
14711×
        g.insert(
14721×
            h(2),
1473
            0,
14741×
            Vertex::Atom((h(1), 2)),
14751×
            Vertex::End,
14761×
            &lines(&["d\n"]),
1477
        );
14781×
        assert!(g.as_chain().is_some());
14791×
        assert_eq!(g.materialize(&NoDeps), g.materialize_general(&NoDeps));
1480
        // Inserted between two lines: not a chain (a has two successors).
14811×
        g.insert(
14821×
            h(4),
1483
            0,
14841×
            Vertex::Atom((h(1), 0)),
14851×
            Vertex::Atom((h(1), 1)),
14861×
            &lines(&["x\n"]),
1487
        );
14881×
        assert!(g.as_chain().is_none());
14891×
        assert_eq!(text(&g, &g.materialize(&NoDeps)), "a\nx\nb\nc\nd\n");
1490
        // Two inserts at one anchor: a conflict, never a chain.
14911×
        let mut c = FileGraph::new();
14921×
        c.insert(h(1), 0, Vertex::Start, Vertex::End, &lines(&["a\n"]));
14931×
        c.insert(h(2), 0, Vertex::Start, Vertex::End, &lines(&["b\n"]));
14941×
        assert!(c.as_chain().is_none());
14951×
        assert!(c.materialize(&NoDeps).is_conflicted());
1496
        // A deletion: not a chain.
14971×
        let mut d = FileGraph::new();
14981×
        d.insert(h(1), 0, Vertex::Start, Vertex::End, &lines(&["a\n", "b\n"]));
14991×
        d.delete(
15001×
            h(3),
15011×
            &AtomRange {
15021×
                change: h(1),
15031×
                from: 0,
15041×
                to: 1,
15051×
            },
1506
        );
15071×
        assert!(d.as_chain().is_none());
15081×
        assert_eq!(d.materialize(&NoDeps), d.materialize_general(&NoDeps));
1509
        // Empty.
15101×
        let e = FileGraph::new();
15111×
        assert_eq!(e.materialize(&NoDeps), e.materialize_general(&NoDeps));
15121×
    }
1513
1514
    #[test]
15151×
    fn sequential_inserts_and_deletes() {
15161×
        let mut g = FileGraph::new();
15171×
        g.insert(
15181×
            h(1),
1519
            0,
15201×
            Vertex::Start,
15211×
            Vertex::End,
15221×
            &lines(&["a\n", "b\n", "c\n"]),
1523
        );
15241×
        let m = g.materialize(&NoDeps);
15251×
        assert!(!m.is_conflicted());
15261×
        assert_eq!(text(&g, &m), "a\nb\nc\n");
1527
1528
        // Change 2 depends on 1, inserts between b and c and deletes a.
15291×
        g.insert(
15301×
            h(2),
1531
            0,
15321×
            Vertex::Atom((h(1), 1)),
15331×
            Vertex::Atom((h(1), 2)),
15341×
            &lines(&["x\n"]),
1535
        );
15361×
        g.delete(
15371×
            h(2),
15381×
            &AtomRange {
15391×
                change: h(1),
15401×
                from: 0,
15411×
                to: 1,
15421×
            },
1543
        );
15441×
        let deps = Deps([(h(2), vec![h(1)])].into_iter().collect());
15451×
        let m = g.materialize(&deps);
15461×
        assert!(!m.is_conflicted());
15471×
        assert_eq!(text(&g, &m), "b\nx\nc\n");
15481×
        assert_eq!(m.live_atoms(), vec![(h(1), 1), (h(2), 0), (h(1), 2)]);
15491×
    }
1550
1551
    #[test]
15521×
    fn concurrent_inserts_at_same_anchor_conflict() {
15531×
        let mut g = FileGraph::new();
15541×
        g.insert(h(1), 0, Vertex::Start, Vertex::End, &lines(&["a\n", "b\n"]));
15551×
        g.insert(
15561×
            h(2),
1557
            0,
15581×
            Vertex::Atom((h(1), 0)),
15591×
            Vertex::Atom((h(1), 1)),
15601×
            &lines(&["from-2\n"]),
1561
        );
15621×
        g.insert(
15631×
            h(3),
1564
            0,
15651×
            Vertex::Atom((h(1), 0)),
15661×
            Vertex::Atom((h(1), 1)),
15671×
            &lines(&["from-3\n", "more-3\n"]),
1568
        );
15691×
        let deps = Deps(
15701×
            [(h(2), vec![h(1)]), (h(3), vec![h(1)])]
15711×
                .into_iter()
15721×
                .collect(),
15731×
        );
15741×
        let m = g.materialize(&deps);
15751×
        assert!(m.is_conflicted());
15761×
        assert_eq!(m.conflict_count(), 1);
15771×
        assert_eq!(
1578
            m.segments,
15791×
            vec![
15801×
                Segment::Lines(vec![(h(1), 0)]),
15811×
                Segment::Conflict(vec![vec![(h(2), 0)], vec![(h(3), 0), (h(3), 1)]]),
15821×
                Segment::Lines(vec![(h(1), 1)]),
1583
            ]
1584
        );
15851×
        let t = text(&g, &m);
15861×
        assert!(t.starts_with("a\n<<<<<<< oxy conflict 1 of 1, side 1 of 2: change 0202\nfrom-2\n======= oxy conflict 1 of 1, side 2 of 2: change 0303\nfrom-3\nmore-3\n>>>>>>> oxy conflict 1 of 1 end\nb\n"), "{t}");
15871×
    }
1588
1589
    #[test]
15901×
    fn concurrent_inserts_at_different_anchors_do_not_conflict() {
15911×
        let mut g = FileGraph::new();
15921×
        g.insert(
15931×
            h(1),
1594
            0,
15951×
            Vertex::Start,
15961×
            Vertex::End,
15971×
            &lines(&["a\n", "b\n", "c\n"]),
1598
        );
15991×
        g.insert(
16001×
            h(2),
1601
            0,
16021×
            Vertex::Start,
16031×
            Vertex::Atom((h(1), 0)),
16041×
            &lines(&["top\n"]),
1605
        );
16061×
        g.insert(
16071×
            h(3),
1608
            0,
16091×
            Vertex::Atom((h(1), 2)),
16101×
            Vertex::End,
16111×
            &lines(&["bottom\n"]),
1612
        );
16131×
        let deps = Deps(
16141×
            [(h(2), vec![h(1)]), (h(3), vec![h(1)])]
16151×
                .into_iter()
16161×
                .collect(),
16171×
        );
16181×
        let m = g.materialize(&deps);
16191×
        assert!(!m.is_conflicted());
16201×
        assert_eq!(text(&g, &m), "top\na\nb\nc\nbottom\n");
16211×
    }
1622
1623
    #[test]
16241×
    fn concurrent_deletes_of_the_same_line_agree() {
16251×
        let mut g = FileGraph::new();
16261×
        g.insert(h(1), 0, Vertex::Start, Vertex::End, &lines(&["a\n", "b\n"]));
16271×
        g.delete(
16281×
            h(2),
16291×
            &AtomRange {
16301×
                change: h(1),
16311×
                from: 0,
16321×
                to: 1,
16331×
            },
1634
        );
16351×
        g.delete(
16361×
            h(3),
16371×
            &AtomRange {
16381×
                change: h(1),
16391×
                from: 0,
16401×
                to: 1,
16411×
            },
1642
        );
16431×
        let deps = Deps(
16441×
            [(h(2), vec![h(1)]), (h(3), vec![h(1)])]
16451×
                .into_iter()
16461×
                .collect(),
16471×
        );
16481×
        let m = g.materialize(&deps);
16491×
        assert!(!m.is_conflicted());
16501×
        assert_eq!(text(&g, &m), "b\n");
16511×
    }
1652
1653
    #[test]
16541×
    fn delete_insert_conflict_is_a_zombie() {
16551×
        let mut g = FileGraph::new();
16561×
        g.insert(h(1), 0, Vertex::Start, Vertex::End, &lines(&["a\n", "b\n"]));
1657
        // 2 deletes a; 3 (concurrent) inserts after a.
16581×
        g.delete(
16591×
            h(2),
16601×
            &AtomRange {
16611×
                change: h(1),
16621×
                from: 0,
16631×
                to: 1,
16641×
            },
1665
        );
16661×
        g.insert(
16671×
            h(3),
1668
            0,
16691×
            Vertex::Atom((h(1), 0)),
16701×
            Vertex::Atom((h(1), 1)),
16711×
            &lines(&["after-a\n"]),
1672
        );
16731×
        let deps = Deps(
16741×
            [(h(2), vec![h(1)]), (h(3), vec![h(1)])]
16751×
                .into_iter()
16761×
                .collect(),
16771×
        );
16781×
        let m = g.materialize(&deps);
16791×
        assert!(m.is_conflicted());
16801×
        assert_eq!(
1681
            m.segments,
16821×
            vec![
16831×
                Segment::Zombie {
16841×
                    deleted: vec![(h(1), 0)],
16851×
                    inserted: vec![(h(3), 0)]
16861×
                },
16871×
                Segment::Lines(vec![(h(1), 1)]),
1688
            ]
1689
        );
16901×
        let t = text(&g, &m);
16911×
        assert!(t.contains("-------\na\n======="), "{t}");
16921×
        assert!(t.contains("after-a\n>>>>>>>"), "{t}");
1693
1694
        // If the deleter saw the insert (depends on 3), there is no conflict.
16951×
        let deps = Deps(
16961×
            [(h(2), vec![h(1), h(3)]), (h(3), vec![h(1)])]
16971×
                .into_iter()
16981×
                .collect(),
16991×
        );
17001×
        let m = g.materialize(&deps);
17011×
        assert!(!m.is_conflicted());
17021×
        assert_eq!(text(&g, &m), "after-a\nb\n");
17031×
    }
1704
1705
    #[test]
17061×
    fn insert_after_a_line_deleted_by_a_dependency_is_not_a_conflict() {
1707
        // 1 inserts a,b; 2 deletes b (depends on 1); 3 depends on 2 yet anchors
1708
        // after the dead b (a rewritten change may do this): no conflict.
17091×
        let mut g = FileGraph::new();
17101×
        g.insert(h(1), 0, Vertex::Start, Vertex::End, &lines(&["a\n", "b\n"]));
17111×
        g.delete(
17121×
            h(2),
17131×
            &AtomRange {
17141×
                change: h(1),
17151×
                from: 1,
17161×
                to: 2,
17171×
            },
1718
        );
17191×
        g.insert(
17201×
            h(3),
1721
            0,
17221×
            Vertex::Atom((h(1), 1)),
17231×
            Vertex::End,
17241×
            &lines(&["c\n"]),
1725
        );
17261×
        let deps = Deps(
17271×
            [(h(2), vec![h(1)]), (h(3), vec![h(2)])]
17281×
                .into_iter()
17291×
                .collect(),
17301×
        );
17311×
        let m = g.materialize(&deps);
17321×
        assert!(!m.is_conflicted(), "{:?}", m.segments);
17331×
        assert_eq!(text(&g, &m), "a\nc\n");
1734
        // A change that deletes a line it introduced itself, with a dependent
1735
        // anchoring after it, is likewise fine.
17361×
        let mut g = FileGraph::new();
17371×
        g.insert(h(1), 0, Vertex::Start, Vertex::End, &lines(&["x\n"]));
17381×
        g.delete(
17391×
            h(1),
17401×
            &AtomRange {
17411×
                change: h(1),
17421×
                from: 0,
17431×
                to: 1,
17441×
            },
1745
        );
17461×
        g.insert(
17471×
            h(2),
1748
            0,
17491×
            Vertex::Atom((h(1), 0)),
17501×
            Vertex::End,
17511×
            &lines(&["y\n"]),
1752
        );
17531×
        let deps = Deps([(h(2), vec![h(1)])].into_iter().collect());
17541×
        let m = g.materialize(&deps);
17551×
        assert!(!m.is_conflicted());
17561×
        assert_eq!(text(&g, &m), "y\n");
17571×
    }
1758
1759
    #[test]
17601×
    fn resolution_collapses_a_conflict() {
17611×
        let mut g = FileGraph::new();
17621×
        g.insert(h(1), 0, Vertex::Start, Vertex::End, &lines(&["a\n"]));
17631×
        g.insert(
17641×
            h(2),
1765
            0,
17661×
            Vertex::Start,
17671×
            Vertex::Atom((h(1), 0)),
17681×
            &lines(&["x\n"]),
1769
        );
17701×
        g.insert(
17711×
            h(3),
1772
            0,
17731×
            Vertex::Start,
17741×
            Vertex::Atom((h(1), 0)),
17751×
            &lines(&["y\n"]),
1776
        );
17771×
        let mut deps: HashMap<_, _> = [(h(2), vec![h(1)]), (h(3), vec![h(1)])]
17781×
            .into_iter()
17791×
            .collect();
17801×
        assert!(g.materialize(&Deps(deps.clone())).is_conflicted());
1781
        // Resolution keeps y, drops x.
17821×
        g.delete(
17831×
            h(4),
17841×
            &AtomRange {
17851×
                change: h(2),
17861×
                from: 0,
17871×
                to: 1,
17881×
            },
1789
        );
17901×
        deps.insert(h(4), vec![h(2), h(3)]);
17911×
        let m = g.materialize(&Deps(deps));
17921×
        assert!(!m.is_conflicted());
17931×
        assert_eq!(text(&g, &m), "y\na\n");
17941×
    }
1795
1796
    #[test]
17971×
    fn empty_and_unterminated_files() {
17981×
        let g = FileGraph::new();
17991×
        let m = g.materialize(&NoDeps);
18001×
        assert_eq!(m.segments, vec![]);
18011×
        assert_eq!(text(&g, &m), "");
18021×
        let mut g = FileGraph::new();
18031×
        g.insert(h(1), 0, Vertex::Start, Vertex::End, &lines(&["no newline"]));
18041×
        assert_eq!(text(&g, &g.materialize(&NoDeps)), "no newline");
18051×
    }
1806
1807
    #[test]
18081×
    fn serialization_round_trip() {
18091×
        let mut g = FileGraph::new();
18101×
        g.insert(h(1), 0, Vertex::Start, Vertex::End, &lines(&["a\n", "b\n"]));
18111×
        g.insert(
18121×
            h(2),
1813
            0,
18141×
            Vertex::Atom((h(1), 0)),
18151×
            Vertex::Atom((h(1), 1)),
18161×
            &lines(&["x\n"]),
1817
        );
18181×
        g.delete(
18191×
            h(3),
18201×
            &AtomRange {
18211×
                change: h(1),
18221×
                from: 1,
18231×
                to: 2,
18241×
            },
1825
        );
18261×
        let v = g.to_value();
18271×
        let bytes = crate::cbor::encode(&v);
18281×
        let back = FileGraph::from_value(&crate::cbor::decode(&bytes).unwrap()).unwrap();
18291×
        let deps = Deps(
18301×
            [(h(2), vec![h(1)]), (h(3), vec![h(1)])]
18311×
                .into_iter()
18321×
                .collect(),
18331×
        );
18341×
        assert_eq!(back.materialize(&deps), g.materialize(&deps));
18351×
        assert_eq!(text(&back, &back.materialize(&deps)), "a\nx\n");
18361×
        assert_eq!(
18371×
            crate::cbor::encode(&back.to_value()),
1838
            bytes,
1839
            "deterministic"
1840
        );
18411×
    }
1842
1843
    /// Spec §7.3: the graph is a function of the set of changes, not their order.
1844
    #[test]
18451×
    fn application_order_is_irrelevant() {
1846
        use rand::seq::SliceRandom;
1847
        type Op = (
1848
            ChangeHash,
1849
            Vec<(u32, Vertex, Vertex, Lines)>,
1850
            Vec<AtomRange>,
1851
        );
18521×
        let ops: Vec<Op> = vec![
18531×
            (
18541×
                h(1),
18551×
                vec![(0, Vertex::Start, Vertex::End, lines(&["a\n", "b\n", "c\n"]))],
18561×
                vec![],
18571×
            ),
18581×
            (
18591×
                h(2),
18601×
                vec![(
18611×
                    0,
18621×
                    Vertex::Atom((h(1), 0)),
18631×
                    Vertex::Atom((h(1), 1)),
18641×
                    lines(&["p\n"]),
18651×
                )],
18661×
                vec![],
18671×
            ),
18681×
            (
18691×
                h(3),
18701×
                vec![(
18711×
                    0,
18721×
                    Vertex::Atom((h(1), 0)),
18731×
                    Vertex::Atom((h(1), 1)),
18741×
                    lines(&["q\n", "r\n"]),
18751×
                )],
18761×
                vec![AtomRange {
18771×
                    change: h(1),
18781×
                    from: 2,
18791×
                    to: 3,
18801×
                }],
18811×
            ),
18821×
            (
18831×
                h(4),
18841×
                vec![(
18851×
                    0,
18861×
                    Vertex::Atom((h(3), 1)),
18871×
                    Vertex::Atom((h(1), 1)),
18881×
                    lines(&["s\n"]),
18891×
                )],
18901×
                vec![AtomRange {
18911×
                    change: h(1),
18921×
                    from: 1,
18931×
                    to: 2,
18941×
                }],
18951×
            ),
18961×
            (
18971×
                h(5),
18981×
                vec![(0, Vertex::Atom((h(1), 2)), Vertex::End, lines(&["z\n"]))],
18991×
                vec![],
19001×
            ),
1901
        ];
19021×
        let deps = Deps(
19031×
            [
19041×
                (h(2), vec![h(1)]),
19051×
                (h(3), vec![h(1)]),
19061×
                (h(4), vec![h(3), h(1)]),
19071×
                (h(5), vec![h(1)]),
19081×
            ]
19091×
            .into_iter()
19101×
            .collect(),
19111×
        );
191251×
        let build = |order: &[usize]| {
191351×
            let mut g = FileGraph::new();
1914255×
            for &i in order {
1915255×
                let (c, ins, dels) = &ops[i];
1916255×
                for (idx, a, b, l) in ins {
1917255×
                    g.insert(*c, *idx, *a, *b, l);
1918255×
                }
1919255×
                for d in dels {
1920102×
                    g.delete(*c, d);
1921102×
                }
1922
            }
192351×
            let m = g.materialize(&deps);
192451×
            (m.clone(), text(&g, &m))
192551×
        };
19261×
        let reference = build(&[0, 1, 2, 3, 4]);
19271×
        assert!(reference.0.is_conflicted());
19281×
        let mut rng = rand::thread_rng();
19291×
        let mut order: Vec<usize> = (0..ops.len()).collect();
19301×
        for _ in 0..50 {
193150×
            order.shuffle(&mut rng);
193250×
            assert_eq!(build(&order), reference, "order {order:?}");
1933
        }
19341×
    }
1935
}