1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
use std::collections::HashMap;

use fxhash::FxBuildHasher;

use super::{OpSet, OpTree};
use crate::{
    op_tree::OpTreeInternal,
    storage::load::{DocObserver, LoadedObject},
    types::ObjId,
};

/// An opset builder which creates an optree for each object as it finishes loading, inserting the
/// ops using `OpTreeInternal::insert`. This should be faster than using `OpSet::insert_*` but only
/// works because the ops in the document format are in the same order as in the optrees.
pub(crate) struct OpSetBuilder {
    completed_objects: HashMap<ObjId, OpTree, FxBuildHasher>,
}

impl OpSetBuilder {
    pub(crate) fn new() -> OpSetBuilder {
        Self {
            completed_objects: HashMap::default(),
        }
    }
}

impl DocObserver for OpSetBuilder {
    type Output = OpSet;

    fn object_loaded(&mut self, loaded: LoadedObject) {
        let mut internal = OpTreeInternal::new();
        for (index, op) in loaded.ops.into_iter().enumerate() {
            internal.insert(index, op);
        }
        let tree = OpTree {
            internal,
            objtype: loaded.obj_type,
            parent: loaded.parent,
            last_insert: None,
        };
        self.completed_objects.insert(loaded.id, tree);
    }

    fn finish(self, metadata: super::OpSetMetadata) -> Self::Output {
        let len = self.completed_objects.values().map(|t| t.len()).sum();
        OpSet {
            trees: self.completed_objects,
            length: len,
            m: metadata,
        }
    }
}