OXYGENHUB

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

1065 of 1128 lines run, 223 of 298 functions · run #403 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
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
601051333×
pub(crate) fn field<'a>(m: &'a Map, k: u64, what: &str) -> Result<&'a Value, ObjectError> {
611051333×
    m.get(&k)
621051333×
        .ok_or_else(|| ObjectError::Schema(format!("missing field {k} ({what})")))
631051333×
}
64426405×
pub(crate) fn uint(v: &Value, what: &str) -> Result<u64, ObjectError> {
65426405×
    v.as_uint()
66426405×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected unsigned integer")))
67426405×
}
6877527×
pub(crate) fn u32_(v: &Value, what: &str) -> Result<u32, ObjectError> {
6977527×
    u32::try_from(uint(v, what)?).map_err(|_| ObjectError::Schema(format!("{what}: exceeds u32")))
7077527×
}
71146885×
pub(crate) fn text<'a>(v: &'a Value, what: &str) -> Result<&'a str, ObjectError> {
72146885×
    v.as_text()
73146885×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected text")))
74146885×
}
75331275×
pub(crate) fn array<'a>(v: &'a Value, what: &str) -> Result<&'a [Value], ObjectError> {
76331275×
    v.as_array()
77331275×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected array")))
78331275×
}
79156625×
pub(crate) fn map<'a>(v: &'a Value, what: &str) -> Result<&'a Map, ObjectError> {
80156625×
    v.as_map()
81156625×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected map")))
82156625×
}
83468619×
pub(crate) fn bytes<'a>(v: &'a Value, what: &str) -> Result<&'a [u8], ObjectError> {
84468619×
    v.as_bytes()
85468619×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected bytes")))
86468619×
}
87162136×
pub(crate) fn oref(v: &Value, what: &str) -> Result<ObjectRef, ObjectError> {
88162136×
    ObjectRef::from_slice(bytes(v, what)?)
89162135×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected 32 bytes")))
90162136×
}
91157327×
pub(crate) fn node_id(v: &Value, what: &str) -> Result<NodeId, ObjectError> {
92157327×
    NodeId::from_slice(bytes(v, what)?)
93157327×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected 16 bytes")))
94157327×
}
9535184×
pub(crate) fn check_version(m: &Map) -> Result<(), ObjectError> {
9635184×
    let v = uint(field(m, 0, "version")?, "version")?;
9735184×
    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
        });
11135184×
    }
11235184×
    Ok(())
11335184×
}
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 {
1257401×
    pub fn now() -> Hlc {
1267401×
        let wall_ms = std::time::SystemTime::now()
1277401×
            .duration_since(std::time::UNIX_EPOCH)
1287401×
            .map(|d| d.as_millis() as u64)
1297401×
            .unwrap_or(0);
1307401×
        Hlc {
1317401×
            wall_ms,
1327401×
            logical: 0,
1337401×
        }
1347401×
    }
13514424×
    pub(crate) fn to_value(self) -> Value {
13614424×
        Value::map([
13714424×
            (0, Value::Uint(self.wall_ms)),
13814424×
            (1, Value::Uint(self.logical as u64)),
13914424×
        ])
14014424×
    }
14142755×
    pub(crate) fn from_value(v: &Value) -> Result<Hlc, ObjectError> {
14242755×
        let m = map(v, "hlc")?;
143
        Ok(Hlc {
14442755×
            wall_ms: uint(field(m, 0, "hlc.wall_ms")?, "hlc.wall_ms")?,
14542755×
            logical: u32_(field(m, 1, "hlc.logical")?, "hlc.logical")?,
146
        })
14742755×
    }
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 {
16274104×
    pub(crate) fn tag(self) -> u64 {
16374104×
        match self {
16473032×
            NodeKind::File => 0,
1651050×
            NodeKind::Dir => 1,
1663×
            NodeKind::Symlink => 2,
16719×
            NodeKind::Subrepo => 3,
168
        }
16974104×
    }
17099644×
    pub(crate) fn from_tag(t: u64) -> Result<NodeKind, ObjectError> {
17199644×
        Ok(match t {
17297317×
            0 => NodeKind::File,
1732155×
            1 => NodeKind::Dir,
1749×
            2 => NodeKind::Symlink,
175163×
            3 => NodeKind::Subrepo,
1760×
            _ => return schema(format!("unknown node kind {t}")),
177
        })
17899644×
    }
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
    };
19773714×
    pub(crate) fn bits(self) -> u64 {
19873714×
        (self.exec as u64) | ((self.opaque as u64) << 1)
19973714×
    }
20099606×
    pub(crate) fn from_bits(b: u64) -> Result<Mode, ObjectError> {
20199606×
        if b > 3 {
2021×
            return schema(format!("unknown mode bits {b}"));
20399605×
        }
20499605×
        Ok(Mode {
20599605×
            exec: b & 1 != 0,
20699605×
            opaque: b & 2 != 0,
20799605×
        })
20899606×
    }
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 {
220649×
    fn to_value(self) -> Value {
221649×
        Value::Array(vec![
222649×
            Value::Bytes(self.change.0.to_vec()),
223649×
            Value::Uint(self.index as u64),
224649×
        ])
225649×
    }
2261064×
    fn from_value(v: &Value, what: &str) -> Result<OpRef, ObjectError> {
2271064×
        let a = array(v, what)?;
2281064×
        if a.len() != 2 {
2290×
            return schema(format!("{what}: expected [hash, index]"));
2301064×
        }
231
        Ok(OpRef {
2321064×
            change: oref(&a[0], what)?,
2331064×
            index: u32_(&a[1], what)?,
234
        })
2351064×
    }
236
    /// Replace a self reference with the concrete change hash.
2371064×
    pub fn resolve(self, me: ChangeHash) -> OpRef {
2381064×
        if self.change.is_zero() {
2391×
            OpRef { change: me, ..self }
240
        } else {
2411063×
            self
242
        }
2431064×
    }
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).
27349522×
pub fn validate_name(name: &str) -> Result<(), ObjectError> {
27449522×
    if name.is_empty() || name == "." || name == ".." || name.contains('/') || name.contains('\0') {
2756×
        return schema(format!("invalid placement name {name:?}"));
27649516×
    }
27749516×
    Ok(())
27849522×
}
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
2906971×
    fn to_value(&self) -> Value {
29113327×
        let nid = |n: &NodeId| Value::Bytes(n.0.to_vec());
2926971×
        match self {
293
            TreeOp::AddNode {
2946322×
                node,
2956322×
                kind,
2966322×
                mode,
2976322×
                parent,
2986322×
                name,
2996322×
            } => Value::map([
3006322×
                (0, Value::Uint(0)),
3016322×
                (1, nid(node)),
3026322×
                (2, Value::Uint(kind.tag())),
3036322×
                (3, Value::Uint(mode.bits())),
3046322×
                (4, nid(parent)),
3056322×
                (5, Value::Text(name.clone())),
3066322×
            ]),
307548×
            TreeOp::RemoveNode { node, placement } => Value::map([
308548×
                (0, Value::Uint(1)),
309548×
                (1, nid(node)),
310548×
                (2, placement.to_value()),
311548×
            ]),
312
            TreeOp::Move {
31334×
                node,
31434×
                old,
31534×
                parent,
31634×
                name,
31734×
            } => Value::map([
31834×
                (0, Value::Uint(2)),
31934×
                (1, nid(node)),
32034×
                (2, old.to_value()),
32134×
                (4, nid(parent)),
32234×
                (5, Value::Text(name.clone())),
32334×
            ]),
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
        }
3316971×
    }
332
33350387×
    fn from_value(v: &Value) -> Result<TreeOp, ObjectError> {
33450387×
        let m = map(v, "tree_op")?;
33550387×
        let tag = uint(field(m, 0, "tree_op tag")?, "tree_op tag")?;
33650387×
        let node = node_id(field(m, 1, "tree_op.node")?, "tree_op.node")?;
33750387×
        let op = match tag {
338
            0 => {
33949323×
                let name = text(field(m, 5, "name")?, "name")?.to_owned();
34049323×
                validate_name(&name)?;
341
                TreeOp::AddNode {
34249323×
                    node,
34349323×
                    kind: NodeKind::from_tag(uint(field(m, 2, "kind")?, "kind")?)?,
34449323×
                    mode: Mode::from_bits(uint(field(m, 3, "mode")?, "mode")?)?,
34549323×
                    parent: node_id(field(m, 4, "parent")?, "parent")?,
34649323×
                    name,
347
                }
348
            }
349
            1 => TreeOp::RemoveNode {
350853×
                node,
351853×
                placement: OpRef::from_value(field(m, 2, "placement")?, "placement")?,
352
            },
353
            2 => {
354172×
                let name = text(field(m, 5, "name")?, "name")?.to_owned();
355172×
                validate_name(&name)?;
356
                TreeOp::Move {
357172×
                    node,
358172×
                    old: OpRef::from_value(field(m, 2, "old")?, "old")?,
359172×
                    parent: node_id(field(m, 4, "parent")?, "parent")?,
360172×
                    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
        };
37050387×
        if node.is_root() {
3710×
            return schema("tree op on the root node");
37250387×
        }
37350387×
        Ok(op)
37450387×
    }
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 {
38716630×
    fn to_value(self) -> Value {
38816630×
        match self {
3895908×
            AtomRef::Start => Value::Uint(0),
3906127×
            AtomRef::End => Value::Uint(1),
3914595×
            AtomRef::Atom { change, index } => Value::Array(vec![
3924595×
                Value::Bytes(change.0.to_vec()),
3934595×
                Value::Uint(index as u64),
3944595×
            ]),
395
        }
39616630×
    }
397105388×
    fn from_value(v: &Value, what: &str) -> Result<AtomRef, ObjectError> {
3989932×
        match v {
39947002×
            Value::Uint(0) => Ok(AtomRef::Start),
40048454×
            Value::Uint(1) => Ok(AtomRef::End),
4019932×
            Value::Array(a) if a.len() == 2 => Ok(AtomRef::Atom {
4029932×
                change: oref(&a[0], what)?,
4039932×
                index: u32_(&a[1], what)?,
404
            }),
4050×
            _ => schema(format!("{what}: expected atom reference")),
406
        }
407105388×
    }
40867390×
    pub fn resolve(self, me: ChangeHash) -> AtomRef {
40910542×
        match self {
41010542×
            AtomRef::Atom { change, index } if change.is_zero() => {
41141×
                AtomRef::Atom { change: me, index }
412
            }
41367349×
            other => other,
414
        }
41567390×
    }
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 {
4272490×
    fn to_value(self) -> Value {
4282490×
        Value::Array(vec![
4292490×
            Value::Bytes(self.change.0.to_vec()),
4302490×
            Value::Uint(self.from as u64),
4312490×
            Value::Uint(self.to as u64),
4322490×
        ])
4332490×
    }
4344576×
    fn from_value(v: &Value) -> Result<AtomRange, ObjectError> {
4354576×
        let a = array(v, "atom range")?;
4364576×
        if a.len() != 3 {
4370×
            return schema("atom range: expected [hash, from, to]");
4384576×
        }
4394576×
        let r = AtomRange {
4404576×
            change: oref(&a[0], "range.change")?,
4414576×
            from: u32_(&a[1], "range.from")?,
4424576×
            to: u32_(&a[2], "range.to")?,
443
        };
4444576×
        if r.from >= r.to {
4450×
            return schema("atom range: empty or inverted");
4464576×
        }
4474576×
        Ok(r)
4484576×
    }
4494888×
    pub fn resolve(self, me: ChangeHash) -> AtomRange {
4504888×
        if self.change.is_zero() {
45118×
            AtomRange { change: me, ..self }
452
        } else {
4534870×
            self
454
        }
4554888×
    }
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 {
47850479×
    pub fn node(&self) -> NodeId {
47950479×
        match self {
48046499×
            Edit::Insert { node, .. } | Edit::Delete { node, .. } | Edit::Replace { node, .. } => {
48150479×
                *node
482
            }
483
        }
48450479×
    }
485
486
    /// Whether this insert is stored as a text blob in a change of `version`.
48710679×
    fn stored_text(&self, version: u64) -> bool {
4888318×
        matches!(self, Edit::Insert { lines, .. }
4898318×
            if version >= 2 && cbor::byte_strings_len(lines) >= TEXT_BLOB_MIN)
49010679×
    }
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).
49610672×
    fn to_value(&self, stored: Option<(ObjectRef, TextForm)>, compact: bool) -> Value {
49710672×
        let nid = |n: &NodeId| Value::Bytes(n.0.to_vec());
49810672×
        let opt = |o: &Option<ObjectRef>| match o {
499253×
            Some(r) => Value::Bytes(r.0.to_vec()),
500161×
            None => Value::Null,
501414×
        };
50210672×
        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 {
5278216×
                    node,
5288216×
                    after,
5298216×
                    before,
5308216×
                    lines,
531
                },
532
                None,
5338216×
            ) => Value::map([
5348216×
                (0, Value::Uint(0)),
5358216×
                (1, nid(node)),
5368216×
                (2, after.to_value()),
5378216×
                (3, before.to_value()),
538
                (
539
                    4,
5408216×
                    if compact {
5418210×
                        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
            ]),
5472150×
            (Edit::Delete { node, atoms }, _) => Value::map([
5482150×
                (0, Value::Uint(1)),
5492150×
                (1, nid(node)),
550
                (
551
                    2,
5522490×
                    Value::Array(atoms.iter().map(|r| r.to_value()).collect()),
553
                ),
554
            ]),
555207×
            (Edit::Replace { node, old, new }, _) => Value::map([
556207×
                (0, Value::Uint(2)),
557207×
                (1, nid(node)),
558207×
                (2, opt(old)),
559207×
                (3, opt(new)),
560207×
            ]),
561
        }
56210672×
    }
563
5649193×
    fn from_value(v: &Value, version: u64, resolve: &mut Resolver) -> Result<Edit, ObjectError> {
5659193×
        let m = map(v, "edit")?;
5669193×
        let tag = uint(field(m, 0, "edit tag")?, "edit tag")?;
5679193×
        let node = node_id(field(m, 1, "edit.node")?, "edit.node")?;
5689193×
        let opt = |v: &Value, what: &str| -> Result<Option<ObjectRef>, ObjectError> {
5692200×
            if v.is_null() {
570886×
                Ok(None)
571
            } else {
5721314×
                Ok(Some(oref(v, what)?))
573
            }
5742200×
        };
5759193×
        Ok(match tag {
576
            0 => {
5774445×
                let lines = match (m.get(&4), m.get(&5)) {
5784180×
                    (Some(inline), None) => {
5794180×
                        let lines = array_lines(inline)?;
5804180×
                        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");
5824179×
                        }
5834179×
                        if lines.is_empty() {
5840×
                            return schema("insert with no lines");
5854179×
                        }
5864179×
                        lines
587
                    }
588265×
                    (None, Some(text)) if version >= 2 => {
589265×
                        let text = oref(text, "insert text")?;
590265×
                        let count = u32_(field(m, 6, "insert line count")?, "insert line count")?;
591265×
                        if count == 0 {
5920×
                            return schema("insert with no lines");
593265×
                        }
594265×
                        let form = match (version, m.get(&7)) {
5951×
                            (2, None) => TextForm::Cbor,
596263×
                            (_, 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`).
601265×
                        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 {
6104442×
                    node,
6114442×
                    after: AtomRef::from_value(field(m, 2, "after")?, "after")?,
6124442×
                    before: AtomRef::from_value(field(m, 3, "before")?, "before")?,
6134442×
                    lines,
614
                }
615
            }
616
            1 => {
6173648×
                let atoms = array(field(m, 2, "atoms")?, "atoms")?
6183648×
                    .iter()
6193648×
                    .map(AtomRange::from_value)
6203648×
                    .collect::<Result<Vec<_>, _>>()?;
6213648×
                if atoms.is_empty() {
6220×
                    return schema("delete with no atoms");
6233648×
                }
6243648×
                Edit::Delete { node, atoms }
625
            }
626
            2 => Edit::Replace {
6271100×
                node,
6281100×
                old: opt(field(m, 2, "old")?, "old")?,
6291100×
                new: opt(field(m, 3, "new")?, "new")?,
630
            },
6310×
            _ => return schema(format!("unknown edit tag {tag}")),
632
        })
6339193×
    }
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 {
64617874×
    pub(crate) fn tag(self) -> u64 {
64717874×
        match self {
64814780×
            ChangeKind::Normal => 0,
64951×
            ChangeKind::Resolution => 1,
6503043×
            ChangeKind::WorkingCopy => 2,
651
        }
65217874×
    }
65331916×
    pub(crate) fn from_tag(t: u64) -> Result<ChangeKind, ObjectError> {
65431916×
        Ok(match t {
65528360×
            0 => ChangeKind::Normal,
656184×
            1 => ChangeKind::Resolution,
6573372×
            2 => ChangeKind::WorkingCopy,
6580×
            _ => return schema(format!("unknown change kind {t}")),
659
        })
66031916×
    }
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 {
6806545×
    pub fn normalize(&mut self) {
6816545×
        self.deps.sort();
6826545×
        self.deps.dedup();
6836545×
    }
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.
6938981×
    fn stored_texts(&self, sink: &mut TextSink) -> Vec<Option<(ObjectRef, TextForm)>> {
694
        use rayon::prelude::*;
6958981×
        let mut refs: Vec<Option<(ObjectRef, TextForm)>> = vec![None; self.edits.len()];
6968981×
        let stored: Vec<usize> = (0..self.edits.len())
69710672×
            .filter(|i| self.edits[*i].stored_text(self.version))
6988981×
            .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.
7028981×
        let mut batches: Vec<&[usize]> = Vec::new();
7038981×
        let (mut start, mut bytes) = (0, 0usize);
7048981×
        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
        }
7138981×
        if start < stored.len() {
71498×
            batches.push(&stored[start..]);
7158883×
        }
7168981×
        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
        }
7428981×
        refs
7438981×
    }
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.
7478981×
    fn value_with(&self, sink: &mut TextSink, compact: bool) -> Value {
7488981×
        Value::map([
7498981×
            (0, Value::Uint(self.version)),
7508981×
            (1, Value::Bytes(self.change_id.0.to_vec())),
751
            (
752
                2,
753
                Value::Array(
7548981×
                    self.deps
7558981×
                        .iter()
75610478×
                        .map(|d| Value::Bytes(d.0.to_vec()))
7578981×
                        .collect(),
758
                ),
759
            ),
7608981×
            (3, Value::Bytes(self.author.0.to_vec())),
7618981×
            (4, self.hlc.to_value()),
7628981×
            (5, Value::Text(self.message.clone())),
763
            (
764
                6,
7658981×
                Value::Array(self.tree_ops.iter().map(|t| t.to_value()).collect()),
766
            ),
767
            (
768
                7,
769
                Value::Array(
7708981×
                    self.edits
7718981×
                        .iter()
7728981×
                        .zip(self.stored_texts(sink))
77310672×
                        .map(|(e, stored)| e.to_value(stored, compact))
7748981×
                        .collect(),
775
                ),
776
            ),
7778981×
            (8, Value::Uint(self.kind.tag())),
7788981×
            (9, Value::Map(BTreeMap::new())),
779
        ])
7808981×
    }
781
7824420×
    pub fn encode(&self) -> Vec<u8> {
7834420×
        debug_assert!(
7844420×
            self.deps.windows(2).all(|w| w[0] < w[1]),
785
            "deps must be normalized"
786
        );
7874420×
        cbor::encode(&self.value_with(&mut |_| true, true))
7884420×
    }
789
790
    /// The encoding and the text blobs its large inserts are stored as,
791
    /// which must be stored with it.
792128×
    pub fn encode_parts(&self) -> (Vec<u8>, Vec<StoredText>) {
793128×
        debug_assert!(
794128×
            self.deps.windows(2).all(|w| w[0] < w[1]),
795
            "deps must be normalized"
796
        );
797128×
        let mut texts = Vec::new();
798128×
        let bytes = cbor::encode(&self.value_with(
7995×
            &mut |batch| {
8005×
                texts.extend(batch);
8015×
                true
8025×
            },
803
            true,
804
        ));
805128×
        (bytes, texts)
806128×
    }
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.
8114427×
    pub fn encode_streaming<E>(
8124427×
        &self,
8134427×
        mut store: impl FnMut(Vec<StoredText>) -> Result<(), E>,
8144427×
    ) -> Result<Vec<u8>, E> {
8154427×
        debug_assert!(
8164427×
            self.deps.windows(2).all(|w| w[0] < w[1]),
817
            "deps must be normalized"
818
        );
8194427×
        let mut failed = None;
8204427×
        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
        );
8304427×
        match failed {
8310×
            Some(e) => Err(e),
8324427×
            None => Ok(cbor::encode(&value)),
833
        }
8344427×
    }
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
8413995×
    pub fn hash(&self) -> ChangeHash {
8423995×
        hash_object(ObjectType::Change, &self.encode())
8433995×
    }
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).
8586152×
    pub fn decode_with(bytes: &[u8], resolve: &mut Resolver) -> Result<Change, ObjectError> {
8596152×
        let v = cbor::decode(bytes)?;
8606152×
        Self::from_value_with(&v, resolve)
8616152×
    }
862
86313554×
    pub fn from_value(v: &Value) -> Result<Change, ObjectError> {
86413554×
        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×
        })
87013554×
    }
871
87219706×
    pub(crate) fn from_value_with(
87319706×
        v: &Value,
87419706×
        resolve: &mut Resolver,
87519706×
    ) -> Result<Change, ObjectError> {
87619706×
        let m = map(v, "change")?;
87719706×
        let version = uint(field(m, 0, "version")?, "version")?;
87819706×
        if !(1..=CHANGE_VERSION).contains(&version) {
8791×
            return schema(format!("unsupported change format version {version}"));
88019705×
        }
88119705×
        let change_id = ChangeId::from_slice(bytes(field(m, 1, "change_id")?, "change_id")?)
88219705×
            .ok_or_else(|| ObjectError::Schema("change_id: expected 16 bytes".into()))?;
88319705×
        let deps = array(field(m, 2, "deps")?, "deps")?
88419705×
            .iter()
88519705×
            .map(|d| oref(d, "dep"))
88619705×
            .collect::<Result<Vec<_>, _>>()?;
88719705×
        if !deps.windows(2).all(|w| w[0] < w[1]) {
8881×
            return schema("deps must be sorted and unique");
88919704×
        }
89019704×
        if deps.iter().any(|d| d.is_zero()) {
8910×
            return schema("deps may not contain the self reference");
89219704×
        }
89319704×
        let extra = map(field(m, 9, "extra")?, "extra")?;
89419704×
        if !extra.is_empty() {
8951×
            return schema("extra must be empty in format version 1");
89619703×
        }
897
        Ok(Change {
89819703×
            version,
89919703×
            change_id,
90019703×
            deps,
90119703×
            author: oref(field(m, 3, "author")?, "author")?,
90219703×
            hlc: Hlc::from_value(field(m, 4, "hlc")?)?,
90319703×
            message: text(field(m, 5, "message")?, "message")?.to_owned(),
90419703×
            tree_ops: array(field(m, 6, "tree_ops")?, "tree_ops")?
90519703×
                .iter()
90619703×
                .map(TreeOp::from_value)
90719703×
                .collect::<Result<Vec<_>, _>>()?,
90819703×
            edits: array(field(m, 7, "edits")?, "edits")?
90919703×
                .iter()
91019703×
                .map(|e| Edit::from_value(e, version, resolve))
91119703×
                .collect::<Result<Vec<_>, _>>()?,
91219700×
            kind: ChangeKind::from_tag(uint(field(m, 8, "kind")?, "kind")?)?,
913
        })
91419706×
    }
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`]).
94433762×
pub fn inline_lines(array: &[u8]) -> Result<Lines, ObjectError> {
94533762×
    let v = cbor::decode(array)?;
94633762×
    let lines = array_lines(&v)?;
94733762×
    if lines.is_empty() {
9480×
        return schema("insert with no lines");
94933762×
    }
95033762×
    Ok(lines)
95133762×
}
952
953
/// The lines of a CBOR array of byte strings, copied once into one buffer.
95437948×
fn array_lines(v: &Value) -> Result<Lines, ObjectError> {
95537948×
    Ok(array(v, "lines")?
95637948×
        .iter()
95761508×
        .map(|l| bytes(l, "line"))
95837948×
        .collect::<Result<Vec<&[u8]>, _>>()?
95937948×
        .into_iter()
96037948×
        .collect())
96137948×
}
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.
96910232×
    pub fn decode_skeleton(
97010232×
        bytes: &[u8],
97110232×
        me: ChangeHash,
97210232×
    ) -> Result<(Change, Vec<TextRef>), ObjectError> {
97310232×
        let mut c = cbor::Cursor::new(bytes);
97410232×
        let (major, n) = c.head()?;
97510232×
        if major != 5 {
9760×
            return schema("change: expected map");
97710232×
        }
97810232×
        let mut fields = Map::new();
97910232×
        let mut edits = Vec::new();
98010232×
        let mut texts = Vec::new();
98110232×
        let mut version = None;
98210232×
        let mut last: Option<u64> = None;
98310232×
        for _ in 0..n {
984102318×
            let k = map_key(&mut c, &mut last)?;
985102318×
            if k == 7 {
98610232×
                let Some(v) = version else {
9870×
                    return schema("change: version must come first");
988
                };
98910232×
                let (am, an) = c.head()?;
99010232×
                if am != 4 {
9910×
                    return schema("edits: expected array");
99210232×
                }
99310232×
                for _ in 0..an {
99452021×
                    edits.push(edit_skeleton(&mut c, v, me, &mut texts)?);
995
                }
99610231×
                fields.insert(7, Value::Array(Vec::new()));
997
            } else {
99892086×
                let val = c.value()?;
99992086×
                if k == 0 {
100010232×
                    version = Some(uint(&val, "version")?);
100181854×
                }
100292086×
                fields.insert(k, val);
1003
            }
1004
        }
100510231×
        if !c.at_end() {
10060×
            return Err(ObjectError::Cbor(cbor::CborError::TrailingBytes));
100710231×
        }
100810231×
        let mut change = Change::from_value(&Value::Map(fields))?;
100910231×
        change.edits = edits;
101010231×
        Ok((change, texts))
101110232×
    }
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.
10183319×
    pub fn decode_meta(bytes: &[u8]) -> Result<crate::state::ChangeMeta, ObjectError> {
10193319×
        let mut c = cbor::Cursor::new(bytes);
10203319×
        let (major, n) = c.head()?;
10213319×
        if major != 5 {
10220×
            return schema("change: expected map");
10233319×
        }
10243319×
        let mut fields = Map::new();
10253319×
        let mut last: Option<u64> = None;
10263319×
        for _ in 0..n {
102733190×
            let k = map_key(&mut c, &mut last)?;
102833190×
            if k == 6 || k == 7 {
10296638×
                c.skip()?;
10306638×
                fields.insert(k, Value::Array(Vec::new()));
1031
            } else {
103226552×
                fields.insert(k, c.value()?);
1033
            }
1034
        }
10353319×
        if !c.at_end() {
10360×
            return Err(ObjectError::Cbor(cbor::CborError::TrailingBytes));
10373319×
        }
10383319×
        Ok(crate::state::ChangeMeta::of(&Change::from_value(
10393319×
            &Value::Map(fields),
10400×
        )?))
10413319×
    }
1042
}
1043
1044
/// A canonical map key: an unsigned integer above the previous one.
1045389374×
fn map_key(c: &mut cbor::Cursor, last: &mut Option<u64>) -> Result<u64, ObjectError> {
1046389374×
    let (km, k) = c.head()?;
1047389374×
    if km != 0 || last.is_some_and(|l| k <= l) {
10480×
        return Err(ObjectError::Cbor(cbor::CborError::BadMapKey));
1049389374×
    }
1050389374×
    *last = Some(k);
1051389374×
    Ok(k)
1052389374×
}
1053
1054
/// One edit of [`Change::decode_skeleton`]: an insert's lines are left out.
105552021×
fn edit_skeleton(
105652021×
    c: &mut cbor::Cursor,
105752021×
    version: u64,
105852021×
    me: ChangeHash,
105952021×
    texts: &mut Vec<TextRef>,
106052021×
) -> Result<Edit, ObjectError> {
106152021×
    let (major, n) = c.head()?;
106252021×
    if major != 5 {
10630×
        return schema("edit: expected map");
106452021×
    }
106552021×
    let mut fields = Map::new();
106652021×
    let mut inline: Option<(usize, usize, u64)> = None;
106752021×
    let mut last: Option<u64> = None;
106852021×
    for _ in 0..n {
1069253866×
        let k = map_key(c, &mut last)?;
1070253866×
        if k == 4 {
107148253×
            let start = c.pos();
107248253×
            let (am, count) = c.head()?;
107348253×
            if am != 4 {
10740×
                return schema("lines: expected array");
107548253×
            }
107648253×
            for _ in 0..count {
107764994×
                c.skip()?;
1078
            }
107948253×
            inline = Some((start, c.pos(), count));
108048253×
            continue;
1081205613×
        }
1082205613×
        fields.insert(k, c.value()?);
1083
    }
108452021×
    let Some((start, end, count)) = inline else {
10853768×
        return Edit::from_value(&Value::Map(fields), version, &mut |text, count, form| {
1086146×
            texts.push(TextRef::Blob(*text, count, form));
1087146×
            Ok(Lines::default())
1088146×
        });
1089
    };
109048253×
    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");
109248253×
    }
109348253×
    if count == 0 {
10940×
        return schema("insert with no lines");
109548253×
    }
109648253×
    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");
109848252×
    }
109948252×
    let (Ok(start), Ok(end)) = (u32::try_from(start), u32::try_from(end)) else {
11000×
        return schema("change too large");
1101
    };
110248252×
    texts.push(TextRef::Inline {
110348252×
        change: me,
110448252×
        start,
110548252×
        end,
110648252×
    });
1107
    Ok(Edit::Insert {
110848252×
        node: node_id(field(&fields, 1, "edit.node")?, "edit.node")?,
110948252×
        after: AtomRef::from_value(field(&fields, 2, "after")?, "after")?,
111048252×
        before: AtomRef::from_value(field(&fields, 3, "before")?, "before")?,
111148252×
        lines: Lines::default(),
1112
    })
111352021×
}
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.
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).
1173568×
    pub fn of(content: &[u8]) -> Blob {
1174
        Blob {
1175568×
            length: content.len() as u64,
1176568×
            chunks: crate::chunk::chunks(content)
1177568×
                .into_iter()
1178756×
                .map(|c| hash_object(ObjectType::Chunk, c))
1179568×
                .collect(),
1180
        }
1181568×
    }
1182
1183696×
    pub fn encode(&self) -> Vec<u8> {
1184696×
        cbor::encode(&Value::map([
1185696×
            (0, Value::Uint(FORMAT_VERSION)),
1186696×
            (1, Value::Uint(self.length)),
1187
            (
1188
                2,
1189
                Value::Array(
1190696×
                    self.chunks
1191696×
                        .iter()
1192983×
                        .map(|c| Value::Bytes(c.0.to_vec()))
1193696×
                        .collect(),
1194
                ),
1195
            ),
1196
        ]))
1197696×
    }
1198431×
    pub fn hash(&self) -> ObjectRef {
1199431×
        hash_object(ObjectType::Blob, &self.encode())
1200431×
    }
1201563×
    pub fn decode(bytes: &[u8]) -> Result<Blob, ObjectError> {
1202563×
        let v = cbor::decode(bytes)?;
1203563×
        let m = map(&v, "blob")?;
1204563×
        check_version(m)?;
1205
        Ok(Blob {
1206563×
            length: uint(field(m, 1, "length")?, "length")?,
1207563×
            chunks: array(field(m, 2, "chunks")?, "chunks")?
1208563×
                .iter()
1209961×
                .map(|c| oref(c, "chunk"))
1210563×
                .collect::<Result<Vec<_>, _>>()?,
1211
        })
1212563×
    }
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 {
12703795×
    pub fn new(mut heads: Vec<ChangeHash>) -> StateObject {
12713795×
        heads.sort();
12723795×
        heads.dedup();
12733795×
        StateObject { heads }
12743795×
    }
12753791×
    pub fn encode(&self) -> Vec<u8> {
12763791×
        debug_assert!(self.heads.windows(2).all(|w| w[0] < w[1]));
12773791×
        cbor::encode(&Value::map([
12783791×
            (0, Value::Uint(FORMAT_VERSION)),
1279
            (
1280
                1,
1281
                Value::Array(
12823791×
                    self.heads
12833791×
                        .iter()
12844574×
                        .map(|h| Value::Bytes(h.0.to_vec()))
12853791×
                        .collect(),
1286
                ),
1287
            ),
1288
        ]))
12893791×
    }
12902×
    pub fn hash(&self) -> ObjectRef {
12912×
        hash_object(ObjectType::State, &self.encode())
12922×
    }
12936404×
    pub fn decode(bytes: &[u8]) -> Result<StateObject, ObjectError> {
12946404×
        let v = cbor::decode(bytes)?;
12956404×
        let m = map(&v, "state")?;
12966404×
        check_version(m)?;
12976404×
        let heads = array(field(m, 1, "heads")?, "heads")?
12986404×
            .iter()
129910129×
            .map(|h| oref(h, "head"))
13006404×
            .collect::<Result<Vec<_>, _>>()?;
13016404×
        if !heads.windows(2).all(|w| w[0] < w[1]) {
13020×
            return schema("state heads must be sorted and unique");
13036404×
        }
13046404×
        Ok(StateObject { heads })
13056404×
    }
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
}