OXYGENHUB

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

1065 of 1128 lines run, 226 of 316 functions · run #415 on main · 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
5425×
pub(crate) fn schema<T>(msg: impl Into<String>) -> Result<T, ObjectError> {
5525×
    Err(ObjectError::Schema(msg.into()))
5625×
}
57
58
pub(crate) type Map = BTreeMap<u64, Value>;
59
601040509×
pub(crate) fn field<'a>(m: &'a Map, k: u64, what: &str) -> Result<&'a Value, ObjectError> {
611040509×
    m.get(&k)
621040509×
        .ok_or_else(|| ObjectError::Schema(format!("missing field {k} ({what})")))
631040509×
}
64420938×
pub(crate) fn uint(v: &Value, what: &str) -> Result<u64, ObjectError> {
65420938×
    v.as_uint()
66420938×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected unsigned integer")))
67420938×
}
6875436×
pub(crate) fn u32_(v: &Value, what: &str) -> Result<u32, ObjectError> {
6975436×
    u32::try_from(uint(v, what)?).map_err(|_| ObjectError::Schema(format!("{what}: exceeds u32")))
7075436×
}
71145637×
pub(crate) fn text<'a>(v: &'a Value, what: &str) -> Result<&'a str, ObjectError> {
72145637×
    v.as_text()
73145637×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected text")))
74145637×
}
75327104×
pub(crate) fn array<'a>(v: &'a Value, what: &str) -> Result<&'a [Value], ObjectError> {
76327104×
    v.as_array()
77327104×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected array")))
78327104×
}
79154492×
pub(crate) fn map<'a>(v: &'a Value, what: &str) -> Result<&'a Map, ObjectError> {
80154492×
    v.as_map()
81154492×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected map")))
82154492×
}
83463124×
pub(crate) fn bytes<'a>(v: &'a Value, what: &str) -> Result<&'a [u8], ObjectError> {
84463124×
    v.as_bytes()
85463124×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected bytes")))
86463124×
}
87159089×
pub(crate) fn oref(v: &Value, what: &str) -> Result<ObjectRef, ObjectError> {
88159089×
    ObjectRef::from_slice(bytes(v, what)?)
89159088×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected 32 bytes")))
90159089×
}
91156278×
pub(crate) fn node_id(v: &Value, what: &str) -> Result<NodeId, ObjectError> {
92156278×
    NodeId::from_slice(bytes(v, what)?)
93156278×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected 16 bytes")))
94156278×
}
9534987×
pub(crate) fn check_version(m: &Map) -> Result<(), ObjectError> {
9634987×
    let v = uint(field(m, 0, "version")?, "version")?;
9734987×
    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
        });
11134987×
    }
11234987×
    Ok(())
11334987×
}
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 {
1257331×
    pub fn now() -> Hlc {
1267331×
        let wall_ms = std::time::SystemTime::now()
1277331×
            .duration_since(std::time::UNIX_EPOCH)
1287331×
            .map(|d| d.as_millis() as u64)
1297331×
            .unwrap_or(0);
1307331×
        Hlc {
1317331×
            wall_ms,
1327331×
            logical: 0,
1337331×
        }
1347331×
    }
13514168×
    pub(crate) fn to_value(self) -> Value {
13614168×
        Value::map([
13714168×
            (0, Value::Uint(self.wall_ms)),
13814168×
            (1, Value::Uint(self.logical as u64)),
13914168×
        ])
14014168×
    }
14142091×
    pub(crate) fn from_value(v: &Value) -> Result<Hlc, ObjectError> {
14242091×
        let m = map(v, "hlc")?;
143
        Ok(Hlc {
14442091×
            wall_ms: uint(field(m, 0, "hlc.wall_ms")?, "hlc.wall_ms")?,
14542091×
            logical: u32_(field(m, 1, "hlc.logical")?, "hlc.logical")?,
146
        })
14742091×
    }
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 {
16274221×
    pub(crate) fn tag(self) -> u64 {
16374221×
        match self {
16473239×
            NodeKind::File => 0,
165958×
            NodeKind::Dir => 1,
1663×
            NodeKind::Symlink => 2,
16721×
            NodeKind::Subrepo => 3,
168
        }
16974221×
    }
17099488×
    pub(crate) fn from_tag(t: u64) -> Result<NodeKind, ObjectError> {
17199488×
        Ok(match t {
17297233×
            0 => NodeKind::File,
1732064×
            1 => NodeKind::Dir,
1749×
            2 => NodeKind::Symlink,
175182×
            3 => NodeKind::Subrepo,
1760×
            _ => return schema(format!("unknown node kind {t}")),
177
        })
17899488×
    }
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
    };
19773874×
    pub(crate) fn bits(self) -> u64 {
19873874×
        (self.exec as u64) | ((self.opaque as u64) << 1)
19973874×
    }
20099454×
    pub(crate) fn from_bits(b: u64) -> Result<Mode, ObjectError> {
20199454×
        if b > 3 {
2021×
            return schema(format!("unknown mode bits {b}"));
20399453×
        }
20499453×
        Ok(Mode {
20599453×
            exec: b & 1 != 0,
20699453×
            opaque: b & 2 != 0,
20799453×
        })
20899454×
    }
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 {
220665×
    fn to_value(self) -> Value {
221665×
        Value::Array(vec![
222665×
            Value::Bytes(self.change.0.to_vec()),
223665×
            Value::Uint(self.index as u64),
224665×
        ])
225665×
    }
2261138×
    fn from_value(v: &Value, what: &str) -> Result<OpRef, ObjectError> {
2271138×
        let a = array(v, what)?;
2281138×
        if a.len() != 2 {
2290×
            return schema(format!("{what}: expected [hash, index]"));
2301138×
        }
231
        Ok(OpRef {
2321138×
            change: oref(&a[0], what)?,
2331138×
            index: u32_(&a[1], what)?,
234
        })
2351138×
    }
236
    /// Replace a self reference with the concrete change hash.
2371131×
    pub fn resolve(self, me: ChangeHash) -> OpRef {
2381131×
        if self.change.is_zero() {
2391×
            OpRef { change: me, ..self }
240
        } else {
2411130×
            self
242
        }
2431131×
    }
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).
27349392×
pub fn validate_name(name: &str) -> Result<(), ObjectError> {
27449392×
    if name.is_empty() || name == "." || name == ".." || name.contains('/') || name.contains('\0') {
2756×
        return schema(format!("invalid placement name {name:?}"));
27649386×
    }
27749386×
    Ok(())
27849392×
}
279
280
impl TreeOp {
281134×
    pub fn node(&self) -> NodeId {
282134×
        match self {
283102×
            TreeOp::AddNode { node, .. }
28417×
            | TreeOp::RemoveNode { node, .. }
28514×
            | TreeOp::Move { node, .. }
286134×
            | TreeOp::SetMode { node, .. } => *node,
287
        }
288134×
    }
289
2907025×
    fn to_value(&self) -> Value {
29113445×
        let nid = |n: &NodeId| Value::Bytes(n.0.to_vec());
2927025×
        match self {
293
            TreeOp::AddNode {
2946360×
                node,
2956360×
                kind,
2966360×
                mode,
2976360×
                parent,
2986360×
                name,
2996360×
            } => Value::map([
3006360×
                (0, Value::Uint(0)),
3016360×
                (1, nid(node)),
3026360×
                (2, Value::Uint(kind.tag())),
3036360×
                (3, Value::Uint(mode.bits())),
3046360×
                (4, nid(parent)),
3056360×
                (5, Value::Text(name.clone())),
3066360×
            ]),
307538×
            TreeOp::RemoveNode { node, placement } => Value::map([
308538×
                (0, Value::Uint(1)),
309538×
                (1, nid(node)),
310538×
                (2, placement.to_value()),
311538×
            ]),
312
            TreeOp::Move {
31360×
                node,
31460×
                old,
31560×
                parent,
31660×
                name,
31760×
            } => Value::map([
31860×
                (0, Value::Uint(2)),
31960×
                (1, nid(node)),
32060×
                (2, old.to_value()),
32160×
                (4, nid(parent)),
32260×
                (5, Value::Text(name.clone())),
32360×
            ]),
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
        }
3317025×
    }
332
33350286×
    fn from_value(v: &Value) -> Result<TreeOp, ObjectError> {
33450286×
        let m = map(v, "tree_op")?;
33550286×
        let tag = uint(field(m, 0, "tree_op tag")?, "tree_op tag")?;
33650286×
        let node = node_id(field(m, 1, "tree_op.node")?, "tree_op.node")?;
33750286×
        let op = match tag {
338
            0 => {
33949148×
                let name = text(field(m, 5, "name")?, "name")?.to_owned();
34049148×
                validate_name(&name)?;
341
                TreeOp::AddNode {
34249148×
                    node,
34349148×
                    kind: NodeKind::from_tag(uint(field(m, 2, "kind")?, "kind")?)?,
34449148×
                    mode: Mode::from_bits(uint(field(m, 3, "mode")?, "mode")?)?,
34549148×
                    parent: node_id(field(m, 4, "parent")?, "parent")?,
34649148×
                    name,
347
                }
348
            }
349
            1 => TreeOp::RemoveNode {
350882×
                node,
351882×
                placement: OpRef::from_value(field(m, 2, "placement")?, "placement")?,
352
            },
353
            2 => {
354217×
                let name = text(field(m, 5, "name")?, "name")?.to_owned();
355217×
                validate_name(&name)?;
356
                TreeOp::Move {
357217×
                    node,
358217×
                    old: OpRef::from_value(field(m, 2, "old")?, "old")?,
359217×
                    parent: node_id(field(m, 4, "parent")?, "parent")?,
360217×
                    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
        };
37050286×
        if node.is_root() {
3710×
            return schema("tree op on the root node");
37250286×
        }
37350286×
        Ok(op)
37450286×
    }
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 {
38716490×
    fn to_value(self) -> Value {
38816490×
        match self {
3896020×
            AtomRef::Start => Value::Uint(0),
3906265×
            AtomRef::End => Value::Uint(1),
3914205×
            AtomRef::Atom { change, index } => Value::Array(vec![
3924205×
                Value::Bytes(change.0.to_vec()),
3934205×
                Value::Uint(index as u64),
3944205×
            ]),
395
        }
39616490×
    }
397104512×
    fn from_value(v: &Value, what: &str) -> Result<AtomRef, ObjectError> {
3989184×
        match v {
39946868×
            Value::Uint(0) => Ok(AtomRef::Start),
40048460×
            Value::Uint(1) => Ok(AtomRef::End),
4019184×
            Value::Array(a) if a.len() == 2 => Ok(AtomRef::Atom {
4029184×
                change: oref(&a[0], what)?,
4039184×
                index: u32_(&a[1], what)?,
404
            }),
4050×
            _ => schema(format!("{what}: expected atom reference")),
406
        }
407104512×
    }
40866650×
    pub fn resolve(self, me: ChangeHash) -> AtomRef {
4099882×
        match self {
4109882×
            AtomRef::Atom { change, index } if change.is_zero() => {
41141×
                AtomRef::Atom { change: me, index }
412
            }
41366609×
            other => other,
414
        }
41566650×
    }
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 {
4272386×
    fn to_value(self) -> Value {
4282386×
        Value::Array(vec![
4292386×
            Value::Bytes(self.change.0.to_vec()),
4302386×
            Value::Uint(self.from as u64),
4312386×
            Value::Uint(self.to as u64),
4322386×
        ])
4332386×
    }
4344240×
    fn from_value(v: &Value) -> Result<AtomRange, ObjectError> {
4354240×
        let a = array(v, "atom range")?;
4364240×
        if a.len() != 3 {
4370×
            return schema("atom range: expected [hash, from, to]");
4384240×
        }
4394240×
        let r = AtomRange {
4404240×
            change: oref(&a[0], "range.change")?,
4414240×
            from: u32_(&a[1], "range.from")?,
4424240×
            to: u32_(&a[2], "range.to")?,
443
        };
4444240×
        if r.from >= r.to {
4450×
            return schema("atom range: empty or inverted");
4464240×
        }
4474240×
        Ok(r)
4484240×
    }
4494663×
    pub fn resolve(self, me: ChangeHash) -> AtomRange {
4504663×
        if self.change.is_zero() {
45118×
            AtomRange { change: me, ..self }
452
        } else {
4534645×
            self
454
        }
4554663×
    }
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 {
47849828×
    pub fn node(&self) -> NodeId {
47949828×
        match self {
48046178×
            Edit::Insert { node, .. } | Edit::Delete { node, .. } | Edit::Replace { node, .. } => {
48149828×
                *node
482
            }
483
        }
48449828×
    }
485
486
    /// Whether this insert is stored as a text blob in a change of `version`.
48710442×
    fn stored_text(&self, version: u64) -> bool {
4888248×
        matches!(self, Edit::Insert { lines, .. }
4898248×
            if version >= 2 && cbor::byte_strings_len(lines) >= TEXT_BLOB_MIN)
49010442×
    }
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).
49610435×
    fn to_value(&self, stored: Option<(ObjectRef, TextForm)>, compact: bool) -> Value {
49710435×
        let nid = |n: &NodeId| Value::Bytes(n.0.to_vec());
49810435×
        let opt = |o: &Option<ObjectRef>| match o {
499255×
            Some(r) => Value::Bytes(r.0.to_vec()),
500163×
            None => Value::Null,
501418×
        };
50210435×
        match (self, stored) {
503
            (
504
                Edit::Insert {
50599×
                    node,
50699×
                    after,
50799×
                    before,
50899×
                    lines,
509
                },
51099×
                Some((r, form)),
511
            ) => {
51299×
                let mut fields = vec![
51399×
                    (0, Value::Uint(0)),
51499×
                    (1, nid(node)),
51599×
                    (2, after.to_value()),
51699×
                    (3, before.to_value()),
51799×
                    (5, Value::Bytes(r.0.to_vec())),
51899×
                    (6, Value::Uint(lines.len() as u64)),
519
                ];
52099×
                if form == TextForm::CborFallback {
5211×
                    fields.push((7, Value::Uint(1)));
52298×
                }
52399×
                Value::map(fields)
524
            }
525
            (
526
                Edit::Insert {
5278146×
                    node,
5288146×
                    after,
5298146×
                    before,
5308146×
                    lines,
531
                },
532
                None,
5338146×
            ) => Value::map([
5348146×
                (0, Value::Uint(0)),
5358146×
                (1, nid(node)),
5368146×
                (2, after.to_value()),
5378146×
                (3, before.to_value()),
538
                (
539
                    4,
5408146×
                    if compact {
5418140×
                        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
            ]),
5471981×
            (Edit::Delete { node, atoms }, _) => Value::map([
5481981×
                (0, Value::Uint(1)),
5491981×
                (1, nid(node)),
550
                (
551
                    2,
5522386×
                    Value::Array(atoms.iter().map(|r| r.to_value()).collect()),
553
                ),
554
            ]),
555209×
            (Edit::Replace { node, old, new }, _) => Value::map([
556209×
                (0, Value::Uint(2)),
557209×
                (1, nid(node)),
558209×
                (2, opt(old)),
559209×
                (3, opt(new)),
560209×
            ]),
561
        }
56210435×
    }
563
5648751×
    fn from_value(v: &Value, version: u64, resolve: &mut Resolver) -> Result<Edit, ObjectError> {
5658751×
        let m = map(v, "edit")?;
5668751×
        let tag = uint(field(m, 0, "edit tag")?, "edit tag")?;
5678751×
        let node = node_id(field(m, 1, "edit.node")?, "edit.node")?;
5688751×
        let opt = |v: &Value, what: &str| -> Result<Option<ObjectRef>, ObjectError> {
5692254×
            if v.is_null() {
570905×
                Ok(None)
571
            } else {
5721349×
                Ok(Some(oref(v, what)?))
573
            }
5742254×
        };
5758751×
        Ok(match tag {
576
            0 => {
5774383×
                let lines = match (m.get(&4), m.get(&5)) {
5784119×
                    (Some(inline), None) => {
5794119×
                        let lines = array_lines(inline)?;
5804119×
                        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");
5824118×
                        }
5834118×
                        if lines.is_empty() {
5840×
                            return schema("insert with no lines");
5854118×
                        }
5864118×
                        lines
587
                    }
588264×
                    (None, Some(text)) if version >= 2 => {
589264×
                        let text = oref(text, "insert text")?;
590264×
                        let count = u32_(field(m, 6, "insert line count")?, "insert line count")?;
591264×
                        if count == 0 {
5920×
                            return schema("insert with no lines");
593264×
                        }
594264×
                        let form = match (version, m.get(&7)) {
5951×
                            (2, None) => TextForm::Cbor,
596262×
                            (_, 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`).
601264×
                        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 {
6104380×
                    node,
6114380×
                    after: AtomRef::from_value(field(m, 2, "after")?, "after")?,
6124380×
                    before: AtomRef::from_value(field(m, 3, "before")?, "before")?,
6134380×
                    lines,
614
                }
615
            }
616
            1 => {
6173241×
                let atoms = array(field(m, 2, "atoms")?, "atoms")?
6183241×
                    .iter()
6193241×
                    .map(AtomRange::from_value)
6203241×
                    .collect::<Result<Vec<_>, _>>()?;
6213241×
                if atoms.is_empty() {
6220×
                    return schema("delete with no atoms");
6233241×
                }
6243241×
                Edit::Delete { node, atoms }
625
            }
626
            2 => Edit::Replace {
6271127×
                node,
6281127×
                old: opt(field(m, 2, "old")?, "old")?,
6291127×
                new: opt(field(m, 3, "new")?, "new")?,
630
            },
6310×
            _ => return schema(format!("unknown edit tag {tag}")),
632
        })
6338751×
    }
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 {
64617450×
    pub(crate) fn tag(self) -> u64 {
64717450×
        match self {
64814396×
            ChangeKind::Normal => 0,
64951×
            ChangeKind::Resolution => 1,
6503003×
            ChangeKind::WorkingCopy => 2,
651
        }
65217450×
    }
65331420×
    pub(crate) fn from_tag(t: u64) -> Result<ChangeKind, ObjectError> {
65431420×
        Ok(match t {
65527896×
            0 => ChangeKind::Normal,
656184×
            1 => ChangeKind::Resolution,
6573340×
            2 => ChangeKind::WorkingCopy,
6580×
            _ => return schema(format!("unknown change kind {t}")),
659
        })
66031420×
    }
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 {
6806497×
    pub fn normalize(&mut self) {
6816497×
        self.deps.sort();
6826497×
        self.deps.dedup();
6836497×
    }
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.
6938771×
    fn stored_texts(&self, sink: &mut TextSink) -> Vec<Option<(ObjectRef, TextForm)>> {
694
        use rayon::prelude::*;
6958771×
        let mut refs: Vec<Option<(ObjectRef, TextForm)>> = vec![None; self.edits.len()];
6968771×
        let stored: Vec<usize> = (0..self.edits.len())
69710435×
            .filter(|i| self.edits[*i].stored_text(self.version))
6988771×
            .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.
7028771×
        let mut batches: Vec<&[usize]> = Vec::new();
7038771×
        let (mut start, mut bytes) = (0, 0usize);
7048771×
        for (k, i) in stored.iter().enumerate() {
70599×
            if let Edit::Insert { lines, .. } = &self.edits[*i] {
70699×
                bytes += lines.bytes().len();
70799×
            }
70899×
            if k + 1 - start == 256 || bytes >= 32 << 20 {
7090×
                batches.push(&stored[start..=k]);
7100×
                (start, bytes) = (k + 1, 0);
71199×
            }
712
        }
7138771×
        if start < stored.len() {
71498×
            batches.push(&stored[start..]);
7158673×
        }
7168771×
        for batch in batches {
71798×
            let made: Vec<StoredText> = batch
71898×
                .par_iter()
71999×
                .map(|i| {
72099×
                    let Edit::Insert { lines, .. } = &self.edits[*i] else {
7210×
                        unreachable!("only inserts are stored as text");
722
                    };
72399×
                    let form = text_form(self.version, lines);
72499×
                    let content = match form {
72597×
                        TextForm::Raw => lines.bytes().to_vec(),
7262×
                        TextForm::Cbor | TextForm::CborFallback => cbor::encode_byte_strings(lines),
727
                    };
72899×
                    StoredText {
72999×
                        blob: Blob::of(&content),
73099×
                        content,
73199×
                        form,
73299×
                    }
73399×
                })
73498×
                .collect();
73599×
            for (i, t) in batch.iter().zip(&made) {
73699×
                refs[*i] = Some((t.blob.hash(), t.form));
73799×
            }
73898×
            if !sink(made) {
7390×
                break;
74098×
            }
741
        }
7428771×
        refs
7438771×
    }
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.
7478771×
    fn value_with(&self, sink: &mut TextSink, compact: bool) -> Value {
7488771×
        Value::map([
7498771×
            (0, Value::Uint(self.version)),
7508771×
            (1, Value::Bytes(self.change_id.0.to_vec())),
751
            (
752
                2,
753
                Value::Array(
7548771×
                    self.deps
7558771×
                        .iter()
75610172×
                        .map(|d| Value::Bytes(d.0.to_vec()))
7578771×
                        .collect(),
758
                ),
759
            ),
7608771×
            (3, Value::Bytes(self.author.0.to_vec())),
7618771×
            (4, self.hlc.to_value()),
7628771×
            (5, Value::Text(self.message.clone())),
763
            (
764
                6,
7658771×
                Value::Array(self.tree_ops.iter().map(|t| t.to_value()).collect()),
766
            ),
767
            (
768
                7,
769
                Value::Array(
7708771×
                    self.edits
7718771×
                        .iter()
7728771×
                        .zip(self.stored_texts(sink))
77310435×
                        .map(|(e, stored)| e.to_value(stored, compact))
7748771×
                        .collect(),
775
                ),
776
            ),
7778771×
            (8, Value::Uint(self.kind.tag())),
7788771×
            (9, Value::Map(BTreeMap::new())),
779
        ])
7808771×
    }
781
7824266×
    pub fn encode(&self) -> Vec<u8> {
7834266×
        debug_assert!(
7844266×
            self.deps.windows(2).all(|w| w[0] < w[1]),
785
            "deps must be normalized"
786
        );
7874266×
        cbor::encode(&self.value_with(&mut |_| true, true))
7884266×
    }
789
790
    /// The encoding and the text blobs its large inserts are stored as,
791
    /// which must be stored with it.
792134×
    pub fn encode_parts(&self) -> (Vec<u8>, Vec<StoredText>) {
793134×
        debug_assert!(
794134×
            self.deps.windows(2).all(|w| w[0] < w[1]),
795
            "deps must be normalized"
796
        );
797134×
        let mut texts = Vec::new();
798134×
        let bytes = cbor::encode(&self.value_with(
7995×
            &mut |batch| {
8005×
                texts.extend(batch);
8015×
                true
8025×
            },
803
            true,
804
        ));
805134×
        (bytes, texts)
806134×
    }
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.
8114365×
    pub fn encode_streaming<E>(
8124365×
        &self,
8134365×
        mut store: impl FnMut(Vec<StoredText>) -> Result<(), E>,
8144365×
    ) -> Result<Vec<u8>, E> {
8154365×
        debug_assert!(
8164365×
            self.deps.windows(2).all(|w| w[0] < w[1]),
817
            "deps must be normalized"
818
        );
8194365×
        let mut failed = None;
8204365×
        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
        );
8304365×
        match failed {
8310×
            Some(e) => Err(e),
8324365×
            None => Ok(cbor::encode(&value)),
833
        }
8344365×
    }
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
8413851×
    pub fn hash(&self) -> ChangeHash {
8423851×
        hash_object(ObjectType::Change, &self.encode())
8433851×
    }
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).
8586040×
    pub fn decode_with(bytes: &[u8], resolve: &mut Resolver) -> Result<Change, ObjectError> {
8596040×
        let v = cbor::decode(bytes)?;
8606040×
        Self::from_value_with(&v, resolve)
8616040×
    }
862
86313189×
    pub fn from_value(v: &Value) -> Result<Change, ObjectError> {
86413189×
        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×
        })
87013189×
    }
871
87219229×
    pub(crate) fn from_value_with(
87319229×
        v: &Value,
87419229×
        resolve: &mut Resolver,
87519229×
    ) -> Result<Change, ObjectError> {
87619229×
        let m = map(v, "change")?;
87719229×
        let version = uint(field(m, 0, "version")?, "version")?;
87819229×
        if !(1..=CHANGE_VERSION).contains(&version) {
8791×
            return schema(format!("unsupported change format version {version}"));
88019228×
        }
88119228×
        let change_id = ChangeId::from_slice(bytes(field(m, 1, "change_id")?, "change_id")?)
88219228×
            .ok_or_else(|| ObjectError::Schema("change_id: expected 16 bytes".into()))?;
88319228×
        let deps = array(field(m, 2, "deps")?, "deps")?
88419228×
            .iter()
88519228×
            .map(|d| oref(d, "dep"))
88619228×
            .collect::<Result<Vec<_>, _>>()?;
88719228×
        if !deps.windows(2).all(|w| w[0] < w[1]) {
8881×
            return schema("deps must be sorted and unique");
88919227×
        }
89019227×
        if deps.iter().any(|d| d.is_zero()) {
8910×
            return schema("deps may not contain the self reference");
89219227×
        }
89319227×
        let extra = map(field(m, 9, "extra")?, "extra")?;
89419227×
        if !extra.is_empty() {
8951×
            return schema("extra must be empty in format version 1");
89619226×
        }
897
        Ok(Change {
89819226×
            version,
89919226×
            change_id,
90019226×
            deps,
90119226×
            author: oref(field(m, 3, "author")?, "author")?,
90219226×
            hlc: Hlc::from_value(field(m, 4, "hlc")?)?,
90319226×
            message: text(field(m, 5, "message")?, "message")?.to_owned(),
90419226×
            tree_ops: array(field(m, 6, "tree_ops")?, "tree_ops")?
90519226×
                .iter()
90619226×
                .map(TreeOp::from_value)
90719226×
                .collect::<Result<Vec<_>, _>>()?,
90819226×
            edits: array(field(m, 7, "edits")?, "edits")?
90919226×
                .iter()
91019226×
                .map(|e| Edit::from_value(e, version, resolve))
91119226×
                .collect::<Result<Vec<_>, _>>()?,
91219223×
            kind: ChangeKind::from_tag(uint(field(m, 8, "kind")?, "kind")?)?,
913
        })
91419229×
    }
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`]).
94433505×
pub fn inline_lines(array: &[u8]) -> Result<Lines, ObjectError> {
94533505×
    let v = cbor::decode(array)?;
94633505×
    let lines = array_lines(&v)?;
94733505×
    if lines.is_empty() {
9480×
        return schema("insert with no lines");
94933505×
    }
95033505×
    Ok(lines)
95133505×
}
952
953
/// The lines of a CBOR array of byte strings, copied once into one buffer.
95437630×
fn array_lines(v: &Value) -> Result<Lines, ObjectError> {
95537630×
    Ok(array(v, "lines")?
95637630×
        .iter()
95760940×
        .map(|l| bytes(l, "line"))
95837630×
        .collect::<Result<Vec<&[u8]>, _>>()?
95937630×
        .into_iter()
96037630×
        .collect())
96137630×
}
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.
9699925×
    pub fn decode_skeleton(
9709925×
        bytes: &[u8],
9719925×
        me: ChangeHash,
9729925×
    ) -> Result<(Change, Vec<TextRef>), ObjectError> {
9739925×
        let mut c = cbor::Cursor::new(bytes);
9749925×
        let (major, n) = c.head()?;
9759925×
        if major != 5 {
9760×
            return schema("change: expected map");
9779925×
        }
9789925×
        let mut fields = Map::new();
9799925×
        let mut edits = Vec::new();
9809925×
        let mut texts = Vec::new();
9819925×
        let mut version = None;
9829925×
        let mut last: Option<u64> = None;
9839925×
        for _ in 0..n {
98499248×
            let k = map_key(&mut c, &mut last)?;
98599248×
            if k == 7 {
9869925×
                let Some(v) = version else {
9870×
                    return schema("change: version must come first");
988
                };
9899925×
                let (am, an) = c.head()?;
9909925×
                if am != 4 {
9910×
                    return schema("edits: expected array");
9929925×
                }
9939925×
                for _ in 0..an {
99451313×
                    edits.push(edit_skeleton(&mut c, v, me, &mut texts)?);
995
                }
9969924×
                fields.insert(7, Value::Array(Vec::new()));
997
            } else {
99889323×
                let val = c.value()?;
99989323×
                if k == 0 {
10009925×
                    version = Some(uint(&val, "version")?);
100179398×
                }
100289323×
                fields.insert(k, val);
1003
            }
1004
        }
10059924×
        if !c.at_end() {
10060×
            return Err(ObjectError::Cbor(cbor::CborError::TrailingBytes));
10079924×
        }
10089924×
        let mut change = Change::from_value(&Value::Map(fields))?;
10099924×
        change.edits = edits;
10109924×
        Ok((change, texts))
10119925×
    }
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.
10183261×
    pub fn decode_meta(bytes: &[u8]) -> Result<crate::state::ChangeMeta, ObjectError> {
10193261×
        let mut c = cbor::Cursor::new(bytes);
10203261×
        let (major, n) = c.head()?;
10213261×
        if major != 5 {
10220×
            return schema("change: expected map");
10233261×
        }
10243261×
        let mut fields = Map::new();
10253261×
        let mut last: Option<u64> = None;
10263261×
        for _ in 0..n {
102732610×
            let k = map_key(&mut c, &mut last)?;
102832610×
            if k == 6 || k == 7 {
10296522×
                c.skip()?;
10306522×
                fields.insert(k, Value::Array(Vec::new()));
1031
            } else {
103226088×
                fields.insert(k, c.value()?);
1033
            }
1034
        }
10353261×
        if !c.at_end() {
10360×
            return Err(ObjectError::Cbor(cbor::CborError::TrailingBytes));
10373261×
        }
10383261×
        Ok(crate::state::ChangeMeta::of(&Change::from_value(
10393261×
            &Value::Map(fields),
10400×
        )?))
10413261×
    }
1042
}
1043
1044
/// A canonical map key: an unsigned integer above the previous one.
1045382869×
fn map_key(c: &mut cbor::Cursor, last: &mut Option<u64>) -> Result<u64, ObjectError> {
1046382869×
    let (km, k) = c.head()?;
1047382869×
    if km != 0 || last.is_some_and(|l| k <= l) {
10480×
        return Err(ObjectError::Cbor(cbor::CborError::BadMapKey));
1049382869×
    }
1050382869×
    *last = Some(k);
1051382869×
    Ok(k)
1052382869×
}
1053
1054
/// One edit of [`Change::decode_skeleton`]: an insert's lines are left out.
105551313×
fn edit_skeleton(
105651313×
    c: &mut cbor::Cursor,
105751313×
    version: u64,
105851313×
    me: ChangeHash,
105951313×
    texts: &mut Vec<TextRef>,
106051313×
) -> Result<Edit, ObjectError> {
106151313×
    let (major, n) = c.head()?;
106251313×
    if major != 5 {
10630×
        return schema("edit: expected map");
106451313×
    }
106551313×
    let mut fields = Map::new();
106651313×
    let mut inline: Option<(usize, usize, u64)> = None;
106751313×
    let mut last: Option<u64> = None;
106851313×
    for _ in 0..n {
1069251011×
        let k = map_key(c, &mut last)?;
1070251011×
        if k == 4 {
107147877×
            let start = c.pos();
107247877×
            let (am, count) = c.head()?;
107347877×
            if am != 4 {
10740×
                return schema("lines: expected array");
107547877×
            }
107647877×
            for _ in 0..count {
107764227×
                c.skip()?;
1078
            }
107947877×
            inline = Some((start, c.pos(), count));
108047877×
            continue;
1081203134×
        }
1082203134×
        fields.insert(k, c.value()?);
1083
    }
108451313×
    let Some((start, end, count)) = inline else {
10853436×
        return Edit::from_value(&Value::Map(fields), version, &mut |text, count, form| {
1086145×
            texts.push(TextRef::Blob(*text, count, form));
1087145×
            Ok(Lines::default())
1088145×
        });
1089
    };
109047877×
    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");
109247877×
    }
109347877×
    if count == 0 {
10940×
        return schema("insert with no lines");
109547877×
    }
109647877×
    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");
109847876×
    }
109947876×
    let (Ok(start), Ok(end)) = (u32::try_from(start), u32::try_from(end)) else {
11000×
        return schema("change too large");
1101
    };
110247876×
    texts.push(TextRef::Inline {
110347876×
        change: me,
110447876×
        start,
110547876×
        end,
110647876×
    });
1107
    Ok(Edit::Insert {
110847876×
        node: node_id(field(&fields, 1, "edit.node")?, "edit.node")?,
110947876×
        after: AtomRef::from_value(field(&fields, 2, "after")?, "after")?,
111047876×
        before: AtomRef::from_value(field(&fields, 3, "before")?, "before")?,
111147876×
        lines: Lines::default(),
1112
    })
111351313×
}
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.
112599×
fn text_form(version: u64, lines: &Lines) -> TextForm {
112698×
    match version {
112799×
        ..=2 => TextForm::Cbor,
112898×
        _ if lines.is_split_form() => TextForm::Raw,
11291×
        _ => TextForm::CborFallback,
1130
    }
113199×
}
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.
1136136×
pub fn text_lines(content: &[u8], count: u32, form: TextForm) -> Result<Lines, ObjectError> {
1137136×
    let lines = match form {
1138130×
        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.
1143136×
    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
        ));
1148134×
    }
1149134×
    if form == TextForm::CborFallback && lines.is_split_form() {
11501×
        return schema("these lines are stored as their bytes in a version 3 change");
1151133×
    }
1152133×
    if lines.len() != count as usize {
11532×
        return schema(format!(
1154
            "a text blob holds {} lines, the insert says {count}",
11552×
            lines.len()
1156
        ));
1157131×
    }
1158131×
    Ok(lines)
1159136×
}
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).
1173583×
    pub fn of(content: &[u8]) -> Blob {
1174
        Blob {
1175583×
            length: content.len() as u64,
1176583×
            chunks: crate::chunk::chunks(content)
1177583×
                .into_iter()
1178773×
                .map(|c| hash_object(ObjectType::Chunk, c))
1179583×
                .collect(),
1180
        }
1181583×
    }
1182
1183711×
    pub fn encode(&self) -> Vec<u8> {
1184711×
        cbor::encode(&Value::map([
1185711×
            (0, Value::Uint(FORMAT_VERSION)),
1186711×
            (1, Value::Uint(self.length)),
1187
            (
1188
                2,
1189
                Value::Array(
1190711×
                    self.chunks
1191711×
                        .iter()
11921000×
                        .map(|c| Value::Bytes(c.0.to_vec()))
1193711×
                        .collect(),
1194
                ),
1195
            ),
1196
        ]))
1197711×
    }
1198431×
    pub fn hash(&self) -> ObjectRef {
1199431×
        hash_object(ObjectType::Blob, &self.encode())
1200431×
    }
1201596×
    pub fn decode(bytes: &[u8]) -> Result<Blob, ObjectError> {
1202596×
        let v = cbor::decode(bytes)?;
1203596×
        let m = map(&v, "blob")?;
1204596×
        check_version(m)?;
1205
        Ok(Blob {
1206596×
            length: uint(field(m, 1, "length")?, "length")?,
1207596×
            chunks: array(field(m, 2, "chunks")?, "chunks")?
1208596×
                .iter()
1209999×
                .map(|c| oref(c, "chunk"))
1210596×
                .collect::<Result<Vec<_>, _>>()?,
1211
        })
1212596×
    }
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 {
122715×
    pub fn encode(&self) -> Vec<u8> {
122815×
        cbor::encode(&Value::map([
122915×
            (0, Value::Uint(FORMAT_VERSION)),
1230
            (
1231
                1,
1232
                Value::Array(
123315×
                    self.heads
123415×
                        .iter()
123516×
                        .map(|h| Value::Bytes(h.0.to_vec()))
123615×
                        .collect(),
1237
                ),
1238
            ),
123915×
            (2, Value::Uint(self.count)),
124015×
            (3, Value::Bytes(self.payload.0.to_vec())),
1241
        ]))
124215×
    }
12430×
    pub fn hash(&self) -> ObjectRef {
12440×
        hash_object(ObjectType::Checkpoint, &self.encode())
12450×
    }
1246115×
    pub fn decode(bytes: &[u8]) -> Result<Checkpoint, ObjectError> {
1247115×
        let v = cbor::decode(bytes)?;
1248115×
        let m = map(&v, "checkpoint")?;
1249115×
        check_version(m)?;
1250
        Ok(Checkpoint {
1251115×
            heads: array(field(m, 1, "heads")?, "heads")?
1252115×
                .iter()
1253117×
                .map(|h| oref(h, "head"))
1254115×
                .collect::<Result<Vec<_>, _>>()?,
1255115×
            count: uint(field(m, 2, "count")?, "count")?,
1256115×
            payload: oref(field(m, 3, "payload")?, "payload")?,
1257
        })
1258115×
    }
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 {
12703773×
    pub fn new(mut heads: Vec<ChangeHash>) -> StateObject {
12713773×
        heads.sort();
12723773×
        heads.dedup();
12733773×
        StateObject { heads }
12743773×
    }
12753769×
    pub fn encode(&self) -> Vec<u8> {
12763769×
        debug_assert!(self.heads.windows(2).all(|w| w[0] < w[1]));
12773769×
        cbor::encode(&Value::map([
12783769×
            (0, Value::Uint(FORMAT_VERSION)),
1279
            (
1280
                1,
1281
                Value::Array(
12823769×
                    self.heads
12833769×
                        .iter()
12844455×
                        .map(|h| Value::Bytes(h.0.to_vec()))
12853769×
                        .collect(),
1286
                ),
1287
            ),
1288
        ]))
12893769×
    }
12902×
    pub fn hash(&self) -> ObjectRef {
12912×
        hash_object(ObjectType::State, &self.encode())
12922×
    }
12936353×
    pub fn decode(bytes: &[u8]) -> Result<StateObject, ObjectError> {
12946353×
        let v = cbor::decode(bytes)?;
12956353×
        let m = map(&v, "state")?;
12966353×
        check_version(m)?;
12976353×
        let heads = array(field(m, 1, "heads")?, "heads")?
12986353×
            .iter()
12999823×
            .map(|h| oref(h, "head"))
13006353×
            .collect::<Result<Vec<_>, _>>()?;
13016353×
        if !heads.windows(2).all(|w| w[0] < w[1]) {
13020×
            return schema("state heads must be sorted and unique");
13036353×
        }
13046353×
        Ok(StateObject { heads })
13056353×
    }
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
}