OXYGENHUB

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

1446 of 1494 lines run, 212 of 236 functions · run #411 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<'_> {
384943×
    fn depends_on(&self, a: &ChangeHash, b: &ChangeHash) -> bool {
394943×
        if let Some(v) = self.known.borrow().get(&(*a, *b)) {
402483×
            return *v;
412460×
        }
422460×
        let v = self.inner.depends_on(a, b);
432460×
        self.known.borrow_mut().insert((*a, *b), v);
442460×
        v
454943×
    }
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 {
9430917×
    fn get(&self) -> Option<std::sync::Arc<Order>> {
9530917×
        self.0.lock().unwrap_or_else(|e| e.into_inner()).clone()
9630917×
    }
971820×
    fn set(&self, o: Option<std::sync::Arc<Order>>) {
981820×
        *self.0.lock().unwrap_or_else(|e| e.into_inner()) = o;
991820×
    }
10075103×
    fn take(&mut self) -> Option<std::sync::Arc<Order>> {
10175103×
        self.0.get_mut().unwrap_or_else(|e| e.into_inner()).take()
10275103×
    }
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 {
1121810×
    fn known(atoms: Vec<AtomKey>) -> Order {
1131810×
        Order {
1141810×
            atoms,
1151810×
            unchecked: Vec::new(),
1161810×
            confirmed: std::sync::atomic::AtomicBool::new(true),
1171810×
        }
1181810×
    }
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.
125535×
    fn splice(
126535×
        &self,
127535×
        h: ChangeHash,
128535×
        inserts: &[(Vertex, Vertex, u32, u32)],
129535×
        deleted: &[AtomKey],
130535×
    ) -> Option<std::sync::Arc<Order>> {
131535×
        let mut want: HashSet<AtomKey> = deleted.iter().copied().collect();
132579×
        for (a, b, _, _) in inserts {
1331158×
            for v in [a, b] {
1341158×
                if let Vertex::Atom(k) = v {
135947×
                    want.insert(*k);
136947×
                }
137
            }
138
        }
139535×
        let mut pos: HashMap<AtomKey, usize> = HashMap::default();
1402865×
        for (i, k) in self.atoms.iter().enumerate() {
1412865×
            if want.contains(k) {
1421294×
                pos.insert(*k, i);
1431571×
            }
144
        }
145535×
        let len = self.atoms.len();
146535×
        let mut gone = vec![false; len];
147535×
        let mut unchecked = if self.confirmed.load(std::sync::atomic::Ordering::Relaxed) {
148535×
            Vec::new()
149
        } else {
1500×
            self.unchecked.clone()
151
        };
152740×
        for k in deleted {
153740×
            if k.0 == h {
1540×
                return None;
155740×
            }
156740×
            if let Some(&i) = pos.get(k) {
157717×
                if !gone[i] {
158717×
                    gone[i] = true;
159717×
                    unchecked.push(*k);
160717×
                }
16123×
            }
162
        }
163
        // Each run goes in the gap its anchors leave (slot `i`: before
164
        // `atoms[i]`), which must hold nothing that stays.
165535×
        let mut slots: Vec<(usize, usize, u32, u32)> = Vec::with_capacity(inserts.len());
166560×
        for &(a, b, first, count) in inserts {
167560×
            let from = match a {
168143×
                Vertex::Start => 0,
169417×
                Vertex::Atom(k) => pos.get(&k)? + 1,
1700×
                Vertex::End => return None,
171
            };
172549×
            let to = match b {
17364×
                Vertex::End => len,
174485×
                Vertex::Atom(k) => *pos.get(&k)?,
1750×
                Vertex::Start => return None,
176
            };
177542×
            if from > to || gone[from..to].iter().any(|g| !g) {
1785×
                return None;
179537×
            }
180537×
            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.
184512×
        slots.sort_unstable();
185512×
        for w in slots.windows(2) {
186159×
            let (end, next) = (w[0].1, w[1].0);
187302×
            if end >= next || !gone[end..next].iter().any(|g| !g) {
1880×
                return None;
189159×
            }
190
        }
191536×
        let added: usize = slots.iter().map(|s| s.3 as usize).sum();
192512×
        let mut atoms = Vec::with_capacity(len + added);
193512×
        let mut slots = slots.into_iter().peekable();
1943165×
        let mut runs_at = |i: usize, atoms: &mut Vec<AtomKey>| {
1953701×
            while let Some(&(from, _, first, count)) = slots.peek() {
1961790×
                if from != i {
1971254×
                    break;
198536×
                }
199783×
                atoms.extend((first..first + count).map(|j| (h, j)));
200536×
                slots.next();
201
            }
2023165×
        };
2032653×
        for (i, (k, g)) in self.atoms.iter().zip(&gone).enumerate() {
2042653×
            runs_at(i, &mut atoms);
2052653×
            if !g {
2061973×
                atoms.push(*k);
2071973×
            }
208
        }
209512×
        runs_at(len, &mut atoms);
210512×
        let confirmed = unchecked.is_empty();
211512×
        Some(std::sync::Arc::new(Order {
212512×
            atoms,
213512×
            unchecked,
214512×
            confirmed: std::sync::atomic::AtomicBool::new(confirmed),
215512×
        }))
216535×
    }
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 {
230246550×
    fn insert(&mut self, v: Vertex) {
23135811×
        match self {
232208409×
            Edges::None => *self = Edges::One(v),
23335811×
            Edges::One(a) if *a == v => {}
23435811×
            Edges::One(a) => {
23535811×
                let a = *a;
23635811×
                *self = Edges::Many(if a < v { vec![a, v] } else { vec![v, a] });
237
            }
2382330×
            Edges::Many(list) => {
2392330×
                if let Err(i) = list.binary_search(&v) {
2402330×
                    list.insert(i, v);
2412330×
                }
242
            }
243
        }
244246550×
    }
245
246957891×
    fn as_slice(&self) -> &[Vertex] {
247957891×
        match self {
2485045×
            Edges::None => &[],
249697776×
            Edges::One(v) => std::slice::from_ref(v),
250255070×
            Edges::Many(list) => list,
251
        }
252957891×
    }
253
254693737×
    fn iter(&self) -> std::slice::Iter<'_, Vertex> {
255693737×
        self.as_slice().iter()
256693737×
    }
257
}
258
259
impl Default for FileGraph {
26029562×
    fn default() -> Self {
26129562×
        Self::new()
26229562×
    }
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 {
28550688×
    pub fn is_conflicted(&self) -> bool {
28650688×
        self.segments
28750688×
            .iter()
28850688×
            .any(|s| !matches!(s, Segment::Lines(_)))
28950688×
    }
29028974×
    pub fn conflict_count(&self) -> usize {
29128974×
        self.segments
29228974×
            .iter()
29329813×
            .filter(|s| !matches!(s, Segment::Lines(_)))
29428974×
            .count()
29528974×
    }
296
    /// Every live atom in materialized order, conflict sides concatenated.
2971370×
    pub fn live_atoms(&self) -> Vec<AtomKey> {
2981370×
        let mut out = Vec::new();
2991404×
        for s in &self.segments {
3001404×
            match s {
3011360×
                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
        }
3061370×
        out
3071370×
    }
308
}
309
310
impl FileGraph {
31129632×
    pub fn new() -> Self {
31229632×
        let mut g = FileGraph {
31329632×
            atoms: HashMap::default(),
31429632×
            succ: HashMap::default(),
31529632×
            order: OrderSlot::default(),
31629632×
        };
31729632×
        g.edge(Vertex::Start, Vertex::End);
31829632×
        g
31929632×
    }
320
32134814×
    fn edge(&mut self, a: Vertex, b: Vertex) {
32234814×
        self.succ.entry(a).or_default().insert(b);
32334814×
        self.succ.entry(b).or_default();
32434814×
    }
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.
34137424×
    pub fn insert_owned(
34237424×
        &mut self,
34337424×
        change: ChangeHash,
34437424×
        first_index: u32,
34537424×
        after: Vertex,
34637424×
        before: Vertex,
34737424×
        lines: Lines,
34837424×
    ) {
34937424×
        self.order.take();
35037424×
        self.atoms.reserve(lines.len());
35137424×
        self.succ.reserve(lines.len() + 1);
35237424×
        let mut prev = after;
353174312×
        for i in 0..lines.len() {
354174312×
            let key = (change, first_index + i as u32);
355174312×
            self.atoms.entry(key).or_default().content =
356174312×
                Some(LineRef::new(lines.clone(), i as u32));
357174312×
            let v = Vertex::Atom(key);
358174312×
            self.succ.entry(prev).or_default().insert(v);
359174312×
            prev = v;
360174312×
        }
36137424×
        self.succ.entry(prev).or_default().insert(before);
36237424×
        self.succ.entry(before).or_default();
36337424×
    }
364
365
    /// Apply a `Delete` of `range` by change `by`.
3666244×
    pub fn delete(&mut self, by: ChangeHash, range: &AtomRange) {
3676244×
        self.order.take();
3686559×
        for i in range.from..range.to {
3696559×
            self.atoms
3706559×
                .entry((range.change, i))
3716559×
                .or_default()
3726559×
                .deleted_by
3736559×
                .insert(by);
3746559×
        }
3756244×
    }
376
377470992×
    pub fn is_live(&self, k: &AtomKey) -> bool {
378470992×
        self.atoms
379470992×
            .get(k)
380470992×
            .is_some_and(|a| a.content.is_some() && a.deleted_by.is_empty())
381470992×
    }
382
383159791×
    pub fn content(&self, k: &AtomKey) -> Option<&[u8]> {
384159791×
        self.atoms
385159791×
            .get(k)
386159791×
            .and_then(|a| a.content.as_ref().map(LineRef::bytes))
387159791×
    }
388
389277×
    pub fn deleters(&self, k: &AtomKey) -> impl Iterator<Item = &ChangeHash> {
390277×
        self.atoms
391277×
            .get(k)
392277×
            .into_iter()
393277×
            .flat_map(|a| a.deleted_by.iter())
394277×
    }
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.
4039×
    pub fn adjacent_insertion(&self, m: &Materialized, i: usize, deps: &dyn DepOracle) -> bool {
4049×
        let Some(Segment::Conflict(sides)) = m.segments.get(i) else {
4050×
            return false;
406
        };
4079×
        let before = match i.checked_sub(1).map(|j| &m.segments[j]) {
4080×
            None => Vertex::Start,
4099×
            Some(Segment::Lines(a)) => match a.last() {
4109×
                Some(k) => Vertex::Atom(*k),
4110×
                None => return false,
412
            },
4130×
            Some(_) => return false,
414
        };
4159×
        let on_side: HashSet<AtomKey> = sides.iter().flatten().copied().collect();
4169×
        let side_changes: Vec<BTreeSet<ChangeHash>> = sides
4179×
            .iter()
41818×
            .map(|s| s.iter().map(|a| a.0).collect())
4199×
            .collect();
4209×
        let shared = |d: &ChangeHash| {
4213×
            side_changes
4223×
                .iter()
4235×
                .all(|s| s.iter().any(|c| deps.depends_on(c, d)))
4243×
        };
425
        // From the line before, through the sides' lines and deleted ones,
426
        // up to the next live line.
4279×
        let mut seen: HashSet<AtomKey> = HashSet::default();
4289×
        let mut todo = vec![before];
42927×
        while let Some(v) = todo.pop() {
43033×
            for &w in self.succ.get(&v).map(Edges::as_slice).unwrap_or(&[]) {
43133×
                let Vertex::Atom(k) = w else { continue };
43233×
                if !seen.insert(k) {
43312×
                    continue;
43421×
                }
43521×
                if !on_side.contains(&k) {
4369×
                    if self.is_live(&k) {
4376×
                        continue;
4383×
                    }
4393×
                    if self.deleters(&k).any(|d| !shared(d)) {
4403×
                        return false;
4410×
                    }
44212×
                }
44312×
                todo.push(w);
444
            }
445
        }
4466×
        true
4479×
    }
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
5181262×
    pub fn live_successor_changes(&self, k: &AtomKey) -> Vec<ChangeHash> {
5191262×
        self.succ
5201262×
            .get(&Vertex::Atom(*k))
5211262×
            .map(|ss| {
5221261×
                ss.iter()
5231261×
                    .filter_map(|s| match s {
524964×
                        Vertex::Atom(y) if self.is_live(y) => Some(y.0),
525458×
                        _ => None,
5261310×
                    })
5271261×
                    .collect()
5281261×
            })
5291262×
            .unwrap_or_default()
5301262×
    }
531
532356613×
    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.
537356613×
        self.succ.get(&Vertex::Atom(*k)).is_some_and(|ss| {
538469169×
            ss.iter().any(|s| match s {
539469169×
                Vertex::Atom(y) if self.is_live(y) => !info
5404814×
                    .deleted_by
5414814×
                    .iter()
5424942×
                    .any(|d| deps.depends_on(d, &y.0) || deps.depends_on(&y.0, d)),
543494295×
                _ => false,
544499109×
            })
545356613×
        })
546356613×
    }
547
548
    /// Successors of `v` in the graph with non-kept vertices contracted away.
54910401×
    fn reduced_succ(
55010401×
        &self,
55110401×
        v: Vertex,
55210401×
        kept: &HashSet<Vertex>,
55310401×
        memo: &mut HashMap<Vertex, BTreeSet<Vertex>>,
55410401×
    ) -> BTreeSet<Vertex> {
55510401×
        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.
55811151×
        if direct.iter().all(|s| kept.contains(s)) {
5596288×
            return direct.iter().copied().collect();
5604113×
        }
5614113×
        let mut out = BTreeSet::new();
5624113×
        let mut stack: Vec<Vertex> = direct.to_vec();
5634113×
        let mut seen = HashSet::default();
564503517×
        while let Some(s) = stack.pop() {
565499404×
            if kept.contains(&s) {
56634452×
                out.insert(s);
567464952×
            } else if seen.insert(s) {
568319898×
                if let Some(m) = memo.get(&s) {
5690×
                    out.extend(m.iter().copied());
570319898×
                } else if let Some(next) = self.succ.get(&s) {
571319898×
                    stack.extend(next.iter().copied());
572319898×
                }
573145054×
            }
574
        }
5754113×
        out
57610401×
    }
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.
58329176×
    fn as_chain(&self) -> Option<Vec<AtomKey>> {
58429176×
        if self
58529176×
            .atoms
58629176×
            .values()
587112057×
            .any(|a| a.content.is_none() || !a.deleted_by.is_empty())
588
        {
5892188×
            return None;
59026988×
        }
59126988×
        let mut order = Vec::with_capacity(self.atoms.len());
59226988×
        let mut v = Vertex::Start;
593
        loop {
594130912×
            let succ = self.succ.get(&v)?.as_slice();
595159611×
            let mut atoms = succ.iter().filter(|s| **s != Vertex::End);
596130912×
            match (atoms.next(), atoms.next()) {
59726586×
                (None, _) if succ.contains(&Vertex::End) => break,
598103924×
                (Some(Vertex::Atom(k)), None) if order.len() < self.atoms.len() => {
599103924×
                    order.push(*k);
600103924×
                    v = Vertex::Atom(*k);
601103924×
                }
602402×
                _ => return None,
603
            }
604
        }
60526586×
        (order.len() == self.atoms.len()).then_some(order)
60629176×
    }
607
608
    /// Order the live atoms and locate conflicts.
60930452×
    pub fn materialize(&self, deps: &dyn DepOracle) -> Materialized {
61030452×
        let deps = &MemoDeps {
61130452×
            inner: deps,
61230452×
            known: Default::default(),
61330452×
        };
61430452×
        let lines = |order: Vec<AtomKey>| Materialized {
61529676×
            segments: if order.is_empty() {
616163×
                vec![]
617
            } else {
61829513×
                vec![Segment::Lines(order)]
619
            },
62029676×
        };
621
        use std::sync::atomic::Ordering::Relaxed;
622
        // Which way it went, and how long it took (`OXY_TIMINGS`).
62330452×
        let started = crate::timing::enabled().then(std::time::Instant::now);
62430452×
        let took = |name: &'static str| {
62530452×
            if let Some(t) = started {
6260×
                crate::timing::add(name, t.elapsed());
62730452×
            }
62830452×
        };
62930452×
        if let Some(o) = self.order.get() {
6301292×
            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×
                });
6361292×
            if holds {
6371282×
                o.confirmed.store(true, Relaxed);
6381282×
                took("graph: kept order");
6391282×
                return lines(o.atoms.clone());
64010×
            }
64110×
            self.order.set(None);
64229160×
        }
643
        // A chain (nothing ever deleted) is quick to walk, and a fresh tree
644
        // is all chains: no order is kept for one.
64529170×
        if let Some(order) = self.as_chain() {
64626584×
            took("graph: chain");
64726584×
            return lines(order);
6482586×
        }
6492586×
        if let Some(order) = self.as_order(deps) {
6501810×
            self.order
6511810×
                .set(Some(std::sync::Arc::new(Order::known(order.clone()))));
6521810×
            took("graph: single order");
6531810×
            return lines(order);
654776×
        }
655776×
        let m = self.materialize_general(deps);
656776×
        took("graph: general");
657776×
        m
65830452×
    }
659
660
    /// Take the kept order, to [`Order::splice`] it once a change's edits
661
    /// have applied (they drop it).
66231435×
    pub fn take_order(&mut self) -> Option<std::sync::Arc<Order>> {
66331435×
        self.order.take()
66431435×
    }
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.
670536×
    pub fn keep_spliced(
671536×
        &mut self,
672536×
        order: std::sync::Arc<Order>,
673536×
        h: ChangeHash,
674536×
        inserts: &[(Vertex, Vertex, u32, u32)],
675536×
        deleted: &[AtomKey],
676536×
    ) {
677536×
        let live = inserts
678536×
            .iter()
679850×
            .all(|&(_, _, first, count)| (first..first + count).all(|i| self.is_live(&(h, i))));
680536×
        let spliced = if live {
681535×
            order.splice(h, inserts, deleted)
682
        } else {
6831×
            None
684
        };
685536×
        *self.order.0.get_mut().unwrap_or_else(|e| e.into_inner()) = spliced;
686536×
    }
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.
6942588×
    fn as_order(&self, deps: &dyn DepOracle) -> Option<Vec<AtomKey>> {
695
        // Kept vertices by dense index: Start, End, then the live atoms.
6962588×
        let mut index: HashMap<Vertex, u32> =
6972588×
            HashMap::with_capacity_and_hasher(self.atoms.len() + 2, Default::default());
6982588×
        let mut verts: Vec<Vertex> = Vec::with_capacity(self.atoms.len() + 2);
6992588×
        verts.extend([Vertex::Start, Vertex::End]);
7002588×
        index.insert(Vertex::Start, 0);
7012588×
        index.insert(Vertex::End, 1);
70299564×
        for (k, info) in &self.atoms {
70399564×
            if info.content.is_none() {
7040×
                continue;
70599564×
            }
70699564×
            if info.deleted_by.is_empty() {
70751539×
                index.insert(Vertex::Atom(*k), verts.len() as u32);
70851539×
                verts.push(Vertex::Atom(*k));
70951539×
            } else if self.is_ghost(k, info, deps) {
710350×
                return None;
71147675×
            }
712
        }
713
        // Each kept vertex's successors, contracting the others: what a
714
        // contracted vertex reaches is worked out once (post-order).
7152238×
        let mut reach: HashMap<Vertex, Vec<u32>> = HashMap::default();
71611111×
        let contracted = |v: Vertex, reach: &mut HashMap<Vertex, Vec<u32>>| {
71711111×
            let mut stack: Vec<(Vertex, bool)> = vec![(v, false)];
71888844×
            while let Some((x, done)) = stack.pop() {
71977733×
                if reach.contains_key(&x) {
72010169×
                    continue;
72167564×
                }
72267564×
                let next = self.succ.get(&x).map(Edges::as_slice).unwrap_or_default();
72367564×
                if !done {
72433782×
                    stack.push((x, true));
72545722×
                    for s in next {
72645722×
                        if !index.contains_key(s) && !reach.contains_key(s) {
72732840×
                            stack.push((*s, false));
72832840×
                        }
729
                    }
73033782×
                    continue;
73133782×
                }
73233782×
                let mut out: Vec<u32> = Vec::new();
73345722×
                for s in next {
73445722×
                    match index.get(s) {
7355605×
                        Some(i) => out.push(*i),
73640117×
                        None => out.extend(reach.get(s).into_iter().flatten()),
737
                    }
738
                }
73933782×
                out.sort_unstable();
74033782×
                out.dedup();
74133782×
                reach.insert(x, out);
742
            }
74311111×
        };
744
        // Successors of vertex `i`: `succ[starts[i]..starts[i + 1]]`.
7452238×
        let mut succ: Vec<u32> = Vec::with_capacity(verts.len() * 2);
7462238×
        let mut starts: Vec<usize> = Vec::with_capacity(verts.len() + 1);
7472238×
        let mut indeg: Vec<u32> = vec![0; verts.len()];
74855235×
        for v in &verts {
74955235×
            let from = succ.len();
75055235×
            starts.push(from);
75164938×
            for s in self.succ.get(v).map(Edges::as_slice).unwrap_or_default() {
75264938×
                match index.get(s) {
75353827×
                    Some(i) => succ.push(*i),
75411111×
                    None => {
75511111×
                        contracted(*s, &mut reach);
75611111×
                        succ.extend(reach.get(s).into_iter().flatten());
75711111×
                    }
758
                }
759
            }
76055235×
            if succ.len() - from > 1 {
7616036×
                succ[from..].sort_unstable();
7626036×
                let mut kept = from;
76318169×
                for i in from..succ.len() {
76418169×
                    if i == from || succ[i] != succ[kept - 1] {
76512975×
                        succ[kept] = succ[i];
76612975×
                        kept += 1;
76712975×
                    }
768
                }
7696036×
                succ.truncate(kept);
77049199×
            }
77159936×
            for &w in &succ[from..] {
77259936×
                indeg[w as usize] += 1;
77359936×
            }
774
        }
7752238×
        starts.push(succ.len());
776
        // Kahn's algorithm, giving up where two vertices are ready at once.
7772238×
        let mut ready: Vec<u32> = (0..verts.len() as u32)
77855235×
            .filter(|&i| indeg[i as usize] == 0)
7792238×
            .collect();
7802238×
        let mut order: Vec<AtomKey> = Vec::with_capacity(verts.len());
7812238×
        let mut seen = 0;
78255288×
        while let Some(v) = ready.pop() {
78353477×
            if !ready.is_empty() {
7840×
                return None;
78553477×
            }
78653477×
            seen += 1;
78753477×
            if let Vertex::Atom(k) = verts[v as usize] {
78849428×
                order.push(k);
78949428×
            }
79058460×
            for &w in &succ[starts[v as usize]..starts[v as usize + 1]] {
79158460×
                indeg[w as usize] -= 1;
79258460×
                if indeg[w as usize] == 0 {
79352093×
                    ready.push(w);
79452093×
                }
795
            }
79653477×
            if ready.len() > 1 {
797427×
                return None;
79853050×
            }
799
        }
8001811×
        (seen == verts.len()).then_some(order)
8012588×
    }
802
803
    /// [`FileGraph::materialize`] for any graph: contraction, then a
804
    /// topological order with conflict regions.
8051270×
    fn materialize_general(&self, deps: &dyn DepOracle) -> Materialized {
806
        // 1. Vertices that survive contraction: live atoms, ghosts, Start, End.
8071270×
        let mut kept: HashSet<Vertex> = HashSet::default();
8081270×
        let mut ghosts: HashSet<AtomKey> = HashSet::default();
8091270×
        kept.insert(Vertex::Start);
8101270×
        kept.insert(Vertex::End);
811315353×
        for (k, info) in &self.atoms {
812315353×
            if info.content.is_none() {
8130×
                continue;
814315353×
            }
815315353×
            if info.deleted_by.is_empty() {
8167381×
                kept.insert(Vertex::Atom(*k));
817307972×
            } else if self.is_ghost(k, info, deps) {
818480×
                kept.insert(Vertex::Atom(*k));
819480×
                ghosts.insert(*k);
820307492×
            }
821
        }
822
823
        // 2. Reduced graph over kept vertices.
8241270×
        let mut memo = HashMap::default();
8251270×
        let mut rsucc: HashMap<Vertex, BTreeSet<Vertex>> = HashMap::default();
8261270×
        let mut indeg: HashMap<Vertex, usize> = HashMap::default();
82710401×
        for &u in &kept {
82810401×
            indeg.entry(u).or_insert(0);
82910401×
            let rs = self.reduced_succ(u, &kept, &mut memo);
83015620×
            for &w in &rs {
83115620×
                *indeg.entry(w).or_insert(0) += 1;
83215620×
            }
83310401×
            rsucc.insert(u, rs);
834
        }
835
836
        // 3. Kahn's algorithm with side labelling for conflict regions.
8371270×
        let mut ready: BTreeSet<Vertex> = indeg
8381270×
            .iter()
83910401×
            .filter(|(_, &d)| d == 0)
8401270×
            .map(|(v, _)| *v)
8411270×
            .collect();
8421270×
        let mut side: HashMap<Vertex, u32> = HashMap::default();
8431270×
        let mut joins: HashSet<Vertex> = HashSet::default();
8441270×
        let mut next_side = 0u32;
8451270×
        let mut plain: Vec<Vertex> = Vec::new();
8461270×
        let mut conflict: Option<BTreeMap<u32, Vec<Vertex>>> = None;
8471270×
        let mut segments: Vec<Segment> = Vec::new();
848
8491863×
        let flush_plain = |plain: &mut Vec<Vertex>, segments: &mut Vec<Segment>| {
8501863×
            let atoms: Vec<AtomKey> = plain
8511863×
                .iter()
8528866×
                .filter_map(|v| {
8538866×
                    if let Vertex::Atom(k) = v {
8546326×
                        Some(*k)
855
                    } else {
8562540×
                        None
857
                    }
8588866×
                })
8591863×
                .collect();
8601863×
            plain.clear();
8611863×
            if !atoms.is_empty() {
8621583×
                segments.extend(split_zombies(atoms, &ghosts));
8631583×
            }
8641863×
        };
8651270×
        let finish_conflict = |c: BTreeMap<u32, Vec<Vertex>>, segments: &mut Vec<Segment>| {
866593×
            let sides: Vec<Vec<AtomKey>> = c
867593×
                .into_values()
8681186×
                .map(|vs| {
8691186×
                    vs.into_iter()
8701535×
                        .filter_map(|v| match v {
8711535×
                            Vertex::Atom(k) if !ghosts.contains(&k) => Some(k),
87254×
                            _ => None,
8731535×
                        })
8741186×
                        .collect::<Vec<_>>()
8751186×
                })
8761186×
                .filter(|s| !s.is_empty())
877593×
                .collect();
878593×
            match sides.len() {
8790×
                0 => {}
8800×
                1 => segments.push(Segment::Lines(sides.into_iter().next().unwrap())),
881593×
                _ => segments.push(Segment::Conflict(sides)),
882
            }
883593×
        };
884
88511671×
        while !ready.is_empty() {
88610401×
            if ready.len() >= 2 {
887650×
                if conflict.is_none() {
888593×
                    flush_plain(&mut plain, &mut segments);
889593×
                    conflict = Some(BTreeMap::new());
890593×
                }
8911300×
                for r in &ready {
8921300×
                    if !side.contains_key(r) {
8931186×
                        side.insert(*r, next_side);
8941186×
                        next_side += 1;
8951186×
                    }
896
                }
8979751×
            }
89810401×
            let v = ready.pop_first().unwrap();
89910401×
            let my_side = side.get(&v).copied();
90010401×
            match (&mut conflict, my_side) {
9011535×
                (Some(c), Some(s)) => c.entry(s).or_default().push(v),
902593×
                (Some(_), None) => {
903593×
                    let c = conflict.take().unwrap();
904593×
                    finish_conflict(c, &mut segments);
905593×
                    plain.push(v);
906593×
                }
9078273×
                (None, _) => plain.push(v),
908
            }
90915620×
            for &w in &rsucc[&v] {
91015620×
                let d = indeg.get_mut(&w).unwrap();
91115620×
                *d -= 1;
91215620×
                if conflict.is_some() && !joins.contains(&w) {
9131649×
                    match (my_side, side.get(&w).copied()) {
914982×
                        (Some(s), None) => {
915982×
                            side.insert(w, s);
916982×
                        }
917667×
                        (Some(s), Some(t)) if s != t => {
918633×
                            side.remove(&w);
919633×
                            joins.insert(w);
920633×
                        }
9210×
                        (None, Some(_)) => {
9220×
                            side.remove(&w);
9230×
                            joins.insert(w);
9240×
                        }
92534×
                        _ => {}
926
                    }
92713971×
                }
92815620×
                if *d == 0 {
9299131×
                    ready.insert(w);
9309131×
                }
931
            }
932
        }
9331270×
        if let Some(c) = conflict.take() {
9340×
            finish_conflict(c, &mut segments);
9351270×
        }
9361270×
        flush_plain(&mut plain, &mut segments);
9371270×
        Materialized { segments }
9381270×
    }
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.
94228973×
    pub fn render(&self, m: &Materialized, label: &dyn Fn(&ChangeHash) -> String) -> Vec<u8> {
94328973×
        let total = m.conflict_count();
94428973×
        let mut n = 0;
94528973×
        let mut out: Vec<u8> = Vec::new();
94630513×
        let push_atoms = |out: &mut Vec<u8>, atoms: &[AtomKey]| {
947159514×
            for a in atoms {
948159514×
                if let Some(c) = self.content(a) {
949159514×
                    out.extend_from_slice(c);
950159514×
                }
951
            }
95230513×
        };
95328973×
        let newline_if_needed = |out: &mut Vec<u8>| {
9542109×
            if !out.is_empty() && *out.last().unwrap() != b'\n' {
9550×
                out.push(b'\n');
9562109×
            }
9572109×
        };
95829810×
        for seg in &m.segments {
95929810×
            match seg {
96029107×
                Segment::Lines(a) => push_atoms(&mut out, a),
961429×
                Segment::Conflict(sides) => {
962429×
                    n += 1;
963429×
                    let k = sides.len();
964858×
                    for (i, s) in sides.iter().enumerate() {
965858×
                        newline_if_needed(&mut out);
966858×
                        let who = s.first().map(|a| label(&a.0)).unwrap_or_default();
967858×
                        let marker = if i == 0 { "<<<<<<<" } else { "=======" };
968858×
                        out.extend_from_slice(
969858×
                            format!("{marker} oxy conflict {n} of {total}, side {} of {k}: change {who}\n", i + 1).as_bytes(),
970
                        );
971858×
                        push_atoms(&mut out, s);
972
                    }
973429×
                    newline_if_needed(&mut out);
974429×
                    out.extend_from_slice(
975429×
                        format!(">>>>>>> oxy conflict {n} of {total} end\n").as_bytes(),
976
                    );
977
                }
978274×
                Segment::Zombie { deleted, inserted } => {
979274×
                    n += 1;
980274×
                    newline_if_needed(&mut out);
981274×
                    let deleter = deleted
982274×
                        .first()
983274×
                        .and_then(|a| self.deleters(a).next().copied())
984274×
                        .map(|d| label(&d))
985274×
                        .unwrap_or_default();
986274×
                    let inserter = inserted.first().map(|a| label(&a.0)).unwrap_or_default();
987274×
                    out.extend_from_slice(
988274×
                        format!("<<<<<<< oxy conflict {n} of {total}, side 1 of 2: deleted by change {deleter}\n-------\n").as_bytes(),
989
                    );
990274×
                    push_atoms(&mut out, deleted);
991274×
                    newline_if_needed(&mut out);
992274×
                    out.extend_from_slice(
993274×
                        format!(
994274×
                            "======= oxy conflict {n} of {total}, side 2 of 2: change {inserter}\n"
995274×
                        )
996274×
                        .as_bytes(),
997
                    );
998274×
                    push_atoms(&mut out, inserted);
999274×
                    newline_if_needed(&mut out);
1000274×
                    out.extend_from_slice(
1001274×
                        format!(">>>>>>> oxy conflict {n} of {total} end\n").as_bytes(),
1002
                    );
1003
                }
1004
            }
1005
        }
100628973×
        out
100728973×
    }
1008
}
1009
101035392×
fn vertex_value(v: &Vertex) -> crate::cbor::Value {
1011
    use crate::cbor::Value;
101235392×
    match v {
10133598×
        Vertex::Start => Value::Uint(0),
10143489×
        Vertex::End => Value::Uint(1),
101528305×
        Vertex::Atom((c, i)) => {
101628305×
            Value::Array(vec![Value::Bytes(c.0.to_vec()), Value::Uint(*i as u64)])
1017
        }
1018
    }
101935392×
}
1020
102110364×
fn vertex_from(v: &crate::cbor::Value) -> Result<Vertex, crate::objects::ObjectError> {
1022
    use crate::cbor::Value;
1023
    use crate::objects::ObjectError;
10248702×
    match v {
1025742×
        Value::Uint(0) => Ok(Vertex::Start),
1026920×
        Value::Uint(1) => Ok(Vertex::End),
10278702×
        Value::Array(a) if a.len() == 2 => Ok(Vertex::Atom((
10288702×
            crate::objects::oref(&a[0], "vertex")?,
10298702×
            crate::objects::u32_(&a[1], "vertex")?,
1030
        ))),
10310×
        _ => Err(ObjectError::Schema(
10320×
            "vertex: expected 0, 1, or [hash, index]".into(),
10330×
        )),
1034
    }
103510364×
}
1036
1037
impl FileGraph {
1038
    /// Serialize for a checkpoint: `{0: atoms [[hash, index, content|null, [deleters]]], 1: edges [[from, to]]}`.
10391531×
    pub fn to_value(&self) -> crate::cbor::Value {
1040
        use crate::cbor::Value;
10411531×
        let mut atoms: Vec<(&AtomKey, &AtomInfo)> = self.atoms.iter().collect();
10421531×
        atoms.sort_by_key(|(k, _)| **k);
10431531×
        let mut edges: Vec<(Vertex, Vertex)> = self
10441531×
            .succ
10451531×
            .iter()
104617696×
            .flat_map(|(a, bs)| bs.iter().map(move |b| (*a, *b)))
10471531×
            .collect();
10481531×
        edges.sort();
10491531×
        Value::map([
1050
            (
1051
                0,
1052
                Value::Array(
10531531×
                    atoms
10541531×
                        .into_iter()
105512882×
                        .map(|((c, i), info)| {
105612882×
                            Value::Array(vec![
105712882×
                                Value::Bytes(c.0.to_vec()),
105812882×
                                Value::Uint(*i as u64),
105912882×
                                info.content
106012882×
                                    .as_ref()
106112882×
                                    .map(|b| Value::Bytes(b.bytes().to_vec()))
106212882×
                                    .unwrap_or(Value::Null),
1063
                                Value::Array(
106412882×
                                    info.deleted_by
106512882×
                                        .iter()
106612882×
                                        .map(|d| Value::Bytes(d.0.to_vec()))
106712882×
                                        .collect(),
1068
                                ),
1069
                            ])
107012882×
                        })
10711531×
                        .collect(),
1072
                ),
1073
            ),
1074
            (
1075
                1,
1076
                Value::Array(
10771531×
                    edges
10781531×
                        .iter()
107917696×
                        .map(|(a, b)| Value::Array(vec![vertex_value(a), vertex_value(b)]))
10801531×
                        .collect(),
1081
                ),
1082
            ),
1083
        ])
10841531×
    }
1085
1086339×
    pub fn from_value(v: &crate::cbor::Value) -> Result<FileGraph, crate::objects::ObjectError> {
1087
        use crate::objects::{array, bytes, field, map, oref, u32_, ObjectError};
1088339×
        let m = map(v, "file graph")?;
1089339×
        let mut g = FileGraph {
1090339×
            atoms: HashMap::default(),
1091339×
            succ: HashMap::default(),
1092339×
            order: OrderSlot::default(),
1093339×
        };
1094339×
        let atoms = array(field(m, 0, "atoms")?, "atoms")?;
1095
        // Every atom's line in one buffer.
1096339×
        let mut texts: Vec<&[u8]> = Vec::new();
10974124×
        for a in atoms {
10984124×
            let e = array(a, "atom")?;
10994124×
            if e.len() == 4 && !e[2].is_null() {
11004124×
                texts.push(bytes(&e[2], "atom content")?);
11010×
            }
1102
        }
1103339×
        let all: Lines = texts.into_iter().collect();
1104339×
        let mut next = 0u32;
11054124×
        for a in atoms {
11064124×
            let e = array(a, "atom")?;
11074124×
            if e.len() != 4 {
11080×
                return Err(ObjectError::Schema("atom: expected 4 fields".into()));
11094124×
            }
11104124×
            let key = (oref(&e[0], "atom change")?, u32_(&e[1], "atom index")?);
11114124×
            let content = if e[2].is_null() {
11120×
                None
1113
            } else {
11144124×
                next += 1;
11154124×
                Some(LineRef::new(all.clone(), next - 1))
1116
            };
11174124×
            let deleted_by = array(&e[3], "deleters")?
11184124×
                .iter()
11194124×
                .map(|d| oref(d, "deleter"))
11204124×
                .collect::<Result<BTreeSet<_>, _>>()?;
11214124×
            g.atoms.insert(
11224124×
                key,
11234124×
                AtomInfo {
11244124×
                    content,
11254124×
                    deleted_by,
11264124×
                },
1127
            );
1128
        }
11295182×
        for e in array(field(m, 1, "edges")?, "edges")? {
11305182×
            let pair = array(e, "edge")?;
11315182×
            if pair.len() != 2 {
11320×
                return Err(ObjectError::Schema("edge: expected [from, to]".into()));
11335182×
            }
11345182×
            g.edge(vertex_from(&pair[0])?, vertex_from(&pair[1])?);
1135
        }
1136339×
        Ok(g)
1137339×
    }
1138
}
1139
1140
/// Split a plain run into `Lines` and `Zombie` segments around ghost atoms.
11411583×
fn split_zombies(atoms: Vec<AtomKey>, ghosts: &HashSet<AtomKey>) -> Vec<Segment> {
11421583×
    let mut out = Vec::new();
11431583×
    let mut lines: Vec<AtomKey> = Vec::new();
11441583×
    let mut i = 0;
11457439×
    while i < atoms.len() {
11465856×
        if !ghosts.contains(&atoms[i]) {
11475430×
            lines.push(atoms[i]);
11485430×
            i += 1;
11495430×
            continue;
1150426×
        }
1151426×
        if !lines.is_empty() {
1152244×
            out.push(Segment::Lines(std::mem::take(&mut lines)));
1153244×
        }
1154426×
        let mut deleted = Vec::new();
1155852×
        while i < atoms.len() && ghosts.contains(&atoms[i]) {
1156426×
            deleted.push(atoms[i]);
1157426×
            i += 1;
1158426×
        }
1159426×
        let mut inserted = Vec::new();
1160426×
        if i < atoms.len() {
1161406×
            let ch = atoms[i].0;
1162876×
            while i < atoms.len() && atoms[i].0 == ch && !ghosts.contains(&atoms[i]) {
1163470×
                inserted.push(atoms[i]);
1164470×
                i += 1;
1165470×
            }
116620×
        }
1167426×
        out.push(Segment::Zombie { deleted, inserted });
1168
    }
11691583×
    if !lines.is_empty() {
11701354×
        out.push(Segment::Lines(lines));
11711354×
    }
11721583×
    out
11731583×
}
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
}