OXYGENHUB

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

1446 of 1494 lines run, 212 of 236 functions · run #393 on identical-sides · 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<'_> {
385761×
    fn depends_on(&self, a: &ChangeHash, b: &ChangeHash) -> bool {
395761×
        if let Some(v) = self.known.borrow().get(&(*a, *b)) {
402842×
            return *v;
412919×
        }
422919×
        let v = self.inner.depends_on(a, b);
432919×
        self.known.borrow_mut().insert((*a, *b), v);
442919×
        v
455761×
    }
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 {
9428061×
    fn get(&self) -> Option<std::sync::Arc<Order>> {
9528061×
        self.0.lock().unwrap_or_else(|e| e.into_inner()).clone()
9628061×
    }
971795×
    fn set(&self, o: Option<std::sync::Arc<Order>>) {
981795×
        *self.0.lock().unwrap_or_else(|e| e.into_inner()) = o;
991795×
    }
10069929×
    fn take(&mut self) -> Option<std::sync::Arc<Order>> {
10169929×
        self.0.get_mut().unwrap_or_else(|e| e.into_inner()).take()
10269929×
    }
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 {
1121785×
    fn known(atoms: Vec<AtomKey>) -> Order {
1131785×
        Order {
1141785×
            atoms,
1151785×
            unchecked: Vec::new(),
1161785×
            confirmed: std::sync::atomic::AtomicBool::new(true),
1171785×
        }
1181785×
    }
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.
125544×
    fn splice(
126544×
        &self,
127544×
        h: ChangeHash,
128544×
        inserts: &[(Vertex, Vertex, u32, u32)],
129544×
        deleted: &[AtomKey],
130544×
    ) -> Option<std::sync::Arc<Order>> {
131544×
        let mut want: HashSet<AtomKey> = deleted.iter().copied().collect();
132586×
        for (a, b, _, _) in inserts {
1331172×
            for v in [a, b] {
1341172×
                if let Vertex::Atom(k) = v {
135962×
                    want.insert(*k);
136962×
                }
137
            }
138
        }
139544×
        let mut pos: HashMap<AtomKey, usize> = HashMap::default();
1402899×
        for (i, k) in self.atoms.iter().enumerate() {
1412899×
            if want.contains(k) {
1421305×
                pos.insert(*k, i);
1431594×
            }
144
        }
145544×
        let len = self.atoms.len();
146544×
        let mut gone = vec![false; len];
147544×
        let mut unchecked = if self.confirmed.load(std::sync::atomic::Ordering::Relaxed) {
148544×
            Vec::new()
149
        } else {
1500×
            self.unchecked.clone()
151
        };
152737×
        for k in deleted {
153737×
            if k.0 == h {
1540×
                return None;
155737×
            }
156737×
            if let Some(&i) = pos.get(k) {
157714×
                if !gone[i] {
158714×
                    gone[i] = true;
159714×
                    unchecked.push(*k);
160714×
                }
16123×
            }
162
        }
163
        // Each run goes in the gap its anchors leave (slot `i`: before
164
        // `atoms[i]`), which must hold nothing that stays.
165544×
        let mut slots: Vec<(usize, usize, u32, u32)> = Vec::with_capacity(inserts.len());
166567×
        for &(a, b, first, count) in inserts {
167567×
            let from = match a {
168137×
                Vertex::Start => 0,
169430×
                Vertex::Atom(k) => pos.get(&k)? + 1,
1700×
                Vertex::End => return None,
171
            };
172556×
            let to = match b {
17369×
                Vertex::End => len,
174487×
                Vertex::Atom(k) => *pos.get(&k)?,
1750×
                Vertex::Start => return None,
176
            };
177549×
            if from > to || gone[from..to].iter().any(|g| !g) {
1785×
                return None;
179544×
            }
180544×
            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.
184521×
        slots.sort_unstable();
185521×
        for w in slots.windows(2) {
186159×
            let (end, next) = (w[0].1, w[1].0);
187303×
            if end >= next || !gone[end..next].iter().any(|g| !g) {
1880×
                return None;
189159×
            }
190
        }
191543×
        let added: usize = slots.iter().map(|s| s.3 as usize).sum();
192521×
        let mut atoms = Vec::with_capacity(len + added);
193521×
        let mut slots = slots.into_iter().peekable();
1943208×
        let mut runs_at = |i: usize, atoms: &mut Vec<AtomKey>| {
1953751×
            while let Some(&(from, _, first, count)) = slots.peek() {
1961832×
                if from != i {
1971289×
                    break;
198543×
                }
199791×
                atoms.extend((first..first + count).map(|j| (h, j)));
200543×
                slots.next();
201
            }
2023208×
        };
2032687×
        for (i, (k, g)) in self.atoms.iter().zip(&gone).enumerate() {
2042687×
            runs_at(i, &mut atoms);
2052687×
            if !g {
2062010×
                atoms.push(*k);
2072010×
            }
208
        }
209521×
        runs_at(len, &mut atoms);
210521×
        let confirmed = unchecked.is_empty();
211521×
        Some(std::sync::Arc::new(Order {
212521×
            atoms,
213521×
            unchecked,
214521×
            confirmed: std::sync::atomic::AtomicBool::new(confirmed),
215521×
        }))
216544×
    }
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 {
230248314×
    fn insert(&mut self, v: Vertex) {
23133322×
        match self {
232212901×
            Edges::None => *self = Edges::One(v),
23333322×
            Edges::One(a) if *a == v => {}
23433322×
            Edges::One(a) => {
23533322×
                let a = *a;
23633322×
                *self = Edges::Many(if a < v { vec![a, v] } else { vec![v, a] });
237
            }
2382091×
            Edges::Many(list) => {
2392091×
                if let Err(i) = list.binary_search(&v) {
2402091×
                    list.insert(i, v);
2412091×
                }
242
            }
243
        }
244248314×
    }
245
246968256×
    fn as_slice(&self) -> &[Vertex] {
247968256×
        match self {
2485243×
            Edges::None => &[],
249708086×
            Edges::One(v) => std::slice::from_ref(v),
250254927×
            Edges::Many(list) => list,
251
        }
252968256×
    }
253
254699276×
    fn iter(&self) -> std::slice::Iter<'_, Vertex> {
255699276×
        self.as_slice().iter()
256699276×
    }
257
}
258
259
impl Default for FileGraph {
26026819×
    fn default() -> Self {
26126819×
        Self::new()
26226819×
    }
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 {
28534316×
    pub fn is_conflicted(&self) -> bool {
28634316×
        self.segments
28734316×
            .iter()
28834316×
            .any(|s| !matches!(s, Segment::Lines(_)))
28934316×
    }
29026089×
    pub fn conflict_count(&self) -> usize {
29126089×
        self.segments
29226089×
            .iter()
29327101×
            .filter(|s| !matches!(s, Segment::Lines(_)))
29426089×
            .count()
29526089×
    }
296
    /// Every live atom in materialized order, conflict sides concatenated.
2971376×
    pub fn live_atoms(&self) -> Vec<AtomKey> {
2981376×
        let mut out = Vec::new();
2991415×
        for s in &self.segments {
3001415×
            match s {
3011371×
                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
        }
3061376×
        out
3071376×
    }
308
}
309
310
impl FileGraph {
31126889×
    pub fn new() -> Self {
31226889×
        let mut g = FileGraph {
31326889×
            atoms: HashMap::default(),
31426889×
            succ: HashMap::default(),
31526889×
            order: OrderSlot::default(),
31626889×
        };
31726889×
        g.edge(Vertex::Start, Vertex::End);
31826889×
        g
31926889×
    }
320
32132047×
    fn edge(&mut self, a: Vertex, b: Vertex) {
32232047×
        self.succ.entry(a).or_default().insert(b);
32332047×
        self.succ.entry(b).or_default();
32432047×
    }
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.
34134704×
    pub fn insert_owned(
34234704×
        &mut self,
34334704×
        change: ChangeHash,
34434704×
        first_index: u32,
34534704×
        after: Vertex,
34634704×
        before: Vertex,
34734704×
        lines: Lines,
34834704×
    ) {
34934704×
        self.order.take();
35034704×
        self.atoms.reserve(lines.len());
35134704×
        self.succ.reserve(lines.len() + 1);
35234704×
        let mut prev = after;
353181563×
        for i in 0..lines.len() {
354181563×
            let key = (change, first_index + i as u32);
355181563×
            self.atoms.entry(key).or_default().content =
356181563×
                Some(LineRef::new(lines.clone(), i as u32));
357181563×
            let v = Vertex::Atom(key);
358181563×
            self.succ.entry(prev).or_default().insert(v);
359181563×
            prev = v;
360181563×
        }
36134704×
        self.succ.entry(prev).or_default().insert(before);
36234704×
        self.succ.entry(before).or_default();
36334704×
    }
364
365
    /// Apply a `Delete` of `range` by change `by`.
3666416×
    pub fn delete(&mut self, by: ChangeHash, range: &AtomRange) {
3676416×
        self.order.take();
3686679×
        for i in range.from..range.to {
3696679×
            self.atoms
3706679×
                .entry((range.change, i))
3716679×
                .or_default()
3726679×
                .deleted_by
3736679×
                .insert(by);
3746679×
        }
3756416×
    }
376
377478694×
    pub fn is_live(&self, k: &AtomKey) -> bool {
378478694×
        self.atoms
379478694×
            .get(k)
380478694×
            .is_some_and(|a| a.content.is_some() && a.deleted_by.is_empty())
381478694×
    }
382
383166925×
    pub fn content(&self, k: &AtomKey) -> Option<&[u8]> {
384166925×
        self.atoms
385166925×
            .get(k)
386166925×
            .and_then(|a| a.content.as_ref().map(LineRef::bytes))
387166925×
    }
388
389422×
    pub fn deleters(&self, k: &AtomKey) -> impl Iterator<Item = &ChangeHash> {
390422×
        self.atoms
391422×
            .get(k)
392422×
            .into_iter()
393422×
            .flat_map(|a| a.deleted_by.iter())
394422×
    }
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
5181272×
    pub fn live_successor_changes(&self, k: &AtomKey) -> Vec<ChangeHash> {
5191272×
        self.succ
5201272×
            .get(&Vertex::Atom(*k))
5211272×
            .map(|ss| {
5221271×
                ss.iter()
5231271×
                    .filter_map(|s| match s {
524972×
                        Vertex::Atom(y) if self.is_live(y) => Some(y.0),
525462×
                        _ => None,
5261318×
                    })
5271271×
                    .collect()
5281271×
            })
5291272×
            .unwrap_or_default()
5301272×
    }
531
532362239×
    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.
537362239×
        self.succ.get(&Vertex::Atom(*k)).is_some_and(|ss| {
538476855×
            ss.iter().any(|s| match s {
539476855×
                Vertex::Atom(y) if self.is_live(y) => !info
5405394×
                    .deleted_by
5415394×
                    .iter()
5425445×
                    .any(|d| deps.depends_on(d, &y.0) || deps.depends_on(&y.0, d)),
543501668×
                _ => false,
544507062×
            })
545362239×
        })
546362239×
    }
547
548
    /// Successors of `v` in the graph with non-kept vertices contracted away.
54911839×
    fn reduced_succ(
55011839×
        &self,
55111839×
        v: Vertex,
55211839×
        kept: &HashSet<Vertex>,
55311839×
        memo: &mut HashMap<Vertex, BTreeSet<Vertex>>,
55411839×
    ) -> BTreeSet<Vertex> {
55511839×
        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.
55813101×
        if direct.iter().all(|s| kept.contains(s)) {
5597594×
            return direct.iter().copied().collect();
5604245×
        }
5614245×
        let mut out = BTreeSet::new();
5624245×
        let mut stack: Vec<Vertex> = direct.to_vec();
5634245×
        let mut seen = HashSet::default();
564504056×
        while let Some(s) = stack.pop() {
565499811×
            if kept.contains(&s) {
56634714×
                out.insert(s);
567465097×
            } else if seen.insert(s) {
568320043×
                if let Some(m) = memo.get(&s) {
5690×
                    out.extend(m.iter().copied());
570320043×
                } else if let Some(next) = self.succ.get(&s) {
571320043×
                    stack.extend(next.iter().copied());
572320043×
                }
573145054×
            }
574
        }
5754245×
        out
57611839×
    }
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.
58326273×
    fn as_chain(&self) -> Option<Vec<AtomKey>> {
58426273×
        if self
58526273×
            .atoms
58626273×
            .values()
587142779×
            .any(|a| a.content.is_none() || !a.deleted_by.is_empty())
588
        {
5892353×
            return None;
59023920×
        }
59123920×
        let mut order = Vec::with_capacity(self.atoms.len());
59223920×
        let mut v = Vertex::Start;
593
        loop {
594134594×
            let succ = self.succ.get(&v)?.as_slice();
595160251×
            let mut atoms = succ.iter().filter(|s| **s != Vertex::End);
596134594×
            match (atoms.next(), atoms.next()) {
59723467×
                (None, _) if succ.contains(&Vertex::End) => break,
598110674×
                (Some(Vertex::Atom(k)), None) if order.len() < self.atoms.len() => {
599110674×
                    order.push(*k);
600110674×
                    v = Vertex::Atom(*k);
601110674×
                }
602453×
                _ => return None,
603
            }
604
        }
60523467×
        (order.len() == self.atoms.len()).then_some(order)
60626273×
    }
607
608
    /// Order the live atoms and locate conflicts.
60927596×
    pub fn materialize(&self, deps: &dyn DepOracle) -> Materialized {
61027596×
        let deps = &MemoDeps {
61127596×
            inner: deps,
61227596×
            known: Default::default(),
61327596×
        };
61427596×
        let lines = |order: Vec<AtomKey>| Materialized {
61526579×
            segments: if order.is_empty() {
616242×
                vec![]
617
            } else {
61826337×
                vec![Segment::Lines(order)]
619
            },
62026579×
        };
621
        use std::sync::atomic::Ordering::Relaxed;
622
        // Which way it went, and how long it took (`OXY_TIMINGS`).
62327596×
        let started = crate::timing::enabled().then(std::time::Instant::now);
62427596×
        let took = |name: &'static str| {
62527596×
            if let Some(t) = started {
6260×
                crate::timing::add(name, t.elapsed());
62727596×
            }
62827596×
        };
62927596×
        if let Some(o) = self.order.get() {
6301339×
            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×
                });
6361339×
            if holds {
6371329×
                o.confirmed.store(true, Relaxed);
6381329×
                took("graph: kept order");
6391329×
                return lines(o.atoms.clone());
64010×
            }
64110×
            self.order.set(None);
64226257×
        }
643
        // A chain (nothing ever deleted) is quick to walk, and a fresh tree
644
        // is all chains: no order is kept for one.
64526267×
        if let Some(order) = self.as_chain() {
64623465×
            took("graph: chain");
64723465×
            return lines(order);
6482802×
        }
6492802×
        if let Some(order) = self.as_order(deps) {
6501785×
            self.order
6511785×
                .set(Some(std::sync::Arc::new(Order::known(order.clone()))));
6521785×
            took("graph: single order");
6531785×
            return lines(order);
6541017×
        }
6551017×
        let m = self.materialize_general(deps);
6561017×
        took("graph: general");
6571017×
        m
65827596×
    }
659
660
    /// Take the kept order, to [`Order::splice`] it once a change's edits
661
    /// have applied (they drop it).
66228809×
    pub fn take_order(&mut self) -> Option<std::sync::Arc<Order>> {
66328809×
        self.order.take()
66428809×
    }
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.
670545×
    pub fn keep_spliced(
671545×
        &mut self,
672545×
        order: std::sync::Arc<Order>,
673545×
        h: ChangeHash,
674545×
        inserts: &[(Vertex, Vertex, u32, u32)],
675545×
        deleted: &[AtomKey],
676545×
    ) {
677545×
        let live = inserts
678545×
            .iter()
679858×
            .all(|&(_, _, first, count)| (first..first + count).all(|i| self.is_live(&(h, i))));
680545×
        let spliced = if live {
681544×
            order.splice(h, inserts, deleted)
682
        } else {
6831×
            None
684
        };
685545×
        *self.order.0.get_mut().unwrap_or_else(|e| e.into_inner()) = spliced;
686545×
    }
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.
6942804×
    fn as_order(&self, deps: &dyn DepOracle) -> Option<Vec<AtomKey>> {
695
        // Kept vertices by dense index: Start, End, then the live atoms.
6962804×
        let mut index: HashMap<Vertex, u32> =
6972804×
            HashMap::with_capacity_and_hasher(self.atoms.len() + 2, Default::default());
6982804×
        let mut verts: Vec<Vertex> = Vec::with_capacity(self.atoms.len() + 2);
6992804×
        verts.extend([Vertex::Start, Vertex::End]);
7002804×
        index.insert(Vertex::Start, 0);
7012804×
        index.insert(Vertex::End, 1);
702104910×
        for (k, info) in &self.atoms {
703104910×
            if info.content.is_none() {
7040×
                continue;
705104910×
            }
706104910×
            if info.deleted_by.is_empty() {
70751582×
                index.insert(Vertex::Atom(*k), verts.len() as u32);
70851582×
                verts.push(Vertex::Atom(*k));
70953328×
            } else if self.is_ghost(k, info, deps) {
710543×
                return None;
71152785×
            }
712
        }
713
        // Each kept vertex's successors, contracting the others: what a
714
        // contracted vertex reaches is worked out once (post-order).
7152261×
        let mut reach: HashMap<Vertex, Vec<u32>> = HashMap::default();
71610881×
        let contracted = |v: Vertex, reach: &mut HashMap<Vertex, Vec<u32>>| {
71710881×
            let mut stack: Vec<(Vertex, bool)> = vec![(v, false)];
71888374×
            while let Some((x, done)) = stack.pop() {
71977493×
                if reach.contains_key(&x) {
72010007×
                    continue;
72167486×
                }
72267486×
                let next = self.succ.get(&x).map(Edges::as_slice).unwrap_or_default();
72367486×
                if !done {
72433743×
                    stack.push((x, true));
72545687×
                    for s in next {
72645687×
                        if !index.contains_key(s) && !reach.contains_key(s) {
72732869×
                            stack.push((*s, false));
72832869×
                        }
729
                    }
73033743×
                    continue;
73133743×
                }
73233743×
                let mut out: Vec<u32> = Vec::new();
73345687×
                for s in next {
73445687×
                    match index.get(s) {
7355614×
                        Some(i) => out.push(*i),
73640073×
                        None => out.extend(reach.get(s).into_iter().flatten()),
737
                    }
738
                }
73933743×
                out.sort_unstable();
74033743×
                out.dedup();
74133743×
                reach.insert(x, out);
742
            }
74310881×
        };
744
        // Successors of vertex `i`: `succ[starts[i]..starts[i + 1]]`.
7452261×
        let mut succ: Vec<u32> = Vec::with_capacity(verts.len() * 2);
7462261×
        let mut starts: Vec<usize> = Vec::with_capacity(verts.len() + 1);
7472261×
        let mut indeg: Vec<u32> = vec![0; verts.len()];
74855019×
        for v in &verts {
74955019×
            let from = succ.len();
75055019×
            starts.push(from);
75164485×
            for s in self.succ.get(v).map(Edges::as_slice).unwrap_or_default() {
75264485×
                match index.get(s) {
75353604×
                    Some(i) => succ.push(*i),
75410881×
                    None => {
75510881×
                        contracted(*s, &mut reach);
75610881×
                        succ.extend(reach.get(s).into_iter().flatten());
75710881×
                    }
758
                }
759
            }
76055019×
            if succ.len() - from > 1 {
7616047×
                succ[from..].sort_unstable();
7626047×
                let mut kept = from;
76317963×
                for i in from..succ.len() {
76417963×
                    if i == from || succ[i] != succ[kept - 1] {
76512804×
                        succ[kept] = succ[i];
76612804×
                        kept += 1;
76712804×
                    }
768
                }
7696047×
                succ.truncate(kept);
77048972×
            }
77159515×
            for &w in &succ[from..] {
77259515×
                indeg[w as usize] += 1;
77359515×
            }
774
        }
7752261×
        starts.push(succ.len());
776
        // Kahn's algorithm, giving up where two vertices are ready at once.
7772261×
        let mut ready: Vec<u32> = (0..verts.len() as u32)
77855019×
            .filter(|&i| indeg[i as usize] == 0)
7792261×
            .collect();
7802261×
        let mut order: Vec<AtomKey> = Vec::with_capacity(verts.len());
7812261×
        let mut seen = 0;
78254926×
        while let Some(v) = ready.pop() {
78353140×
            if !ready.is_empty() {
7840×
                return None;
78553140×
            }
78653140×
            seen += 1;
78753140×
            if let Vertex::Atom(k) = verts[v as usize] {
78849093×
                order.push(k);
78949093×
            }
79057980×
            for &w in &succ[starts[v as usize]..starts[v as usize + 1]] {
79157980×
                indeg[w as usize] -= 1;
79257980×
                if indeg[w as usize] == 0 {
79351829×
                    ready.push(w);
79451829×
                }
795
            }
79653140×
            if ready.len() > 1 {
797475×
                return None;
79852665×
            }
799
        }
8001786×
        (seen == verts.len()).then_some(order)
8012804×
    }
802
803
    /// [`FileGraph::materialize`] for any graph: contraction, then a
804
    /// topological order with conflict regions.
8051511×
    fn materialize_general(&self, deps: &dyn DepOracle) -> Materialized {
806
        // 1. Vertices that survive contraction: live atoms, ghosts, Start, End.
8071511×
        let mut kept: HashSet<Vertex> = HashSet::default();
8081511×
        let mut ghosts: HashSet<AtomKey> = HashSet::default();
8091511×
        kept.insert(Vertex::Start);
8101511×
        kept.insert(Vertex::End);
811316433×
        for (k, info) in &self.atoms {
812316433×
            if info.content.is_none() {
8130×
                continue;
814316433×
            }
815316433×
            if info.deleted_by.is_empty() {
8168138×
                kept.insert(Vertex::Atom(*k));
817308295×
            } else if self.is_ghost(k, info, deps) {
818679×
                kept.insert(Vertex::Atom(*k));
819679×
                ghosts.insert(*k);
820307616×
            }
821
        }
822
823
        // 2. Reduced graph over kept vertices.
8241511×
        let mut memo = HashMap::default();
8251511×
        let mut rsucc: HashMap<Vertex, BTreeSet<Vertex>> = HashMap::default();
8261511×
        let mut indeg: HashMap<Vertex, usize> = HashMap::default();
82711839×
        for &u in &kept {
82811839×
            indeg.entry(u).or_insert(0);
82911839×
            let rs = self.reduced_succ(u, &kept, &mut memo);
83017495×
            for &w in &rs {
83117495×
                *indeg.entry(w).or_insert(0) += 1;
83217495×
            }
83311839×
            rsucc.insert(u, rs);
834
        }
835
836
        // 3. Kahn's algorithm with side labelling for conflict regions.
8371511×
        let mut ready: BTreeSet<Vertex> = indeg
8381511×
            .iter()
83911839×
            .filter(|(_, &d)| d == 0)
8401511×
            .map(|(v, _)| *v)
8411511×
            .collect();
8421511×
        let mut side: HashMap<Vertex, u32> = HashMap::default();
8431511×
        let mut joins: HashSet<Vertex> = HashSet::default();
8441511×
        let mut next_side = 0u32;
8451511×
        let mut plain: Vec<Vertex> = Vec::new();
8461511×
        let mut conflict: Option<BTreeMap<u32, Vec<Vertex>>> = None;
8471511×
        let mut segments: Vec<Segment> = Vec::new();
848
8492217×
        let flush_plain = |plain: &mut Vec<Vertex>, segments: &mut Vec<Segment>| {
8502217×
            let atoms: Vec<AtomKey> = plain
8512217×
                .iter()
85210070×
                .filter_map(|v| {
85310070×
                    if let Vertex::Atom(k) = v {
8547048×
                        Some(*k)
855
                    } else {
8563022×
                        None
857
                    }
85810070×
                })
8592217×
                .collect();
8602217×
            plain.clear();
8612217×
            if !atoms.is_empty() {
8621827×
                segments.extend(split_zombies(atoms, &ghosts));
8631827×
            }
8642217×
        };
8651511×
        let finish_conflict = |c: BTreeMap<u32, Vec<Vertex>>, segments: &mut Vec<Segment>| {
866706×
            let sides: Vec<Vec<AtomKey>> = c
867706×
                .into_values()
8681429×
                .map(|vs| {
8691429×
                    vs.into_iter()
8701769×
                        .filter_map(|v| match v {
8711769×
                            Vertex::Atom(k) if !ghosts.contains(&k) => Some(k),
87285×
                            _ => None,
8731769×
                        })
8741429×
                        .collect::<Vec<_>>()
8751429×
                })
8761429×
                .filter(|s| !s.is_empty())
877706×
                .collect();
878706×
            match sides.len() {
8790×
                0 => {}
8800×
                1 => segments.push(Segment::Lines(sides.into_iter().next().unwrap())),
881706×
                _ => segments.push(Segment::Conflict(sides)),
882
            }
883706×
        };
884
88513350×
        while !ready.is_empty() {
88611839×
            if ready.len() >= 2 {
887847×
                if conflict.is_none() {
888706×
                    flush_plain(&mut plain, &mut segments);
889706×
                    conflict = Some(BTreeMap::new());
890706×
                }
8911711×
                for r in &ready {
8921711×
                    if !side.contains_key(r) {
8931429×
                        side.insert(*r, next_side);
8941429×
                        next_side += 1;
8951429×
                    }
896
                }
89710992×
            }
89811839×
            let v = ready.pop_first().unwrap();
89911839×
            let my_side = side.get(&v).copied();
90011839×
            match (&mut conflict, my_side) {
9011769×
                (Some(c), Some(s)) => c.entry(s).or_default().push(v),
902706×
                (Some(_), None) => {
903706×
                    let c = conflict.take().unwrap();
904706×
                    finish_conflict(c, &mut segments);
905706×
                    plain.push(v);
906706×
                }
9079364×
                (None, _) => plain.push(v),
908
            }
90917495×
            for &w in &rsucc[&v] {
91017495×
                let d = indeg.get_mut(&w).unwrap();
91117495×
                *d -= 1;
91217495×
                if conflict.is_some() && !joins.contains(&w) {
9132008×
                    match (my_side, side.get(&w).copied()) {
9141123×
                        (Some(s), None) => {
9151123×
                            side.insert(w, s);
9161123×
                        }
917885×
                        (Some(s), Some(t)) if s != t => {
918783×
                            side.remove(&w);
919783×
                            joins.insert(w);
920783×
                        }
9210×
                        (None, Some(_)) => {
9220×
                            side.remove(&w);
9230×
                            joins.insert(w);
9240×
                        }
925102×
                        _ => {}
926
                    }
92715487×
                }
92817495×
                if *d == 0 {
92910328×
                    ready.insert(w);
93010328×
                }
931
            }
932
        }
9331511×
        if let Some(c) = conflict.take() {
9340×
            finish_conflict(c, &mut segments);
9351511×
        }
9361511×
        flush_plain(&mut plain, &mut segments);
9371511×
        Materialized { segments }
9381511×
    }
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.
94226088×
    pub fn render(&self, m: &Materialized, label: &dyn Fn(&ChangeHash) -> String) -> Vec<u8> {
94326088×
        let total = m.conflict_count();
94426088×
        let mut n = 0;
94526088×
        let mut out: Vec<u8> = Vec::new();
94628062×
        let push_atoms = |out: &mut Vec<u8>, atoms: &[AtomKey]| {
947166628×
            for a in atoms {
948166628×
                if let Some(c) = self.content(a) {
949166628×
                    out.extend_from_slice(c);
950166628×
                }
951
            }
95228062×
        };
95326088×
        let newline_if_needed = |out: &mut Vec<u8>| {
9542862×
            if !out.is_empty() && *out.last().unwrap() != b'\n' {
9550×
                out.push(b'\n');
9562862×
            }
9572862×
        };
95827098×
        for seg in &m.segments {
95927098×
            match seg {
96026149×
                Segment::Lines(a) => push_atoms(&mut out, a),
961530×
                Segment::Conflict(sides) => {
962530×
                    n += 1;
963530×
                    let k = sides.len();
9641075×
                    for (i, s) in sides.iter().enumerate() {
9651075×
                        newline_if_needed(&mut out);
9661075×
                        let who = s.first().map(|a| label(&a.0)).unwrap_or_default();
9671075×
                        let marker = if i == 0 { "<<<<<<<" } else { "=======" };
9681075×
                        out.extend_from_slice(
9691075×
                            format!("{marker} oxy conflict {n} of {total}, side {} of {k}: change {who}\n", i + 1).as_bytes(),
970
                        );
9711075×
                        push_atoms(&mut out, s);
972
                    }
973530×
                    newline_if_needed(&mut out);
974530×
                    out.extend_from_slice(
975530×
                        format!(">>>>>>> oxy conflict {n} of {total} end\n").as_bytes(),
976
                    );
977
                }
978419×
                Segment::Zombie { deleted, inserted } => {
979419×
                    n += 1;
980419×
                    newline_if_needed(&mut out);
981419×
                    let deleter = deleted
982419×
                        .first()
983419×
                        .and_then(|a| self.deleters(a).next().copied())
984419×
                        .map(|d| label(&d))
985419×
                        .unwrap_or_default();
986419×
                    let inserter = inserted.first().map(|a| label(&a.0)).unwrap_or_default();
987419×
                    out.extend_from_slice(
988419×
                        format!("<<<<<<< oxy conflict {n} of {total}, side 1 of 2: deleted by change {deleter}\n-------\n").as_bytes(),
989
                    );
990419×
                    push_atoms(&mut out, deleted);
991419×
                    newline_if_needed(&mut out);
992419×
                    out.extend_from_slice(
993419×
                        format!(
994419×
                            "======= oxy conflict {n} of {total}, side 2 of 2: change {inserter}\n"
995419×
                        )
996419×
                        .as_bytes(),
997
                    );
998419×
                    push_atoms(&mut out, inserted);
999419×
                    newline_if_needed(&mut out);
1000419×
                    out.extend_from_slice(
1001419×
                        format!(">>>>>>> oxy conflict {n} of {total} end\n").as_bytes(),
1002
                    );
1003
                }
1004
            }
1005
        }
100626088×
        out
100726088×
    }
1008
}
1009
101034864×
fn vertex_value(v: &Vertex) -> crate::cbor::Value {
1011
    use crate::cbor::Value;
101234864×
    match v {
10133246×
        Vertex::Start => Value::Uint(0),
10143445×
        Vertex::End => Value::Uint(1),
101528173×
        Vertex::Atom((c, i)) => {
101628173×
            Value::Array(vec![Value::Bytes(c.0.to_vec()), Value::Uint(*i as u64)])
1017
        }
1018
    }
101934864×
}
1020
102110316×
fn vertex_from(v: &crate::cbor::Value) -> Result<Vertex, crate::objects::ObjectError> {
1022
    use crate::cbor::Value;
1023
    use crate::objects::ObjectError;
10248690×
    match v {
1025710×
        Value::Uint(0) => Ok(Vertex::Start),
1026916×
        Value::Uint(1) => Ok(Vertex::End),
10278690×
        Value::Array(a) if a.len() == 2 => Ok(Vertex::Atom((
10288690×
            crate::objects::oref(&a[0], "vertex")?,
10298690×
            crate::objects::u32_(&a[1], "vertex")?,
1030
        ))),
10310×
        _ => Err(ObjectError::Schema(
10320×
            "vertex: expected 0, 1, or [hash, index]".into(),
10330×
        )),
1034
    }
103510316×
}
1036
1037
impl FileGraph {
1038
    /// Serialize for a checkpoint: `{0: atoms [[hash, index, content|null, [deleters]]], 1: edges [[from, to]]}`.
10391465×
    pub fn to_value(&self) -> crate::cbor::Value {
1040
        use crate::cbor::Value;
10411465×
        let mut atoms: Vec<(&AtomKey, &AtomInfo)> = self.atoms.iter().collect();
10421465×
        atoms.sort_by_key(|(k, _)| **k);
10431465×
        let mut edges: Vec<(Vertex, Vertex)> = self
10441465×
            .succ
10451465×
            .iter()
104617432×
            .flat_map(|(a, bs)| bs.iter().map(move |b| (*a, *b)))
10471465×
            .collect();
10481465×
        edges.sort();
10491465×
        Value::map([
1050
            (
1051
                0,
1052
                Value::Array(
10531465×
                    atoms
10541465×
                        .into_iter()
105512772×
                        .map(|((c, i), info)| {
105612772×
                            Value::Array(vec![
105712772×
                                Value::Bytes(c.0.to_vec()),
105812772×
                                Value::Uint(*i as u64),
105912772×
                                info.content
106012772×
                                    .as_ref()
106112772×
                                    .map(|b| Value::Bytes(b.bytes().to_vec()))
106212772×
                                    .unwrap_or(Value::Null),
1063
                                Value::Array(
106412772×
                                    info.deleted_by
106512772×
                                        .iter()
106612772×
                                        .map(|d| Value::Bytes(d.0.to_vec()))
106712772×
                                        .collect(),
1068
                                ),
1069
                            ])
107012772×
                        })
10711465×
                        .collect(),
1072
                ),
1073
            ),
1074
            (
1075
                1,
1076
                Value::Array(
10771465×
                    edges
10781465×
                        .iter()
107917432×
                        .map(|(a, b)| Value::Array(vec![vertex_value(a), vertex_value(b)]))
10801465×
                        .collect(),
1081
                ),
1082
            ),
1083
        ])
10841465×
    }
1085
1086333×
    pub fn from_value(v: &crate::cbor::Value) -> Result<FileGraph, crate::objects::ObjectError> {
1087
        use crate::objects::{array, bytes, field, map, oref, u32_, ObjectError};
1088333×
        let m = map(v, "file graph")?;
1089333×
        let mut g = FileGraph {
1090333×
            atoms: HashMap::default(),
1091333×
            succ: HashMap::default(),
1092333×
            order: OrderSlot::default(),
1093333×
        };
1094333×
        let atoms = array(field(m, 0, "atoms")?, "atoms")?;
1095
        // Every atom's line in one buffer.
1096333×
        let mut texts: Vec<&[u8]> = Vec::new();
10974114×
        for a in atoms {
10984114×
            let e = array(a, "atom")?;
10994114×
            if e.len() == 4 && !e[2].is_null() {
11004114×
                texts.push(bytes(&e[2], "atom content")?);
11010×
            }
1102
        }
1103333×
        let all: Lines = texts.into_iter().collect();
1104333×
        let mut next = 0u32;
11054114×
        for a in atoms {
11064114×
            let e = array(a, "atom")?;
11074114×
            if e.len() != 4 {
11080×
                return Err(ObjectError::Schema("atom: expected 4 fields".into()));
11094114×
            }
11104114×
            let key = (oref(&e[0], "atom change")?, u32_(&e[1], "atom index")?);
11114114×
            let content = if e[2].is_null() {
11120×
                None
1113
            } else {
11144114×
                next += 1;
11154114×
                Some(LineRef::new(all.clone(), next - 1))
1116
            };
11174114×
            let deleted_by = array(&e[3], "deleters")?
11184114×
                .iter()
11194114×
                .map(|d| oref(d, "deleter"))
11204114×
                .collect::<Result<BTreeSet<_>, _>>()?;
11214114×
            g.atoms.insert(
11224114×
                key,
11234114×
                AtomInfo {
11244114×
                    content,
11254114×
                    deleted_by,
11264114×
                },
1127
            );
1128
        }
11295158×
        for e in array(field(m, 1, "edges")?, "edges")? {
11305158×
            let pair = array(e, "edge")?;
11315158×
            if pair.len() != 2 {
11320×
                return Err(ObjectError::Schema("edge: expected [from, to]".into()));
11335158×
            }
11345158×
            g.edge(vertex_from(&pair[0])?, vertex_from(&pair[1])?);
1135
        }
1136333×
        Ok(g)
1137333×
    }
1138
}
1139
1140
/// Split a plain run into `Lines` and `Zombie` segments around ghost atoms.
11411827×
fn split_zombies(atoms: Vec<AtomKey>, ghosts: &HashSet<AtomKey>) -> Vec<Segment> {
11421827×
    let mut out = Vec::new();
11431827×
    let mut lines: Vec<AtomKey> = Vec::new();
11441827×
    let mut i = 0;
11458251×
    while i < atoms.len() {
11466424×
        if !ghosts.contains(&atoms[i]) {
11475830×
            lines.push(atoms[i]);
11485830×
            i += 1;
11495830×
            continue;
1150594×
        }
1151594×
        if !lines.is_empty() {
1152372×
            out.push(Segment::Lines(std::mem::take(&mut lines)));
1153372×
        }
1154594×
        let mut deleted = Vec::new();
11551188×
        while i < atoms.len() && ghosts.contains(&atoms[i]) {
1156594×
            deleted.push(atoms[i]);
1157594×
            i += 1;
1158594×
        }
1159594×
        let mut inserted = Vec::new();
1160594×
        if i < atoms.len() {
1161526×
            let ch = atoms[i].0;
11621150×
            while i < atoms.len() && atoms[i].0 == ch && !ghosts.contains(&atoms[i]) {
1163624×
                inserted.push(atoms[i]);
1164624×
                i += 1;
1165624×
            }
116668×
        }
1167594×
        out.push(Segment::Zombie { deleted, inserted });
1168
    }
11691827×
    if !lines.is_empty() {
11701476×
        out.push(Segment::Lines(lines));
11711476×
    }
11721827×
    out
11731827×
}
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
}