OXYGENHUB

Coverage / crates/oxy-core/src/objects.rs 94.4%

1065 of 1128 lines run, 223 of 298 functions · run #339 on proposal/124 · run missed

1
//! Typed objects and their canonical encodings (spec §6, §7, §13.2).
2
//!
3
//! Encoding conventions not fixed by the spec text are defined here:
4
//! - Enum-like items (`TreeOp`, `Edit`) are maps whose key 0 is the variant tag.
5
//! - An `OpRef`/atom reference is `[bytes32, uint]`; `AtomRef::Start` is `0`
6
//!   and `AtomRef::End` is `1`.
7
//! - A `Mode` is an unsigned integer: bit 0 = executable, bit 1 = opaque.
8
//! - `NodeKind`: 0 = file, 1 = dir, 2 = symlink.
9
10
use crate::cbor::{self, Value};
11
use crate::hash::{hash_object, ChangeHash, KeyId, ObjectRef, ObjectType};
12
use crate::ids::{ChangeId, NodeId};
13
use crate::lines::Lines;
14
use std::collections::BTreeMap;
15
16
pub const FORMAT_VERSION: u64 = 1;
17
18
/// The change format writers produce (spec §6.1). Version 2 stores each
19
/// large insert's lines as a text blob holding a CBOR array of them;
20
/// version 3 holds the lines' bytes themselves when splitting them by the
21
/// line rule gives them back. Readers accept 1 to 3, and a change keeps
22
/// the version it was made in, so its hash never moves.
23
pub const CHANGE_VERSION: u64 = 3;
24
25
/// How a text blob holds an insert's lines (spec §7.4).
26
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
27
pub enum TextForm {
28
    /// A CBOR array of the lines' byte strings: version 2.
29
    Cbor,
30
    /// The lines' bytes, split again by the line rule: version 3.
31
    Raw,
32
    /// A CBOR array in a version 3 change, for lines the line rule would
33
    /// not split back (marked by key 7): never for lines it would.
34
    CborFallback,
35
}
36
37
/// In a version 2 change, an insert whose lines encode (as a CBOR array of
38
/// byte strings) to at least this many bytes is stored as a text blob
39
/// holding exactly that encoding; a shorter one is inline (spec §6.1).
40
pub const TEXT_BLOB_MIN: usize = 4096;
41
42
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
43
pub enum ObjectError {
44
    #[error("cbor: {0}")]
45
    Cbor(#[from] cbor::CborError),
46
    #[error("schema: {0}")]
47
    Schema(String),
48
    /// A cache this repository derived and can derive again (a state
49
    /// index) does not match the hash it was written with.
50
    #[error("damaged index: {0}")]
51
    DamagedIndex(String),
52
}
53
5418×
pub(crate) fn schema<T>(msg: impl Into<String>) -> Result<T, ObjectError> {
5518×
    Err(ObjectError::Schema(msg.into()))
5618×
}
57
58
pub(crate) type Map = BTreeMap<u64, Value>;
59
60930052×
pub(crate) fn field<'a>(m: &'a Map, k: u64, what: &str) -> Result<&'a Value, ObjectError> {
61930052×
    m.get(&k)
62930052×
        .ok_or_else(|| ObjectError::Schema(format!("missing field {k} ({what})")))
63930052×
}
64380018×
pub(crate) fn uint(v: &Value, what: &str) -> Result<u64, ObjectError> {
65380018×
    v.as_uint()
66380018×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected unsigned integer")))
67380018×
}
6866578×
pub(crate) fn u32_(v: &Value, what: &str) -> Result<u32, ObjectError> {
6966578×
    u32::try_from(uint(v, what)?).map_err(|_| ObjectError::Schema(format!("{what}: exceeds u32")))
7066578×
}
71127191×
pub(crate) fn text<'a>(v: &'a Value, what: &str) -> Result<&'a str, ObjectError> {
72127191×
    v.as_text()
73127191×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected text")))
74127191×
}
75282429×
pub(crate) fn array<'a>(v: &'a Value, what: &str) -> Result<&'a [Value], ObjectError> {
76282429×
    v.as_array()
77282429×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected array")))
78282429×
}
79137132×
pub(crate) fn map<'a>(v: &'a Value, what: &str) -> Result<&'a Map, ObjectError> {
80137132×
    v.as_map()
81137132×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected map")))
82137132×
}
83414294×
pub(crate) fn bytes<'a>(v: &'a Value, what: &str) -> Result<&'a [u8], ObjectError> {
84414294×
    v.as_bytes()
85414294×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected bytes")))
86414294×
}
87135814×
pub(crate) fn oref(v: &Value, what: &str) -> Result<ObjectRef, ObjectError> {
88135814×
    ObjectRef::from_slice(bytes(v, what)?)
89135813×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected 32 bytes")))
90135814×
}
91149763×
pub(crate) fn node_id(v: &Value, what: &str) -> Result<NodeId, ObjectError> {
92149763×
    NodeId::from_slice(bytes(v, what)?)
93149763×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected 16 bytes")))
94149763×
}
9528496×
pub(crate) fn check_version(m: &Map) -> Result<(), ObjectError> {
9628496×
    let v = uint(field(m, 0, "version")?, "version")?;
9728496×
    if v != FORMAT_VERSION {
980×
        let exe = std::env::current_exe()
990×
            .map(|p| format!(" at {}", p.display()))
1000×
            .unwrap_or_default();
1010×
        let which = format!("oxy {}{exe}", crate::VERSION);
1020×
        return schema(if v > FORMAT_VERSION {
1030×
            format!(
104
                "this data is format {v}, written by a newer oxy, and {which} reads format {FORMAT_VERSION}: install the current oxy, and check that no older copy comes first on PATH"
105
            )
106
        } else {
1070×
            format!(
108
                "this data is format {v}, written by an older oxy, and {which} reads format {FORMAT_VERSION} only"
109
            )
110
        });
11128496×
    }
11228496×
    Ok(())
11328496×
}
114
115
// ---------------------------------------------------------------- Hlc
116
117
/// Hybrid logical clock (spec §6.4).
118
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
119
pub struct Hlc {
120
    pub wall_ms: u64,
121
    pub logical: u32,
122
}
123
124
impl Hlc {
1256264×
    pub fn now() -> Hlc {
1266264×
        let wall_ms = std::time::SystemTime::now()
1276264×
            .duration_since(std::time::UNIX_EPOCH)
1286264×
            .map(|d| d.as_millis() as u64)
1296264×
            .unwrap_or(0);
1306264×
        Hlc {
1316264×
            wall_ms,
1326264×
            logical: 0,
1336264×
        }
1346264×
    }
13512031×
    pub(crate) fn to_value(self) -> Value {
13612031×
        Value::map([
13712031×
            (0, Value::Uint(self.wall_ms)),
13812031×
            (1, Value::Uint(self.logical as u64)),
13912031×
        ])
14012031×
    }
14135870×
    pub(crate) fn from_value(v: &Value) -> Result<Hlc, ObjectError> {
14235870×
        let m = map(v, "hlc")?;
143
        Ok(Hlc {
14435870×
            wall_ms: uint(field(m, 0, "hlc.wall_ms")?, "hlc.wall_ms")?,
14535870×
            logical: u32_(field(m, 1, "hlc.logical")?, "hlc.logical")?,
146
        })
14735870×
    }
148
}
149
150
// ---------------------------------------------------------------- tree
151
152
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
153
pub enum NodeKind {
154
    File,
155
    Dir,
156
    Symlink,
157
    /// A nested repository pinned to a state (spec §7.8); content is a pin.
158
    Subrepo,
159
}
160
161
impl NodeKind {
16273771×
    pub(crate) fn tag(self) -> u64 {
16373771×
        match self {
16472754×
            NodeKind::File => 0,
165993×
            NodeKind::Dir => 1,
1663×
            NodeKind::Symlink => 2,
16721×
            NodeKind::Subrepo => 3,
168
        }
16973771×
    }
17097953×
    pub(crate) fn from_tag(t: u64) -> Result<NodeKind, ObjectError> {
17197953×
        Ok(match t {
17295840×
            0 => NodeKind::File,
1732006×
            1 => NodeKind::Dir,
1749×
            2 => NodeKind::Symlink,
17598×
            3 => NodeKind::Subrepo,
1760×
            _ => return schema(format!("unknown node kind {t}")),
177
        })
17897953×
    }
179
}
180
181
/// Executable bit plus content mode (spec §7.1, §7.5).
182
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PartialOrd, Ord)]
183
pub struct Mode {
184
    pub exec: bool,
185
    pub opaque: bool,
186
}
187
188
impl Mode {
189
    pub const TEXT: Mode = Mode {
190
        exec: false,
191
        opaque: false,
192
    };
193
    pub const OPAQUE: Mode = Mode {
194
        exec: false,
195
        opaque: true,
196
    };
19773388×
    pub(crate) fn bits(self) -> u64 {
19873388×
        (self.exec as u64) | ((self.opaque as u64) << 1)
19973388×
    }
20097912×
    pub(crate) fn from_bits(b: u64) -> Result<Mode, ObjectError> {
20197912×
        if b > 3 {
2021×
            return schema(format!("unknown mode bits {b}"));
20397911×
        }
20497911×
        Ok(Mode {
20597911×
            exec: b & 1 != 0,
20697911×
            opaque: b & 2 != 0,
20797911×
        })
20897912×
    }
209
}
210
211
/// Reference to a tree operation of some change: the placement or mode atom it
212
/// introduced. `change == ObjectRef::ZERO` means this change.
213
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
214
pub struct OpRef {
215
    pub change: ChangeHash,
216
    pub index: u32,
217
}
218
219
impl OpRef {
220430×
    fn to_value(self) -> Value {
221430×
        Value::Array(vec![
222430×
            Value::Bytes(self.change.0.to_vec()),
223430×
            Value::Uint(self.index as u64),
224430×
        ])
225430×
    }
226800×
    fn from_value(v: &Value, what: &str) -> Result<OpRef, ObjectError> {
227800×
        let a = array(v, what)?;
228800×
        if a.len() != 2 {
2290×
            return schema(format!("{what}: expected [hash, index]"));
230800×
        }
231
        Ok(OpRef {
232800×
            change: oref(&a[0], what)?,
233800×
            index: u32_(&a[1], what)?,
234
        })
235800×
    }
236
    /// Replace a self reference with the concrete change hash.
237765×
    pub fn resolve(self, me: ChangeHash) -> OpRef {
238765×
        if self.change.is_zero() {
2391×
            OpRef { change: me, ..self }
240
        } else {
241764×
            self
242
        }
243765×
    }
244
}
245
246
#[derive(Debug, Clone, PartialEq, Eq)]
247
pub enum TreeOp {
248
    AddNode {
249
        node: NodeId,
250
        kind: NodeKind,
251
        mode: Mode,
252
        parent: NodeId,
253
        name: String,
254
    },
255
    RemoveNode {
256
        node: NodeId,
257
        placement: OpRef,
258
    },
259
    Move {
260
        node: NodeId,
261
        old: OpRef,
262
        parent: NodeId,
263
        name: String,
264
    },
265
    SetMode {
266
        node: NodeId,
267
        old: OpRef,
268
        mode: Mode,
269
    },
270
}
271
272
/// Names must be valid, non-empty, not `.`/`..`, and free of `/` and NUL (spec §7.1).
27347709×
pub fn validate_name(name: &str) -> Result<(), ObjectError> {
27447709×
    if name.is_empty() || name == "." || name == ".." || name.contains('/') || name.contains('\0') {
2756×
        return schema(format!("invalid placement name {name:?}"));
27647703×
    }
27747703×
    Ok(())
27847709×
}
279
280
impl TreeOp {
281104×
    pub fn node(&self) -> NodeId {
282104×
        match self {
28381×
            TreeOp::AddNode { node, .. }
28411×
            | TreeOp::RemoveNode { node, .. }
28511×
            | TreeOp::Move { node, .. }
286104×
            | TreeOp::SetMode { node, .. } => *node,
287
        }
288104×
    }
289
2906237×
    fn to_value(&self) -> Value {
29112075×
        let nid = |n: &NodeId| Value::Bytes(n.0.to_vec());
2926237×
        match self {
293
            TreeOp::AddNode {
2945807×
                node,
2955807×
                kind,
2965807×
                mode,
2975807×
                parent,
2985807×
                name,
2995807×
            } => Value::map([
3005807×
                (0, Value::Uint(0)),
3015807×
                (1, nid(node)),
3025807×
                (2, Value::Uint(kind.tag())),
3035807×
                (3, Value::Uint(mode.bits())),
3045807×
                (4, nid(parent)),
3055807×
                (5, Value::Text(name.clone())),
3065807×
            ]),
307332×
            TreeOp::RemoveNode { node, placement } => Value::map([
308332×
                (0, Value::Uint(1)),
309332×
                (1, nid(node)),
310332×
                (2, placement.to_value()),
311332×
            ]),
312
            TreeOp::Move {
31331×
                node,
31431×
                old,
31531×
                parent,
31631×
                name,
31731×
            } => Value::map([
31831×
                (0, Value::Uint(2)),
31931×
                (1, nid(node)),
32031×
                (2, old.to_value()),
32131×
                (4, nid(parent)),
32231×
                (5, Value::Text(name.clone())),
32331×
            ]),
32467×
            TreeOp::SetMode { node, old, mode } => Value::map([
32567×
                (0, Value::Uint(3)),
32667×
                (1, nid(node)),
32767×
                (2, old.to_value()),
32867×
                (3, Value::Uint(mode.bits())),
32967×
            ]),
330
        }
3316237×
    }
332
33348323×
    fn from_value(v: &Value) -> Result<TreeOp, ObjectError> {
33448323×
        let m = map(v, "tree_op")?;
33548323×
        let tag = uint(field(m, 0, "tree_op tag")?, "tree_op tag")?;
33648323×
        let node = node_id(field(m, 1, "tree_op.node")?, "tree_op.node")?;
33748323×
        let op = match tag {
338
            0 => {
33947523×
                let name = text(field(m, 5, "name")?, "name")?.to_owned();
34047523×
                validate_name(&name)?;
341
                TreeOp::AddNode {
34247523×
                    node,
34347523×
                    kind: NodeKind::from_tag(uint(field(m, 2, "kind")?, "kind")?)?,
34447523×
                    mode: Mode::from_bits(uint(field(m, 3, "mode")?, "mode")?)?,
34547523×
                    parent: node_id(field(m, 4, "parent")?, "parent")?,
34647523×
                    name,
347
                }
348
            }
349
            1 => TreeOp::RemoveNode {
350594×
                node,
351594×
                placement: OpRef::from_value(field(m, 2, "placement")?, "placement")?,
352
            },
353
            2 => {
354167×
                let name = text(field(m, 5, "name")?, "name")?.to_owned();
355167×
                validate_name(&name)?;
356
                TreeOp::Move {
357167×
                    node,
358167×
                    old: OpRef::from_value(field(m, 2, "old")?, "old")?,
359167×
                    parent: node_id(field(m, 4, "parent")?, "parent")?,
360167×
                    name,
361
                }
362
            }
363
            3 => TreeOp::SetMode {
36439×
                node,
36539×
                old: OpRef::from_value(field(m, 2, "old")?, "old")?,
36639×
                mode: Mode::from_bits(uint(field(m, 3, "mode")?, "mode")?)?,
367
            },
3680×
            _ => return schema(format!("unknown tree op tag {tag}")),
369
        };
37048323×
        if node.is_root() {
3710×
            return schema("tree op on the root node");
37248323×
        }
37348323×
        Ok(op)
37448323×
    }
375
}
376
377
// ---------------------------------------------------------------- edits
378
379
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
380
pub enum AtomRef {
381
    Start,
382
    End,
383
    Atom { change: ChangeHash, index: u32 },
384
}
385
386
impl AtomRef {
38714702×
    fn to_value(self) -> Value {
38814702×
        match self {
3895345×
            AtomRef::Start => Value::Uint(0),
3905594×
            AtomRef::End => Value::Uint(1),
3913763×
            AtomRef::Atom { change, index } => Value::Array(vec![
3923763×
                Value::Bytes(change.0.to_vec()),
3933763×
                Value::Uint(index as u64),
3943763×
            ]),
395
        }
39614702×
    }
39799930×
    fn from_value(v: &Value, what: &str) -> Result<AtomRef, ObjectError> {
3987834×
        match v {
39945243×
            Value::Uint(0) => Ok(AtomRef::Start),
40046853×
            Value::Uint(1) => Ok(AtomRef::End),
4017834×
            Value::Array(a) if a.len() == 2 => Ok(AtomRef::Atom {
4027834×
                change: oref(&a[0], what)?,
4037834×
                index: u32_(&a[1], what)?,
404
            }),
4050×
            _ => schema(format!("{what}: expected atom reference")),
406
        }
40799930×
    }
40861976×
    pub fn resolve(self, me: ChangeHash) -> AtomRef {
4098526×
        match self {
4108526×
            AtomRef::Atom { change, index } if change.is_zero() => {
41134×
                AtomRef::Atom { change: me, index }
412
            }
41361942×
            other => other,
414
        }
41561976×
    }
416
}
417
418
/// Half-open range of atoms introduced by one change.
419
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
420
pub struct AtomRange {
421
    pub change: ChangeHash,
422
    pub from: u32,
423
    pub to: u32,
424
}
425
426
impl AtomRange {
4272374×
    fn to_value(self) -> Value {
4282374×
        Value::Array(vec![
4292374×
            Value::Bytes(self.change.0.to_vec()),
4302374×
            Value::Uint(self.from as u64),
4312374×
            Value::Uint(self.to as u64),
4322374×
        ])
4332374×
    }
4343892×
    fn from_value(v: &Value) -> Result<AtomRange, ObjectError> {
4353892×
        let a = array(v, "atom range")?;
4363892×
        if a.len() != 3 {
4370×
            return schema("atom range: expected [hash, from, to]");
4383892×
        }
4393892×
        let r = AtomRange {
4403892×
            change: oref(&a[0], "range.change")?,
4413892×
            from: u32_(&a[1], "range.from")?,
4423892×
            to: u32_(&a[2], "range.to")?,
443
        };
4443892×
        if r.from >= r.to {
4450×
            return schema("atom range: empty or inverted");
4463892×
        }
4473892×
        Ok(r)
4483892×
    }
4494285×
    pub fn resolve(self, me: ChangeHash) -> AtomRange {
4504285×
        if self.change.is_zero() {
45118×
            AtomRange { change: me, ..self }
452
        } else {
4534267×
            self
454
        }
4554285×
    }
456
}
457
458
#[derive(Debug, Clone, PartialEq, Eq)]
459
pub enum Edit {
460
    Insert {
461
        node: NodeId,
462
        after: AtomRef,
463
        before: AtomRef,
464
        lines: crate::lines::Lines,
465
    },
466
    Delete {
467
        node: NodeId,
468
        atoms: Vec<AtomRange>,
469
    },
470
    Replace {
471
        node: NodeId,
472
        old: Option<ObjectRef>,
473
        new: Option<ObjectRef>,
474
    },
475
}
476
477
impl Edit {
47847135×
    pub fn node(&self) -> NodeId {
47947135×
        match self {
48043893×
            Edit::Insert { node, .. } | Edit::Delete { node, .. } | Edit::Replace { node, .. } => {
48147135×
                *node
482
            }
483
        }
48447135×
    }
485
486
    /// Whether this insert is stored as a text blob in a change of `version`.
4879514×
    fn stored_text(&self, version: u64) -> bool {
4887354×
        matches!(self, Edit::Insert { lines, .. }
4897354×
            if version >= 2 && cbor::byte_strings_len(lines) >= TEXT_BLOB_MIN)
4909514×
    }
491
492
    /// The edit's value; `stored` is the text blob of an insert stored as
493
    /// one, and its form (see [`Change::value_with`], which works them out).
494
    /// The edit's value; `compact` writes an inline insert's lines as
495
    /// their encoding rather than a value per line (same bytes encoded).
4969507×
    fn to_value(&self, stored: Option<(ObjectRef, TextForm)>, compact: bool) -> Value {
4979507×
        let nid = |n: &NodeId| Value::Bytes(n.0.to_vec());
4989507×
        let opt = |o: &Option<ObjectRef>| match o {
499185×
            Some(r) => Value::Bytes(r.0.to_vec()),
500123×
            None => Value::Null,
501308×
        };
5029507×
        match (self, stored) {
503
            (
504
                Edit::Insert {
50573×
                    node,
50673×
                    after,
50773×
                    before,
50873×
                    lines,
509
                },
51073×
                Some((r, form)),
511
            ) => {
51273×
                let mut fields = vec![
51373×
                    (0, Value::Uint(0)),
51473×
                    (1, nid(node)),
51573×
                    (2, after.to_value()),
51673×
                    (3, before.to_value()),
51773×
                    (5, Value::Bytes(r.0.to_vec())),
51873×
                    (6, Value::Uint(lines.len() as u64)),
519
                ];
52073×
                if form == TextForm::CborFallback {
5211×
                    fields.push((7, Value::Uint(1)));
52272×
                }
52373×
                Value::map(fields)
524
            }
525
            (
526
                Edit::Insert {
5277278×
                    node,
5287278×
                    after,
5297278×
                    before,
5307278×
                    lines,
531
                },
532
                None,
5337278×
            ) => Value::map([
5347278×
                (0, Value::Uint(0)),
5357278×
                (1, nid(node)),
5367278×
                (2, after.to_value()),
5377278×
                (3, before.to_value()),
538
                (
539
                    4,
5407278×
                    if compact {
5417272×
                        Value::Encoded(cbor::encode_byte_strings(lines))
542
                    } else {
5431008×
                        Value::Array(lines.iter().map(|l| Value::Bytes(l.to_vec())).collect())
544
                    },
545
                ),
546
            ]),
5472002×
            (Edit::Delete { node, atoms }, _) => Value::map([
5482002×
                (0, Value::Uint(1)),
5492002×
                (1, nid(node)),
550
                (
551
                    2,
5522374×
                    Value::Array(atoms.iter().map(|r| r.to_value()).collect()),
553
                ),
554
            ]),
555154×
            (Edit::Replace { node, old, new }, _) => Value::map([
556154×
                (0, Value::Uint(2)),
557154×
                (1, nid(node)),
558154×
                (2, opt(old)),
559154×
                (3, opt(new)),
560154×
            ]),
561
        }
5629507×
    }
563
5647916×
    fn from_value(v: &Value, version: u64, resolve: &mut Resolver) -> Result<Edit, ObjectError> {
5657916×
        let m = map(v, "edit")?;
5667916×
        let tag = uint(field(m, 0, "edit tag")?, "edit tag")?;
5677916×
        let node = node_id(field(m, 1, "edit.node")?, "edit.node")?;
5687916×
        let opt = |v: &Value, what: &str| -> Result<Option<ObjectRef>, ObjectError> {
5691610×
            if v.is_null() {
570706×
                Ok(None)
571
            } else {
572904×
                Ok(Some(oref(v, what)?))
573
            }
5741610×
        };
5757916×
        Ok(match tag {
576
            0 => {
5774134×
                let lines = match (m.get(&4), m.get(&5)) {
5783868×
                    (Some(inline), None) => {
5793868×
                        let lines = array_lines(inline)?;
5803868×
                        if version >= 2 && cbor::byte_strings_len(&lines) >= TEXT_BLOB_MIN {
5811×
                            return schema("an insert this large is stored as a text blob in a version 2 change");
5823867×
                        }
5833867×
                        if lines.is_empty() {
5840×
                            return schema("insert with no lines");
5853867×
                        }
5863867×
                        lines
587
                    }
588266×
                    (None, Some(text)) if version >= 2 => {
589266×
                        let text = oref(text, "insert text")?;
590266×
                        let count = u32_(field(m, 6, "insert line count")?, "insert line count")?;
591266×
                        if count == 0 {
5920×
                            return schema("insert with no lines");
593266×
                        }
594266×
                        let form = match (version, m.get(&7)) {
5951×
                            (2, None) => TextForm::Cbor,
596264×
                            (_, None) => TextForm::Raw,
5971×
                            (3.., Some(Value::Uint(1))) => TextForm::CborFallback,
5980×
                            _ => return schema("unknown text blob form"),
599
                        };
600
                        // The resolver checks the count (`text_lines`).
601266×
                        resolve(&text, count, form)?
602
                    }
603
                    _ => {
6040×
                        return schema(
605
                            "an insert has either its lines or, in a version 2 change, a text blob",
606
                        )
607
                    }
608
                };
609
                Edit::Insert {
6104131×
                    node,
6114131×
                    after: AtomRef::from_value(field(m, 2, "after")?, "after")?,
6124131×
                    before: AtomRef::from_value(field(m, 3, "before")?, "before")?,
6134131×
                    lines,
614
                }
615
            }
616
            1 => {
6172977×
                let atoms = array(field(m, 2, "atoms")?, "atoms")?
6182977×
                    .iter()
6192977×
                    .map(AtomRange::from_value)
6202977×
                    .collect::<Result<Vec<_>, _>>()?;
6212977×
                if atoms.is_empty() {
6220×
                    return schema("delete with no atoms");
6232977×
                }
6242977×
                Edit::Delete { node, atoms }
625
            }
626
            2 => Edit::Replace {
627805×
                node,
628805×
                old: opt(field(m, 2, "old")?, "old")?,
629805×
                new: opt(field(m, 3, "new")?, "new")?,
630
            },
6310×
            _ => return schema(format!("unknown edit tag {tag}")),
632
        })
6337916×
    }
634
}
635
636
// ---------------------------------------------------------------- change
637
638
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
639
pub enum ChangeKind {
640
    Normal,
641
    Resolution,
642
    WorkingCopy,
643
}
644
645
impl ChangeKind {
64616566×
    pub(crate) fn tag(self) -> u64 {
64716566×
        match self {
64813981×
            ChangeKind::Normal => 0,
64941×
            ChangeKind::Resolution => 1,
6502544×
            ChangeKind::WorkingCopy => 2,
651
        }
65216566×
    }
65328951×
    pub(crate) fn from_tag(t: u64) -> Result<ChangeKind, ObjectError> {
65428951×
        Ok(match t {
65525939×
            0 => ChangeKind::Normal,
656120×
            1 => ChangeKind::Resolution,
6572892×
            2 => ChangeKind::WorkingCopy,
6580×
            _ => return schema(format!("unknown change kind {t}")),
659
        })
66028951×
    }
661
}
662
663
/// A change (spec §6.1). `deps` is kept sorted and unique by `normalize`.
664
#[derive(Debug, Clone, PartialEq, Eq)]
665
pub struct Change {
666
    /// The format this change is encoded in: [`CHANGE_VERSION`] for a new
667
    /// one, whatever it was made in for one read back.
668
    pub version: u64,
669
    pub change_id: ChangeId,
670
    pub deps: Vec<ChangeHash>,
671
    pub author: KeyId,
672
    pub hlc: Hlc,
673
    pub message: String,
674
    pub tree_ops: Vec<TreeOp>,
675
    pub edits: Vec<Edit>,
676
    pub kind: ChangeKind,
677
}
678
679
impl Change {
6805831×
    pub fn normalize(&mut self) {
6815831×
        self.deps.sort();
6825831×
        self.deps.dedup();
6835831×
    }
684
6856×
    pub fn to_value(&self) -> Value {
6866×
        self.value_with(&mut |_| true, false)
6876×
    }
688
689
    /// The text blob of each edit stored as one, `None` for the others;
690
    /// the stored texts go to `texts`, in order, when it is given. Worked
691
    /// out on every core, a bounded batch at a time: chunking and hashing
692
    /// a whole tree's text is most of encoding a change that adds it.
6937821×
    fn stored_texts(&self, sink: &mut TextSink) -> Vec<Option<(ObjectRef, TextForm)>> {
694
        use rayon::prelude::*;
6957821×
        let mut refs: Vec<Option<(ObjectRef, TextForm)>> = vec![None; self.edits.len()];
6967821×
        let stored: Vec<usize> = (0..self.edits.len())
6979507×
            .filter(|i| self.edits[*i].stored_text(self.version))
6987821×
            .collect();
699
        // At most 256 texts or 32 MiB of them a batch: some directories
700
        // hold hundreds of generated files of megabytes each, and a batch
701
        // is copied and compressed at once.
7027821×
        let mut batches: Vec<&[usize]> = Vec::new();
7037821×
        let (mut start, mut bytes) = (0, 0usize);
7047821×
        for (k, i) in stored.iter().enumerate() {
70573×
            if let Edit::Insert { lines, .. } = &self.edits[*i] {
70673×
                bytes += lines.bytes().len();
70773×
            }
70873×
            if k + 1 - start == 256 || bytes >= 32 << 20 {
7090×
                batches.push(&stored[start..=k]);
7100×
                (start, bytes) = (k + 1, 0);
71173×
            }
712
        }
7137821×
        if start < stored.len() {
71472×
            batches.push(&stored[start..]);
7157749×
        }
7167821×
        for batch in batches {
71772×
            let made: Vec<StoredText> = batch
71872×
                .par_iter()
71973×
                .map(|i| {
72073×
                    let Edit::Insert { lines, .. } = &self.edits[*i] else {
7210×
                        unreachable!("only inserts are stored as text");
722
                    };
72373×
                    let form = text_form(self.version, lines);
72473×
                    let content = match form {
72571×
                        TextForm::Raw => lines.bytes().to_vec(),
7262×
                        TextForm::Cbor | TextForm::CborFallback => cbor::encode_byte_strings(lines),
727
                    };
72873×
                    StoredText {
72973×
                        blob: Blob::of(&content),
73073×
                        content,
73173×
                        form,
73273×
                    }
73373×
                })
73472×
                .collect();
73573×
            for (i, t) in batch.iter().zip(&made) {
73673×
                refs[*i] = Some((t.blob.hash(), t.form));
73773×
            }
73872×
            if !sink(made) {
7390×
                break;
74072×
            }
741
        }
7427821×
        refs
7437821×
    }
744
745
    /// The change's value, its stored texts handed to `sink`; `compact`
746
    /// as [`Edit::to_value`] takes it, for a value that is only encoded.
7477821×
    fn value_with(&self, sink: &mut TextSink, compact: bool) -> Value {
7487821×
        Value::map([
7497821×
            (0, Value::Uint(self.version)),
7507821×
            (1, Value::Bytes(self.change_id.0.to_vec())),
751
            (
752
                2,
753
                Value::Array(
7547821×
                    self.deps
7557821×
                        .iter()
7569263×
                        .map(|d| Value::Bytes(d.0.to_vec()))
7577821×
                        .collect(),
758
                ),
759
            ),
7607821×
            (3, Value::Bytes(self.author.0.to_vec())),
7617821×
            (4, self.hlc.to_value()),
7627821×
            (5, Value::Text(self.message.clone())),
763
            (
764
                6,
7657821×
                Value::Array(self.tree_ops.iter().map(|t| t.to_value()).collect()),
766
            ),
767
            (
768
                7,
769
                Value::Array(
7707821×
                    self.edits
7717821×
                        .iter()
7727821×
                        .zip(self.stored_texts(sink))
7739507×
                        .map(|(e, stored)| e.to_value(stored, compact))
7747821×
                        .collect(),
775
                ),
776
            ),
7777821×
            (8, Value::Uint(self.kind.tag())),
7787821×
            (9, Value::Map(BTreeMap::new())),
779
        ])
7807821×
    }
781
7823911×
    pub fn encode(&self) -> Vec<u8> {
7833911×
        debug_assert!(
7843911×
            self.deps.windows(2).all(|w| w[0] < w[1]),
785
            "deps must be normalized"
786
        );
7873911×
        cbor::encode(&self.value_with(&mut |_| true, true))
7883911×
    }
789
790
    /// The encoding and the text blobs its large inserts are stored as,
791
    /// which must be stored with it.
792120×
    pub fn encode_parts(&self) -> (Vec<u8>, Vec<StoredText>) {
793120×
        debug_assert!(
794120×
            self.deps.windows(2).all(|w| w[0] < w[1]),
795
            "deps must be normalized"
796
        );
797120×
        let mut texts = Vec::new();
798120×
        let bytes = cbor::encode(&self.value_with(
7995×
            &mut |batch| {
8005×
                texts.extend(batch);
8015×
                true
8025×
            },
803
            true,
804
        ));
805120×
        (bytes, texts)
806120×
    }
807
808
    /// The encoding, handing the stored texts to `store` a batch at a time
809
    /// as they are made, so a change adding a whole tree never holds all
810
    /// its text twice. The first error from `store` is returned.
8113784×
    pub fn encode_streaming<E>(
8123784×
        &self,
8133784×
        mut store: impl FnMut(Vec<StoredText>) -> Result<(), E>,
8143784×
    ) -> Result<Vec<u8>, E> {
8153784×
        debug_assert!(
8163784×
            self.deps.windows(2).all(|w| w[0] < w[1]),
817
            "deps must be normalized"
818
        );
8193784×
        let mut failed = None;
8203784×
        let value = self.value_with(
82162×
            &mut |batch| match store(batch) {
82262×
                Ok(()) => true,
8230×
                Err(e) => {
8240×
                    failed = Some(e);
8250×
                    false
826
                }
82762×
            },
828
            true,
829
        );
8303784×
        match failed {
8310×
            Some(e) => Err(e),
8323784×
            None => Ok(cbor::encode(&value)),
833
        }
8343784×
    }
835
836
    /// Whether any insert is stored as a text blob.
8373×
    pub fn has_stored_text(&self) -> bool {
8387×
        self.edits.iter().any(|e| e.stored_text(self.version))
8393×
    }
840
8413904×
    pub fn hash(&self) -> ChangeHash {
8423904×
        hash_object(ObjectType::Change, &self.encode())
8433904×
    }
844
845
    /// Decode a change that stores no text blob; one that does needs
846
    /// [`Change::decode_with`] and something to read them from.
8474×
    pub fn decode(bytes: &[u8]) -> Result<Change, ObjectError> {
8484×
        Self::decode_with(bytes, &mut |r, _, _| {
8491×
            schema(format!(
850
                "text blob {} needs a store to read it from",
8511×
                r.short(12)
852
            ))
8531×
        })
8544×
    }
855
856
    /// Decode a change, reading each stored insert's lines with `resolve`
857
    /// (given the text blob and the line count the insert claims).
8585456×
    pub fn decode_with(bytes: &[u8], resolve: &mut Resolver) -> Result<Change, ObjectError> {
8595456×
        let v = cbor::decode(bytes)?;
8605456×
        Self::from_value_with(&v, resolve)
8615456×
    }
862
86311361×
    pub fn from_value(v: &Value) -> Result<Change, ObjectError> {
86411361×
        Self::from_value_with(v, &mut |r, _, _| {
8650×
            schema(format!(
866
                "text blob {} needs a store to read it from",
8670×
                r.short(12)
868
            ))
8690×
        })
87011361×
    }
871
87216817×
    pub(crate) fn from_value_with(
87316817×
        v: &Value,
87416817×
        resolve: &mut Resolver,
87516817×
    ) -> Result<Change, ObjectError> {
87616817×
        let m = map(v, "change")?;
87716817×
        let version = uint(field(m, 0, "version")?, "version")?;
87816817×
        if !(1..=CHANGE_VERSION).contains(&version) {
8791×
            return schema(format!("unsupported change format version {version}"));
88016816×
        }
88116816×
        let change_id = ChangeId::from_slice(bytes(field(m, 1, "change_id")?, "change_id")?)
88216816×
            .ok_or_else(|| ObjectError::Schema("change_id: expected 16 bytes".into()))?;
88316816×
        let deps = array(field(m, 2, "deps")?, "deps")?
88416816×
            .iter()
88516816×
            .map(|d| oref(d, "dep"))
88616816×
            .collect::<Result<Vec<_>, _>>()?;
88716816×
        if !deps.windows(2).all(|w| w[0] < w[1]) {
8881×
            return schema("deps must be sorted and unique");
88916815×
        }
89016815×
        if deps.iter().any(|d| d.is_zero()) {
8910×
            return schema("deps may not contain the self reference");
89216815×
        }
89316815×
        let extra = map(field(m, 9, "extra")?, "extra")?;
89416815×
        if !extra.is_empty() {
8951×
            return schema("extra must be empty in format version 1");
89616814×
        }
897
        Ok(Change {
89816814×
            version,
89916814×
            change_id,
90016814×
            deps,
90116814×
            author: oref(field(m, 3, "author")?, "author")?,
90216814×
            hlc: Hlc::from_value(field(m, 4, "hlc")?)?,
90316814×
            message: text(field(m, 5, "message")?, "message")?.to_owned(),
90416814×
            tree_ops: array(field(m, 6, "tree_ops")?, "tree_ops")?
90516814×
                .iter()
90616814×
                .map(TreeOp::from_value)
90716814×
                .collect::<Result<Vec<_>, _>>()?,
90816814×
            edits: array(field(m, 7, "edits")?, "edits")?
90916814×
                .iter()
91016814×
                .map(|e| Edit::from_value(e, version, resolve))
91116814×
                .collect::<Result<Vec<_>, _>>()?,
91216811×
            kind: ChangeKind::from_tag(uint(field(m, 8, "kind")?, "kind")?)?,
913
        })
91416817×
    }
915
}
916
917
/// Reads a stored insert's lines, given the text blob and the line count
918
/// the insert claims; [`text_lines`] reads and checks a blob's content.
919
/// A resolver may also return no lines, leaving a placeholder for a reader
920
/// that fills it in later (history-only states, spec §11).
921
pub type Resolver<'a> = dyn FnMut(&ObjectRef, u32, TextForm) -> Result<Lines, ObjectError> + 'a;
922
923
/// Receives the stored texts of a change being encoded, a batch at a
924
/// time; returns false to stop making more.
925
type TextSink<'a> = dyn FnMut(Vec<StoredText>) -> bool + 'a;
926
927
/// Where a history-only load finds an insert's lines when it builds that
928
/// file's graph (spec §11): it keeps no line until then.
929
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
930
pub enum TextRef {
931
    /// A stored insert: its text blob, line count, and the blob's form.
932
    Blob(ObjectRef, u32, TextForm),
933
    /// An inline insert: the byte range of its lines' array in the
934
    /// encoding of `change`.
935
    Inline {
936
        change: ChangeHash,
937
        start: u32,
938
        end: u32,
939
    },
940
}
941
942
/// The lines of an inline insert from its array's bytes (see
943
/// [`TextRef::Inline`]).
94431435×
pub fn inline_lines(array: &[u8]) -> Result<Lines, ObjectError> {
94531435×
    let v = cbor::decode(array)?;
94631435×
    let lines = array_lines(&v)?;
94731435×
    if lines.is_empty() {
9480×
        return schema("insert with no lines");
94931435×
    }
95031435×
    Ok(lines)
95131435×
}
952
953
/// The lines of a CBOR array of byte strings, copied once into one buffer.
95435309×
fn array_lines(v: &Value) -> Result<Lines, ObjectError> {
95535309×
    Ok(array(v, "lines")?
95635309×
        .iter()
95757481×
        .map(|l| bytes(l, "line"))
95835309×
        .collect::<Result<Vec<&[u8]>, _>>()?
95935309×
        .into_iter()
96035309×
        .collect())
96135309×
}
962
963
impl Change {
964
    /// Decode a change for a history-only state (spec §11): every insert is
965
    /// left without its lines (an empty placeholder), and the result says
966
    /// where each one's lines are, in order. The inline lines are stepped
967
    /// over, not decoded: for a change that adds a whole tree, most of its
968
    /// bytes. `me` is the change's hash.
9698275×
    pub fn decode_skeleton(
9708275×
        bytes: &[u8],
9718275×
        me: ChangeHash,
9728275×
    ) -> Result<(Change, Vec<TextRef>), ObjectError> {
9738275×
        let mut c = cbor::Cursor::new(bytes);
9748275×
        let (major, n) = c.head()?;
9758275×
        if major != 5 {
9760×
            return schema("change: expected map");
9778275×
        }
9788275×
        let mut fields = Map::new();
9798275×
        let mut edits = Vec::new();
9808275×
        let mut texts = Vec::new();
9818275×
        let mut version = None;
9828275×
        let mut last: Option<u64> = None;
9838275×
        for _ in 0..n {
98482748×
            let k = map_key(&mut c, &mut last)?;
98582748×
            if k == 7 {
9868275×
                let Some(v) = version else {
9870×
                    return schema("change: version must come first");
988
                };
9898275×
                let (am, an) = c.head()?;
9908275×
                if am != 4 {
9910×
                    return schema("edits: expected array");
9928275×
                }
9938275×
                for _ in 0..an {
99448733×
                    edits.push(edit_skeleton(&mut c, v, me, &mut texts)?);
995
                }
9968274×
                fields.insert(7, Value::Array(Vec::new()));
997
            } else {
99874473×
                let val = c.value()?;
99974473×
                if k == 0 {
10008275×
                    version = Some(uint(&val, "version")?);
100166198×
                }
100274473×
                fields.insert(k, val);
1003
            }
1004
        }
10058274×
        if !c.at_end() {
10060×
            return Err(ObjectError::Cbor(cbor::CborError::TrailingBytes));
10078274×
        }
10088274×
        let mut change = Change::from_value(&Value::Map(fields))?;
10098274×
        change.edits = edits;
10108274×
        Ok((change, texts))
10118275×
    }
1012
}
1013
1014
impl Change {
1015
    /// A change's metadata alone: its tree operations and edits are
1016
    /// stepped over, not decoded. For log, signature checks and walks of
1017
    /// the dependency graph, which read nothing else.
10183083×
    pub fn decode_meta(bytes: &[u8]) -> Result<crate::state::ChangeMeta, ObjectError> {
10193083×
        let mut c = cbor::Cursor::new(bytes);
10203083×
        let (major, n) = c.head()?;
10213083×
        if major != 5 {
10220×
            return schema("change: expected map");
10233083×
        }
10243083×
        let mut fields = Map::new();
10253083×
        let mut last: Option<u64> = None;
10263083×
        for _ in 0..n {
102730830×
            let k = map_key(&mut c, &mut last)?;
102830830×
            if k == 6 || k == 7 {
10296166×
                c.skip()?;
10306166×
                fields.insert(k, Value::Array(Vec::new()));
1031
            } else {
103224664×
                fields.insert(k, c.value()?);
1033
            }
1034
        }
10353083×
        if !c.at_end() {
10360×
            return Err(ObjectError::Cbor(cbor::CborError::TrailingBytes));
10373083×
        }
10383083×
        Ok(crate::state::ChangeMeta::of(&Change::from_value(
10393083×
            &Value::Map(fields),
10400×
        )?))
10413083×
    }
1042
}
1043
1044
/// A canonical map key: an unsigned integer above the previous one.
1045352493×
fn map_key(c: &mut cbor::Cursor, last: &mut Option<u64>) -> Result<u64, ObjectError> {
1046352493×
    let (km, k) = c.head()?;
1047352493×
    if km != 0 || last.is_some_and(|l| k <= l) {
10480×
        return Err(ObjectError::Cbor(cbor::CborError::BadMapKey));
1049352493×
    }
1050352493×
    *last = Some(k);
1051352493×
    Ok(k)
1052352493×
}
1053
1054
/// One edit of [`Change::decode_skeleton`]: an insert's lines are left out.
105548733×
fn edit_skeleton(
105648733×
    c: &mut cbor::Cursor,
105748733×
    version: u64,
105848733×
    me: ChangeHash,
105948733×
    texts: &mut Vec<TextRef>,
106048733×
) -> Result<Edit, ObjectError> {
106148733×
    let (major, n) = c.head()?;
106248733×
    if major != 5 {
10630×
        return schema("edit: expected map");
106448733×
    }
106548733×
    let mut fields = Map::new();
106648733×
    let mut inline: Option<(usize, usize, u64)> = None;
106748733×
    let mut last: Option<u64> = None;
106848733×
    for _ in 0..n {
1069238915×
        let k = map_key(c, &mut last)?;
1070238915×
        if k == 4 {
107145835×
            let start = c.pos();
107245835×
            let (am, count) = c.head()?;
107345835×
            if am != 4 {
10740×
                return schema("lines: expected array");
107545835×
            }
107645835×
            for _ in 0..count {
107761308×
                c.skip()?;
1078
            }
107945835×
            inline = Some((start, c.pos(), count));
108045835×
            continue;
1081193080×
        }
1082193080×
        fields.insert(k, c.value()?);
1083
    }
108448733×
    let Some((start, end, count)) = inline else {
10852898×
        return Edit::from_value(&Value::Map(fields), version, &mut |text, count, form| {
1086147×
            texts.push(TextRef::Blob(*text, count, form));
1087147×
            Ok(Lines::default())
1088147×
        });
1089
    };
109045835×
    if uint(field(&fields, 0, "edit tag")?, "edit tag")? != 0 || fields.contains_key(&5) {
10910×
        return schema("only an insert has inline lines, and not with a text blob");
109245835×
    }
109345835×
    if count == 0 {
10940×
        return schema("insert with no lines");
109545835×
    }
109645835×
    if version >= 2 && end - start >= TEXT_BLOB_MIN {
10971×
        return schema("an insert this large is stored as a text blob in a version 2 change");
109845834×
    }
109945834×
    let (Ok(start), Ok(end)) = (u32::try_from(start), u32::try_from(end)) else {
11000×
        return schema("change too large");
1101
    };
110245834×
    texts.push(TextRef::Inline {
110345834×
        change: me,
110445834×
        start,
110545834×
        end,
110645834×
    });
1107
    Ok(Edit::Insert {
110845834×
        node: node_id(field(&fields, 1, "edit.node")?, "edit.node")?,
110945834×
        after: AtomRef::from_value(field(&fields, 2, "after")?, "after")?,
111045834×
        before: AtomRef::from_value(field(&fields, 3, "before")?, "before")?,
111145834×
        lines: Lines::default(),
1112
    })
111348733×
}
1114
1115
/// A large insert's lines as stored (spec §6.1): the blob and its content,
1116
/// the canonical CBOR array of the lines' byte strings.
1117
#[derive(Debug, Clone, PartialEq, Eq)]
1118
pub struct StoredText {
1119
    pub blob: Blob,
1120
    pub content: Vec<u8>,
1121
    pub form: TextForm,
1122
}
1123
1124
/// The form a change of `version` stores these lines in.
112573×
fn text_form(version: u64, lines: &Lines) -> TextForm {
112672×
    match version {
112773×
        ..=2 => TextForm::Cbor,
112872×
        _ if lines.is_split_form() => TextForm::Raw,
11291×
        _ => TextForm::CborFallback,
1130
    }
113173×
}
1132
1133
/// The lines a text blob's `content` holds, checked against the rules for
1134
/// one: canonical, as many as the insert claims, and not short enough to
1135
/// have been inline.
1136138×
pub fn text_lines(content: &[u8], count: u32, form: TextForm) -> Result<Lines, ObjectError> {
1137138×
    let lines = match form {
1138132×
        TextForm::Raw => Lines::split(content),
11396×
        TextForm::Cbor | TextForm::CborFallback => array_lines(&cbor::decode(content)?)?,
1140
    };
1141
    // One encoding per change: the size rule and the form are both fixed
1142
    // by the lines.
1143138×
    if cbor::byte_strings_len(&lines) < TEXT_BLOB_MIN {
11442×
        return schema(format!(
1145
            "a text blob of {} bytes is short enough to be inline",
11462×
            content.len()
1147
        ));
1148136×
    }
1149136×
    if form == TextForm::CborFallback && lines.is_split_form() {
11501×
        return schema("these lines are stored as their bytes in a version 3 change");
1151135×
    }
1152135×
    if lines.len() != count as usize {
11532×
        return schema(format!(
1154
            "a text blob holds {} lines, the insert says {count}",
11552×
            lines.len()
1156
        ));
1157133×
    }
1158133×
    Ok(lines)
1159138×
}
1160
1161
// ---------------------------------------------------------------- blob
1162
1163
/// File content as an ordered list of chunks (spec §13.2).
1164
#[derive(Debug, Clone, PartialEq, Eq)]
1165
pub struct Blob {
1166
    pub length: u64,
1167
    pub chunks: Vec<ObjectRef>,
1168
}
1169
1170
impl Blob {
1171
    /// The blob for `content`: its chunks as content-defined chunking cuts
1172
    /// them (spec §13.2).
1173473×
    pub fn of(content: &[u8]) -> Blob {
1174
        Blob {
1175473×
            length: content.len() as u64,
1176473×
            chunks: crate::chunk::chunks(content)
1177473×
                .into_iter()
1178596×
                .map(|c| hash_object(ObjectType::Chunk, c))
1179473×
                .collect(),
1180
        }
1181473×
    }
1182
1183601×
    pub fn encode(&self) -> Vec<u8> {
1184601×
        cbor::encode(&Value::map([
1185601×
            (0, Value::Uint(FORMAT_VERSION)),
1186601×
            (1, Value::Uint(self.length)),
1187
            (
1188
                2,
1189
                Value::Array(
1190601×
                    self.chunks
1191601×
                        .iter()
1192823×
                        .map(|c| Value::Bytes(c.0.to_vec()))
1193601×
                        .collect(),
1194
                ),
1195
            ),
1196
        ]))
1197601×
    }
1198384×
    pub fn hash(&self) -> ObjectRef {
1199384×
        hash_object(ObjectType::Blob, &self.encode())
1200384×
    }
1201447×
    pub fn decode(bytes: &[u8]) -> Result<Blob, ObjectError> {
1202447×
        let v = cbor::decode(bytes)?;
1203447×
        let m = map(&v, "blob")?;
1204447×
        check_version(m)?;
1205
        Ok(Blob {
1206447×
            length: uint(field(m, 1, "length")?, "length")?,
1207447×
            chunks: array(field(m, 2, "chunks")?, "chunks")?
1208447×
                .iter()
1209689×
                .map(|c| oref(c, "chunk"))
1210447×
                .collect::<Result<Vec<_>, _>>()?,
1211
        })
1212447×
    }
1213
}
1214
1215
// ---------------------------------------------------------------- checkpoint
1216
1217
/// A materialized state (spec §11): the heads it stands for, how many changes
1218
/// it holds, and a blob with the serialized graphs (`State::checkpoint_payload`).
1219
#[derive(Debug, Clone, PartialEq, Eq)]
1220
pub struct Checkpoint {
1221
    pub heads: Vec<ChangeHash>,
1222
    pub count: u64,
1223
    pub payload: ObjectRef,
1224
}
1225
1226
impl Checkpoint {
122712×
    pub fn encode(&self) -> Vec<u8> {
122812×
        cbor::encode(&Value::map([
122912×
            (0, Value::Uint(FORMAT_VERSION)),
1230
            (
1231
                1,
1232
                Value::Array(
123312×
                    self.heads
123412×
                        .iter()
123513×
                        .map(|h| Value::Bytes(h.0.to_vec()))
123612×
                        .collect(),
1237
                ),
1238
            ),
123912×
            (2, Value::Uint(self.count)),
124012×
            (3, Value::Bytes(self.payload.0.to_vec())),
1241
        ]))
124212×
    }
12430×
    pub fn hash(&self) -> ObjectRef {
12440×
        hash_object(ObjectType::Checkpoint, &self.encode())
12450×
    }
124689×
    pub fn decode(bytes: &[u8]) -> Result<Checkpoint, ObjectError> {
124789×
        let v = cbor::decode(bytes)?;
124889×
        let m = map(&v, "checkpoint")?;
124989×
        check_version(m)?;
1250
        Ok(Checkpoint {
125189×
            heads: array(field(m, 1, "heads")?, "heads")?
125289×
                .iter()
125391×
                .map(|h| oref(h, "head"))
125489×
                .collect::<Result<Vec<_>, _>>()?,
125589×
            count: uint(field(m, 2, "count")?, "count")?,
125689×
            payload: oref(field(m, 3, "payload")?, "payload")?,
1257
        })
125889×
    }
1259
}
1260
1261
// ---------------------------------------------------------------- state
1262
1263
/// A state named by its heads (spec §10.1): what a bookmark or tag points at.
1264
#[derive(Debug, Clone, PartialEq, Eq, Default)]
1265
pub struct StateObject {
1266
    pub heads: Vec<ChangeHash>,
1267
}
1268
1269
impl StateObject {
12703273×
    pub fn new(mut heads: Vec<ChangeHash>) -> StateObject {
12713273×
        heads.sort();
12723273×
        heads.dedup();
12733273×
        StateObject { heads }
12743273×
    }
12753272×
    pub fn encode(&self) -> Vec<u8> {
12763272×
        debug_assert!(self.heads.windows(2).all(|w| w[0] < w[1]));
12773272×
        cbor::encode(&Value::map([
12783272×
            (0, Value::Uint(FORMAT_VERSION)),
1279
            (
1280
                1,
1281
                Value::Array(
12823272×
                    self.heads
12833272×
                        .iter()
12844089×
                        .map(|h| Value::Bytes(h.0.to_vec()))
12853272×
                        .collect(),
1286
                ),
1287
            ),
1288
        ]))
12893272×
    }
12902×
    pub fn hash(&self) -> ObjectRef {
12912×
        hash_object(ObjectType::State, &self.encode())
12922×
    }
12935567×
    pub fn decode(bytes: &[u8]) -> Result<StateObject, ObjectError> {
12945567×
        let v = cbor::decode(bytes)?;
12955567×
        let m = map(&v, "state")?;
12965567×
        check_version(m)?;
12975567×
        let heads = array(field(m, 1, "heads")?, "heads")?
12985567×
            .iter()
12999212×
            .map(|h| oref(h, "head"))
13005567×
            .collect::<Result<Vec<_>, _>>()?;
13015567×
        if !heads.windows(2).all(|w| w[0] < w[1]) {
13020×
            return schema("state heads must be sorted and unique");
13035567×
        }
13045567×
        Ok(StateObject { heads })
13055567×
    }
1306
}
1307
1308
#[cfg(test)]
1309
pub(crate) mod tests {
1310
    use super::*;
1311
131216×
    pub(crate) fn sample_change() -> Change {
131316×
        let n = NodeId([7; 16]);
131416×
        let dep = ObjectRef([1; 32]);
131516×
        let mut c = Change {
131616×
            version: crate::objects::CHANGE_VERSION,
131716×
            change_id: ChangeId([9; 16]),
131816×
            deps: vec![ObjectRef([2; 32]), dep],
131916×
            author: ObjectRef([3; 32]),
132016×
            hlc: Hlc {
132116×
                wall_ms: 1_700_000_000_000,
132216×
                logical: 4,
132316×
            },
132416×
            message: "Add greeting".into(),
132516×
            tree_ops: vec![
132616×
                TreeOp::AddNode {
132716×
                    node: n,
132816×
                    kind: NodeKind::File,
132916×
                    mode: Mode::TEXT,
133016×
                    parent: NodeId::ROOT,
133116×
                    name: "hello.txt".into(),
133216×
                },
133316×
                TreeOp::SetMode {
133416×
                    node: n,
133516×
                    old: OpRef {
133616×
                        change: ObjectRef::ZERO,
133716×
                        index: 0,
133816×
                    },
133916×
                    mode: Mode {
134016×
                        exec: true,
134116×
                        opaque: false,
134216×
                    },
134316×
                },
134416×
            ],
134516×
            edits: vec![
134616×
                Edit::Insert {
134716×
                    node: n,
134816×
                    after: AtomRef::Start,
134916×
                    before: AtomRef::End,
135016×
                    lines: vec![b"hello\n".to_vec(), b"world\n".to_vec()].into(),
135116×
                },
135216×
                Edit::Delete {
135316×
                    node: n,
135416×
                    atoms: vec![AtomRange {
135516×
                        change: dep,
135616×
                        from: 0,
135716×
                        to: 2,
135816×
                    }],
135916×
                },
136016×
                Edit::Replace {
136116×
                    node: n,
136216×
                    old: None,
136316×
                    new: Some(ObjectRef([5; 32])),
136416×
                },
136516×
            ],
136616×
            kind: ChangeKind::Normal,
136716×
        };
136816×
        c.normalize();
136916×
        c
137016×
    }
1371
1372
    #[test]
13731×
    fn change_round_trips_and_hash_is_stable() {
13741×
        let c = sample_change();
13751×
        let bytes = c.encode();
13761×
        let d = Change::decode(&bytes).unwrap();
13771×
        assert_eq!(c, d);
13781×
        assert_eq!(c.hash(), d.hash());
13791×
        assert_eq!(d.encode(), bytes);
1380
        // Any semantic difference changes the hash.
13811×
        let mut e = c.clone();
13821×
        e.message.push('!');
13831×
        assert_ne!(e.hash(), c.hash());
13841×
    }
1385
1386
    #[test]
13871×
    fn compact_encoding_is_the_plain_one() {
1388
        // Inline lines written as their encoding give the same bytes, so
1389
        // the same hash, as a value per line.
13901×
        let c = sample_change();
13911×
        assert!(!c.has_stored_text(), "the sample's insert is inline");
13921×
        let plain = cbor::encode(&c.to_value());
13931×
        assert_eq!(c.encode(), plain);
13941×
        assert_eq!(c.encode_parts().0, plain);
13951×
        let streamed: Result<Vec<u8>, ()> = c.encode_streaming(|_| Ok(()));
13961×
        assert_eq!(streamed.unwrap(), plain);
13971×
        assert_eq!(Change::decode(&plain).unwrap(), c);
13981×
    }
1399
1400
    #[test]
14011×
    fn decode_rejects_bad_changes() {
14021×
        let c = sample_change();
14031×
        let mut v = c.to_value();
14041×
        if let Value::Map(m) = &mut v {
14051×
            m.insert(0, Value::Uint(4));
14061×
        }
14071×
        assert!(
14081×
            matches!(Change::from_value(&v), Err(ObjectError::Schema(s)) if s.contains("version"))
1409
        );
1410
14111×
        let mut v = c.to_value();
14121×
        if let Value::Map(m) = &mut v {
14131×
            m.insert(
14141×
                2,
14151×
                Value::Array(vec![Value::Bytes(vec![2; 32]), Value::Bytes(vec![1; 32])]),
14161×
            );
14171×
        }
14181×
        assert!(
14191×
            matches!(Change::from_value(&v), Err(ObjectError::Schema(s)) if s.contains("sorted"))
1420
        );
1421
14221×
        let mut v = c.to_value();
14231×
        if let Value::Map(m) = &mut v {
14241×
            m.insert(9, Value::map([(0, Value::Null)]));
14251×
        }
14261×
        assert!(
14271×
            matches!(Change::from_value(&v), Err(ObjectError::Schema(s)) if s.contains("extra"))
1428
        );
14291×
    }
1430
14316×
    fn big_lines(n: usize) -> Lines {
14326×
        (0..n)
14333000×
            .map(|i| format!("line {i} of a large insert\n").into_bytes())
14346×
            .collect()
14356×
    }
1436
14376×
    fn with_insert(mut c: Change, lines: Lines) -> Change {
14386×
        c.edits[0] = Edit::Insert {
14396×
            node: NodeId([7; 16]),
14406×
            after: AtomRef::Start,
14416×
            before: AtomRef::End,
14426×
            lines,
14436×
        };
14446×
        c
14456×
    }
1446
1447
    #[test]
14481×
    fn large_inserts_are_stored_as_text_blobs() {
14491×
        assert!(
14501×
            !sample_change().has_stored_text(),
1451
            "a small insert stays inline"
1452
        );
14531×
        let lines = big_lines(500);
14541×
        let c = with_insert(sample_change(), lines.clone());
14551×
        assert!(c.has_stored_text());
14561×
        let (bytes, texts) = c.encode_parts();
14571×
        assert_eq!(bytes, c.encode());
14581×
        assert!(bytes.len() < 1024, "{}", bytes.len());
14591×
        assert_eq!(texts.len(), 1);
1460
        // Version 3: the lines' bytes themselves.
14611×
        assert_eq!(texts[0].form, TextForm::Raw);
14621×
        assert_eq!(texts[0].content, lines.bytes());
14631×
        assert_eq!(texts[0].blob, Blob::of(&texts[0].content));
14641×
        assert!(Change::decode(&bytes).is_err(), "reading it needs the text");
14651×
        let d = Change::decode_with(&bytes, &mut |r, n, form| {
14661×
            assert_eq!(*r, texts[0].blob.hash());
14671×
            assert_eq!(form, TextForm::Raw);
14681×
            text_lines(&texts[0].content, n, form)
14691×
        })
14701×
        .unwrap();
14711×
        assert_eq!(d, c);
14721×
        assert_eq!(d.hash(), c.hash());
1473
        // Version 2 held the same lines as a CBOR array, and still reads.
14741×
        let mut v2 = c.clone();
14751×
        v2.version = 2;
14761×
        let (b2, t2) = v2.encode_parts();
14771×
        assert_eq!(t2[0].form, TextForm::Cbor);
14781×
        assert_eq!(t2[0].content, cbor::encode_byte_strings(&lines));
14791×
        let d2 = Change::decode_with(&b2, &mut |_, n, form| text_lines(&t2[0].content, n, form))
14801×
            .unwrap();
14811×
        assert_eq!(d2, v2);
1482
        // Lines the line rule would not split back stay a CBOR array,
1483
        // marked; and a marked array of lines that would is refused.
14841×
        let odd: Lines = (0..500)
1485500×
            .map(|i| format!("no newline {i}").into_bytes())
14861×
            .collect();
14871×
        let c3 = with_insert(sample_change(), odd.clone());
14881×
        let (b3, t3) = c3.encode_parts();
14891×
        assert_eq!(t3[0].form, TextForm::CborFallback);
14901×
        let d3 = Change::decode_with(&b3, &mut |_, n, form| text_lines(&t3[0].content, n, form))
14911×
            .unwrap();
14921×
        assert_eq!(d3, c3);
14931×
        let marked = cbor::encode_byte_strings(&lines);
14941×
        assert!(text_lines(&marked, 500, TextForm::CborFallback).is_err());
14951×
    }
1496
1497
    #[test]
14981×
    fn version_1_changes_keep_their_inline_inserts_and_hashes() {
14991×
        let mut c = with_insert(sample_change(), big_lines(500));
15001×
        c.version = 1;
15011×
        let bytes = c.encode();
15021×
        assert!(bytes.len() > TEXT_BLOB_MIN);
15031×
        let (again, texts) = c.encode_parts();
15041×
        assert!(texts.is_empty());
15051×
        assert_eq!(again, bytes);
15061×
        let d = Change::decode(&bytes).unwrap();
15071×
        assert_eq!(d.version, 1);
15081×
        assert_eq!(d.encode(), bytes);
1509
        // The same inline insert in a version 2 change is not canonical.
15101×
        let mut v = c.to_value();
15111×
        if let Value::Map(m) = &mut v {
15121×
            m.insert(0, Value::Uint(2));
15131×
        }
15141×
        assert!(
15151×
            matches!(Change::from_value(&v), Err(ObjectError::Schema(s)) if s.contains("text blob"))
1516
        );
15171×
    }
1518
1519
    #[test]
15201×
    fn a_skeleton_leaves_every_insert_out_and_says_where_its_lines_are() {
15211×
        let mut c = with_insert(sample_change(), big_lines(500));
15221×
        c.edits.push(Edit::Insert {
15231×
            node: NodeId([8; 16]),
15241×
            after: AtomRef::Start,
15251×
            before: AtomRef::End,
15261×
            lines: vec![b"small\n".to_vec(), b"insert\n".to_vec()].into(),
15271×
        });
15281×
        let (bytes, stored) = c.encode_parts();
15291×
        let me = ObjectRef([4; 32]);
15301×
        let (skel, texts) = Change::decode_skeleton(&bytes, me).unwrap();
15311×
        assert_eq!(texts.len(), 2);
15321×
        let mut filled = skel.clone();
15331×
        let mut next = texts.iter();
15344×
        for e in filled.edits.iter_mut() {
15354×
            if let Edit::Insert { lines, .. } = e {
15362×
                assert!(lines.is_empty(), "no line kept");
15372×
                *lines = match next.next().unwrap() {
15381×
                    TextRef::Blob(r, n, form) => {
15391×
                        assert_eq!(*r, stored[0].blob.hash());
15401×
                        text_lines(&stored[0].content, *n, *form).unwrap()
1541
                    }
15421×
                    TextRef::Inline { change, start, end } => {
15431×
                        assert_eq!(*change, me);
15441×
                        inline_lines(&bytes[*start as usize..*end as usize]).unwrap()
1545
                    }
1546
                };
15472×
            }
1548
        }
15491×
        assert_eq!(filled, c, "filled in, it is the change");
1550
        // A version 1 change's large inline insert is fine; in version 2 it is not.
15511×
        let mut v1 = with_insert(sample_change(), big_lines(500));
15521×
        v1.version = 1;
15531×
        assert!(Change::decode_skeleton(&v1.encode(), me).is_ok());
15541×
        let mut v = v1.to_value();
15551×
        if let Value::Map(m) = &mut v {
15561×
            m.insert(0, Value::Uint(2));
15571×
        }
15581×
        assert!(Change::decode_skeleton(&cbor::encode(&v), me).is_err());
15591×
    }
1560
1561
    #[test]
15621×
    fn metadata_reads_without_the_operations() {
15631×
        let c = with_insert(sample_change(), big_lines(500));
15641×
        let (bytes, _) = c.encode_parts();
15651×
        let m = Change::decode_meta(&bytes).unwrap();
15661×
        assert_eq!(m, crate::state::ChangeMeta::of(&c));
15671×
    }
1568
1569
    #[test]
15701×
    fn text_blobs_are_checked() {
15711×
        let lines = big_lines(500);
15721×
        let content = cbor::encode_byte_strings(&lines);
15731×
        assert_eq!(content.len(), cbor::byte_strings_len(&lines));
15741×
        assert_eq!(
1575
            content,
15761×
            cbor::encode(&Value::Array(
1577500×
                lines.iter().map(|l| Value::Bytes(l.to_vec())).collect()
1578
            ))
1579
        );
15801×
        assert_eq!(text_lines(&content, 500, TextForm::Cbor).unwrap(), lines);
15811×
        assert!(text_lines(&content, 499, TextForm::Cbor).is_err());
15821×
        assert_eq!(
15831×
            text_lines(lines.bytes(), 500, TextForm::Raw).unwrap(),
1584
            lines
1585
        );
15861×
        assert!(text_lines(lines.bytes(), 501, TextForm::Raw).is_err());
15871×
        let small = cbor::encode_byte_strings(&vec![b"x\n".to_vec()].into());
15881×
        assert!(
15891×
            text_lines(&small, 1, TextForm::Cbor).is_err(),
1590
            "short enough to be inline"
1591
        );
15921×
        assert!(
15931×
            text_lines(b"x\n", 1, TextForm::Raw).is_err(),
1594
            "short enough to be inline"
1595
        );
15961×
    }
1597
1598
    #[test]
15991×
    fn names_are_validated() {
16005×
        for bad in ["", ".", "..", "a/b", "a\0b"] {
16015×
            assert!(validate_name(bad).is_err(), "{bad:?}");
1602
        }
16031×
        assert!(validate_name("Foo.c").is_ok());
16041×
        assert!(validate_name("...").is_ok());
16051×
    }
1606
1607
    #[test]
16081×
    fn mode_and_kind_tags() {
16093×
        for m in [
16101×
            Mode::TEXT,
16111×
            Mode::OPAQUE,
16121×
            Mode {
16131×
                exec: true,
16141×
                opaque: true,
16151×
            },
16161×
        ] {
16173×
            assert_eq!(Mode::from_bits(m.bits()).unwrap(), m);
1618
        }
16191×
        assert!(Mode::from_bits(4).is_err());
16204×
        for k in [
16211×
            NodeKind::File,
16221×
            NodeKind::Dir,
16231×
            NodeKind::Symlink,
16241×
            NodeKind::Subrepo,
16251×
        ] {
16264×
            assert_eq!(NodeKind::from_tag(k.tag()).unwrap(), k);
1627
        }
16281×
    }
1629
1630
    #[test]
16311×
    fn self_references_resolve() {
16321×
        let me = ObjectRef([8; 32]);
16331×
        assert_eq!(
16341×
            AtomRef::Atom {
16351×
                change: ObjectRef::ZERO,
16361×
                index: 3
16371×
            }
16381×
            .resolve(me),
16391×
            AtomRef::Atom {
16401×
                change: me,
16411×
                index: 3
16421×
            }
1643
        );
16441×
        assert_eq!(AtomRef::Start.resolve(me), AtomRef::Start);
16451×
        let other = ObjectRef([1; 32]);
16461×
        assert_eq!(
16471×
            OpRef {
16481×
                change: other,
16491×
                index: 1
16501×
            }
16511×
            .resolve(me)
1652
            .change,
1653
            other
1654
        );
16551×
    }
1656
1657
    #[test]
16581×
    fn state_object_round_trip() {
16591×
        let st = StateObject::new(vec![
16601×
            ObjectRef([2; 32]),
16611×
            ObjectRef([1; 32]),
16621×
            ObjectRef([2; 32]),
1663
        ]);
16641×
        assert_eq!(st.heads, vec![ObjectRef([1; 32]), ObjectRef([2; 32])]);
16651×
        assert_eq!(StateObject::decode(&st.encode()).unwrap(), st);
16661×
        assert_eq!(StateObject::new(vec![]).heads, vec![]);
16671×
        assert_ne!(StateObject::new(vec![]).hash(), st.hash());
16681×
    }
1669
1670
    #[test]
16711×
    fn blob_round_trip() {
16721×
        let b = Blob {
16731×
            length: 10,
16741×
            chunks: vec![ObjectRef([1; 32]), ObjectRef([2; 32])],
16751×
        };
16761×
        assert_eq!(Blob::decode(&b.encode()).unwrap(), b);
16771×
    }
1678
}