OXYGENHUB

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

1065 of 1128 lines run, 223 of 298 functions · run #368 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
601022686×
pub(crate) fn field<'a>(m: &'a Map, k: u64, what: &str) -> Result<&'a Value, ObjectError> {
611022686×
    m.get(&k)
621022686×
        .ok_or_else(|| ObjectError::Schema(format!("missing field {k} ({what})")))
631022686×
}
64413857×
pub(crate) fn uint(v: &Value, what: &str) -> Result<u64, ObjectError> {
65413857×
    v.as_uint()
66413857×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected unsigned integer")))
67413857×
}
6874102×
pub(crate) fn u32_(v: &Value, what: &str) -> Result<u32, ObjectError> {
6974102×
    u32::try_from(uint(v, what)?).map_err(|_| ObjectError::Schema(format!("{what}: exceeds u32")))
7074102×
}
71143382×
pub(crate) fn text<'a>(v: &'a Value, what: &str) -> Result<&'a str, ObjectError> {
72143382×
    v.as_text()
73143382×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected text")))
74143382×
}
75320241×
pub(crate) fn array<'a>(v: &'a Value, what: &str) -> Result<&'a [Value], ObjectError> {
76320241×
    v.as_array()
77320241×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected array")))
78320241×
}
79151194×
pub(crate) fn map<'a>(v: &'a Value, what: &str) -> Result<&'a Map, ObjectError> {
80151194×
    v.as_map()
81151194×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected map")))
82151194×
}
83454967×
pub(crate) fn bytes<'a>(v: &'a Value, what: &str) -> Result<&'a [u8], ObjectError> {
84454967×
    v.as_bytes()
85454967×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected bytes")))
86454967×
}
87155653×
pub(crate) fn oref(v: &Value, what: &str) -> Result<ObjectRef, ObjectError> {
88155653×
    ObjectRef::from_slice(bytes(v, what)?)
89155652×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected 32 bytes")))
90155653×
}
91154660×
pub(crate) fn node_id(v: &Value, what: &str) -> Result<NodeId, ObjectError> {
92154660×
    NodeId::from_slice(bytes(v, what)?)
93154660×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected 16 bytes")))
94154660×
}
9534329×
pub(crate) fn check_version(m: &Map) -> Result<(), ObjectError> {
9634329×
    let v = uint(field(m, 0, "version")?, "version")?;
9734329×
    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
        });
11134329×
    }
11234329×
    Ok(())
11334329×
}
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 {
1257128×
    pub fn now() -> Hlc {
1267128×
        let wall_ms = std::time::SystemTime::now()
1277128×
            .duration_since(std::time::UNIX_EPOCH)
1287128×
            .map(|d| d.as_millis() as u64)
1297128×
            .unwrap_or(0);
1307128×
        Hlc {
1317128×
            wall_ms,
1327128×
            logical: 0,
1337128×
        }
1347128×
    }
13513706×
    pub(crate) fn to_value(self) -> Value {
13613706×
        Value::map([
13713706×
            (0, Value::Uint(self.wall_ms)),
13813706×
            (1, Value::Uint(self.logical as u64)),
13913706×
        ])
14013706×
    }
14141039×
    pub(crate) fn from_value(v: &Value) -> Result<Hlc, ObjectError> {
14241039×
        let m = map(v, "hlc")?;
143
        Ok(Hlc {
14441039×
            wall_ms: uint(field(m, 0, "hlc.wall_ms")?, "hlc.wall_ms")?,
14541039×
            logical: u32_(field(m, 1, "hlc.logical")?, "hlc.logical")?,
146
        })
14741039×
    }
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 {
16273761×
    pub(crate) fn tag(self) -> u64 {
16373761×
        match self {
16472837×
            NodeKind::File => 0,
165897×
            NodeKind::Dir => 1,
1663×
            NodeKind::Symlink => 2,
16724×
            NodeKind::Subrepo => 3,
168
        }
16973761×
    }
17099076×
    pub(crate) fn from_tag(t: u64) -> Result<NodeKind, ObjectError> {
17199076×
        Ok(match t {
17296918×
            0 => NodeKind::File,
1732026×
            1 => NodeKind::Dir,
1749×
            2 => NodeKind::Symlink,
175123×
            3 => NodeKind::Subrepo,
1760×
            _ => return schema(format!("unknown node kind {t}")),
177
        })
17899076×
    }
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
    };
19773424×
    pub(crate) fn bits(self) -> u64 {
19873424×
        (self.exec as u64) | ((self.opaque as u64) << 1)
19973424×
    }
20099041×
    pub(crate) fn from_bits(b: u64) -> Result<Mode, ObjectError> {
20199041×
        if b > 3 {
2021×
            return schema(format!("unknown mode bits {b}"));
20399040×
        }
20499040×
        Ok(Mode {
20599040×
            exec: b & 1 != 0,
20699040×
            opaque: b & 2 != 0,
20799040×
        })
20899041×
    }
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 {
220525×
    fn to_value(self) -> Value {
221525×
        Value::Array(vec![
222525×
            Value::Bytes(self.change.0.to_vec()),
223525×
            Value::Uint(self.index as u64),
224525×
        ])
225525×
    }
226894×
    fn from_value(v: &Value, what: &str) -> Result<OpRef, ObjectError> {
227894×
        let a = array(v, what)?;
228894×
        if a.len() != 2 {
2290×
            return schema(format!("{what}: expected [hash, index]"));
230894×
        }
231
        Ok(OpRef {
232894×
            change: oref(&a[0], what)?,
233894×
            index: u32_(&a[1], what)?,
234
        })
235894×
    }
236
    /// Replace a self reference with the concrete change hash.
237868×
    pub fn resolve(self, me: ChangeHash) -> OpRef {
238868×
        if self.change.is_zero() {
2391×
            OpRef { change: me, ..self }
240
        } else {
241867×
            self
242
        }
243868×
    }
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).
27348973×
pub fn validate_name(name: &str) -> Result<(), ObjectError> {
27448973×
    if name.is_empty() || name == "." || name == ".." || name.contains('/') || name.contains('\0') {
2756×
        return schema(format!("invalid placement name {name:?}"));
27648967×
    }
27748967×
    Ok(())
27848973×
}
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
2906495×
    fn to_value(&self) -> Value {
29112499×
        let nid = |n: &NodeId| Value::Bytes(n.0.to_vec());
2926495×
        match self {
293
            TreeOp::AddNode {
2945970×
                node,
2955970×
                kind,
2965970×
                mode,
2975970×
                parent,
2985970×
                name,
2995970×
            } => Value::map([
3005970×
                (0, Value::Uint(0)),
3015970×
                (1, nid(node)),
3025970×
                (2, Value::Uint(kind.tag())),
3035970×
                (3, Value::Uint(mode.bits())),
3045970×
                (4, nid(parent)),
3055970×
                (5, Value::Text(name.clone())),
3065970×
            ]),
307424×
            TreeOp::RemoveNode { node, placement } => Value::map([
308424×
                (0, Value::Uint(1)),
309424×
                (1, nid(node)),
310424×
                (2, placement.to_value()),
311424×
            ]),
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
        }
3316495×
    }
332
33349670×
    fn from_value(v: &Value) -> Result<TreeOp, ObjectError> {
33449670×
        let m = map(v, "tree_op")?;
33549670×
        let tag = uint(field(m, 0, "tree_op tag")?, "tree_op tag")?;
33649670×
        let node = node_id(field(m, 1, "tree_op.node")?, "tree_op.node")?;
33749670×
        let op = match tag {
338
            0 => {
33948776×
                let name = text(field(m, 5, "name")?, "name")?.to_owned();
34048776×
                validate_name(&name)?;
341
                TreeOp::AddNode {
34248776×
                    node,
34348776×
                    kind: NodeKind::from_tag(uint(field(m, 2, "kind")?, "kind")?)?,
34448776×
                    mode: Mode::from_bits(uint(field(m, 3, "mode")?, "mode")?)?,
34548776×
                    parent: node_id(field(m, 4, "parent")?, "parent")?,
34648776×
                    name,
347
                }
348
            }
349
            1 => TreeOp::RemoveNode {
350685×
                node,
351685×
                placement: OpRef::from_value(field(m, 2, "placement")?, "placement")?,
352
            },
353
            2 => {
354170×
                let name = text(field(m, 5, "name")?, "name")?.to_owned();
355170×
                validate_name(&name)?;
356
                TreeOp::Move {
357170×
                    node,
358170×
                    old: OpRef::from_value(field(m, 2, "old")?, "old")?,
359170×
                    parent: node_id(field(m, 4, "parent")?, "parent")?,
360170×
                    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
        };
37049670×
        if node.is_root() {
3710×
            return schema("tree op on the root node");
37249670×
        }
37349670×
        Ok(op)
37449670×
    }
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 {
38715702×
    fn to_value(self) -> Value {
38815702×
        match self {
3895589×
            AtomRef::Start => Value::Uint(0),
3905832×
            AtomRef::End => Value::Uint(1),
3914281×
            AtomRef::Atom { change, index } => Value::Array(vec![
3924281×
                Value::Bytes(change.0.to_vec()),
3934281×
                Value::Uint(index as u64),
3944281×
            ]),
395
        }
39615702×
    }
397103670×
    fn from_value(v: &Value, what: &str) -> Result<AtomRef, ObjectError> {
3989054×
        match v {
39946534×
            Value::Uint(0) => Ok(AtomRef::Start),
40048082×
            Value::Uint(1) => Ok(AtomRef::End),
4019054×
            Value::Array(a) if a.len() == 2 => Ok(AtomRef::Atom {
4029054×
                change: oref(&a[0], what)?,
4039054×
                index: u32_(&a[1], what)?,
404
            }),
4050×
            _ => schema(format!("{what}: expected atom reference")),
406
        }
407103670×
    }
40864824×
    pub fn resolve(self, me: ChangeHash) -> AtomRef {
4099441×
        match self {
4109441×
            AtomRef::Atom { change, index } if change.is_zero() => {
41138×
                AtomRef::Atom { change: me, index }
412
            }
41364786×
            other => other,
414
        }
41564824×
    }
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 {
4272475×
    fn to_value(self) -> Value {
4282475×
        Value::Array(vec![
4292475×
            Value::Bytes(self.change.0.to_vec()),
4302475×
            Value::Uint(self.from as u64),
4312475×
            Value::Uint(self.to as u64),
4322475×
        ])
4332475×
    }
4344324×
    fn from_value(v: &Value) -> Result<AtomRange, ObjectError> {
4354324×
        let a = array(v, "atom range")?;
4364324×
        if a.len() != 3 {
4370×
            return schema("atom range: expected [hash, from, to]");
4384324×
        }
4394324×
        let r = AtomRange {
4404324×
            change: oref(&a[0], "range.change")?,
4414324×
            from: u32_(&a[1], "range.from")?,
4424324×
            to: u32_(&a[2], "range.to")?,
443
        };
4444324×
        if r.from >= r.to {
4450×
            return schema("atom range: empty or inverted");
4464324×
        }
4474324×
        Ok(r)
4484324×
    }
4494566×
    pub fn resolve(self, me: ChangeHash) -> AtomRange {
4504566×
        if self.change.is_zero() {
45118×
            AtomRange { change: me, ..self }
452
        } else {
4534548×
            self
454
        }
4554566×
    }
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 {
47849042×
    pub fn node(&self) -> NodeId {
47949042×
        match self {
48045443×
            Edit::Insert { node, .. } | Edit::Delete { node, .. } | Edit::Replace { node, .. } => {
48149042×
                *node
482
            }
483
        }
48449042×
    }
485
486
    /// Whether this insert is stored as a text blob in a change of `version`.
48710126×
    fn stored_text(&self, version: u64) -> bool {
4887854×
        matches!(self, Edit::Insert { lines, .. }
4897854×
            if version >= 2 && cbor::byte_strings_len(lines) >= TEXT_BLOB_MIN)
49010126×
    }
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).
49610119×
    fn to_value(&self, stored: Option<(ObjectRef, TextForm)>, compact: bool) -> Value {
49710119×
        let nid = |n: &NodeId| Value::Bytes(n.0.to_vec());
49810119×
        let opt = |o: &Option<ObjectRef>| match o {
499188×
            Some(r) => Value::Bytes(r.0.to_vec()),
500126×
            None => Value::Null,
501314×
        };
50210119×
        match (self, stored) {
503
            (
504
                Edit::Insert {
50573×
                    node,
50673×
                    after,
50773×
                    before,
50873×
                    lines,
509
                },
51073×
                Some((r, form)),
511
            ) => {
51273×
                let mut fields = vec![
51373×
                    (0, Value::Uint(0)),
51473×
                    (1, nid(node)),
51573×
                    (2, after.to_value()),
51673×
                    (3, before.to_value()),
51773×
                    (5, Value::Bytes(r.0.to_vec())),
51873×
                    (6, Value::Uint(lines.len() as u64)),
519
                ];
52073×
                if form == TextForm::CborFallback {
5211×
                    fields.push((7, Value::Uint(1)));
52272×
                }
52373×
                Value::map(fields)
524
            }
525
            (
526
                Edit::Insert {
5277778×
                    node,
5287778×
                    after,
5297778×
                    before,
5307778×
                    lines,
531
                },
532
                None,
5337778×
            ) => Value::map([
5347778×
                (0, Value::Uint(0)),
5357778×
                (1, nid(node)),
5367778×
                (2, after.to_value()),
5377778×
                (3, before.to_value()),
538
                (
539
                    4,
5407778×
                    if compact {
5417772×
                        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
            ]),
5472111×
            (Edit::Delete { node, atoms }, _) => Value::map([
5482111×
                (0, Value::Uint(1)),
5492111×
                (1, nid(node)),
550
                (
551
                    2,
5522475×
                    Value::Array(atoms.iter().map(|r| r.to_value()).collect()),
553
                ),
554
            ]),
555157×
            (Edit::Replace { node, old, new }, _) => Value::map([
556157×
                (0, Value::Uint(2)),
557157×
                (1, nid(node)),
558157×
                (2, opt(old)),
559157×
                (3, opt(new)),
560157×
            ]),
561
        }
56210119×
    }
563
5648668×
    fn from_value(v: &Value, version: u64, resolve: &mut Resolver) -> Result<Edit, ObjectError> {
5658668×
        let m = map(v, "edit")?;
5668668×
        let tag = uint(field(m, 0, "edit tag")?, "edit tag")?;
5678668×
        let node = node_id(field(m, 1, "edit.node")?, "edit.node")?;
5688668×
        let opt = |v: &Value, what: &str| -> Result<Option<ObjectRef>, ObjectError> {
5691660×
            if v.is_null() {
570731×
                Ok(None)
571
            } else {
572929×
                Ok(Some(oref(v, what)?))
573
            }
5741660×
        };
5758668×
        Ok(match tag {
576
            0 => {
5774462×
                let lines = match (m.get(&4), m.get(&5)) {
5784196×
                    (Some(inline), None) => {
5794196×
                        let lines = array_lines(inline)?;
5804196×
                        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");
5824195×
                        }
5834195×
                        if lines.is_empty() {
5840×
                            return schema("insert with no lines");
5854195×
                        }
5864195×
                        lines
587
                    }
588266×
                    (None, Some(text)) if version >= 2 => {
589266×
                        let text = oref(text, "insert text")?;
590266×
                        let count = u32_(field(m, 6, "insert line count")?, "insert line count")?;
591266×
                        if count == 0 {
5920×
                            return schema("insert with no lines");
593266×
                        }
594266×
                        let form = match (version, m.get(&7)) {
5951×
                            (2, None) => TextForm::Cbor,
596264×
                            (_, None) => TextForm::Raw,
5971×
                            (3.., Some(Value::Uint(1))) => TextForm::CborFallback,
5980×
                            _ => return schema("unknown text blob form"),
599
                        };
600
                        // The resolver checks the count (`text_lines`).
601266×
                        resolve(&text, count, form)?
602
                    }
603
                    _ => {
6040×
                        return schema(
605
                            "an insert has either its lines or, in a version 2 change, a text blob",
606
                        )
607
                    }
608
                };
609
                Edit::Insert {
6104459×
                    node,
6114459×
                    after: AtomRef::from_value(field(m, 2, "after")?, "after")?,
6124459×
                    before: AtomRef::from_value(field(m, 3, "before")?, "before")?,
6134459×
                    lines,
614
                }
615
            }
616
            1 => {
6173376×
                let atoms = array(field(m, 2, "atoms")?, "atoms")?
6183376×
                    .iter()
6193376×
                    .map(AtomRange::from_value)
6203376×
                    .collect::<Result<Vec<_>, _>>()?;
6213376×
                if atoms.is_empty() {
6220×
                    return schema("delete with no atoms");
6233376×
                }
6243376×
                Edit::Delete { node, atoms }
625
            }
626
            2 => Edit::Replace {
627830×
                node,
628830×
                old: opt(field(m, 2, "old")?, "old")?,
629830×
                new: opt(field(m, 3, "new")?, "new")?,
630
            },
6310×
            _ => return schema(format!("unknown edit tag {tag}")),
632
        })
6338668×
    }
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 {
64617382×
    pub(crate) fn tag(self) -> u64 {
64717382×
        match self {
64814498×
            ChangeKind::Normal => 0,
64943×
            ChangeKind::Resolution => 1,
6502841×
            ChangeKind::WorkingCopy => 2,
651
        }
65217382×
    }
65330905×
    pub(crate) fn from_tag(t: u64) -> Result<ChangeKind, ObjectError> {
65430905×
        Ok(match t {
65527592×
            0 => ChangeKind::Normal,
656148×
            1 => ChangeKind::Resolution,
6573165×
            2 => ChangeKind::WorkingCopy,
6580×
            _ => return schema(format!("unknown change kind {t}")),
659
        })
66030905×
    }
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 {
6806241×
    pub fn normalize(&mut self) {
6816241×
        self.deps.sort();
6826241×
        self.deps.dedup();
6836241×
    }
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.
6938381×
    fn stored_texts(&self, sink: &mut TextSink) -> Vec<Option<(ObjectRef, TextForm)>> {
694
        use rayon::prelude::*;
6958381×
        let mut refs: Vec<Option<(ObjectRef, TextForm)>> = vec![None; self.edits.len()];
6968381×
        let stored: Vec<usize> = (0..self.edits.len())
69710119×
            .filter(|i| self.edits[*i].stored_text(self.version))
6988381×
            .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.
7028381×
        let mut batches: Vec<&[usize]> = Vec::new();
7038381×
        let (mut start, mut bytes) = (0, 0usize);
7048381×
        for (k, i) in stored.iter().enumerate() {
70573×
            if let Edit::Insert { lines, .. } = &self.edits[*i] {
70673×
                bytes += lines.bytes().len();
70773×
            }
70873×
            if k + 1 - start == 256 || bytes >= 32 << 20 {
7090×
                batches.push(&stored[start..=k]);
7100×
                (start, bytes) = (k + 1, 0);
71173×
            }
712
        }
7138381×
        if start < stored.len() {
71472×
            batches.push(&stored[start..]);
7158309×
        }
7168381×
        for batch in batches {
71772×
            let made: Vec<StoredText> = batch
71872×
                .par_iter()
71973×
                .map(|i| {
72073×
                    let Edit::Insert { lines, .. } = &self.edits[*i] else {
7210×
                        unreachable!("only inserts are stored as text");
722
                    };
72373×
                    let form = text_form(self.version, lines);
72473×
                    let content = match form {
72571×
                        TextForm::Raw => lines.bytes().to_vec(),
7262×
                        TextForm::Cbor | TextForm::CborFallback => cbor::encode_byte_strings(lines),
727
                    };
72873×
                    StoredText {
72973×
                        blob: Blob::of(&content),
73073×
                        content,
73173×
                        form,
73273×
                    }
73373×
                })
73472×
                .collect();
73573×
            for (i, t) in batch.iter().zip(&made) {
73673×
                refs[*i] = Some((t.blob.hash(), t.form));
73773×
            }
73872×
            if !sink(made) {
7390×
                break;
74072×
            }
741
        }
7428381×
        refs
7438381×
    }
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.
7478381×
    fn value_with(&self, sink: &mut TextSink, compact: bool) -> Value {
7488381×
        Value::map([
7498381×
            (0, Value::Uint(self.version)),
7508381×
            (1, Value::Bytes(self.change_id.0.to_vec())),
751
            (
752
                2,
753
                Value::Array(
7548381×
                    self.deps
7558381×
                        .iter()
7569837×
                        .map(|d| Value::Bytes(d.0.to_vec()))
7578381×
                        .collect(),
758
                ),
759
            ),
7608381×
            (3, Value::Bytes(self.author.0.to_vec())),
7618381×
            (4, self.hlc.to_value()),
7628381×
            (5, Value::Text(self.message.clone())),
763
            (
764
                6,
7658381×
                Value::Array(self.tree_ops.iter().map(|t| t.to_value()).collect()),
766
            ),
767
            (
768
                7,
769
                Value::Array(
7708381×
                    self.edits
7718381×
                        .iter()
7728381×
                        .zip(self.stored_texts(sink))
77310119×
                        .map(|(e, stored)| e.to_value(stored, compact))
7748381×
                        .collect(),
775
                ),
776
            ),
7778381×
            (8, Value::Uint(self.kind.tag())),
7788381×
            (9, Value::Map(BTreeMap::new())),
779
        ])
7808381×
    }
781
7824056×
    pub fn encode(&self) -> Vec<u8> {
7834056×
        debug_assert!(
7844056×
            self.deps.windows(2).all(|w| w[0] < w[1]),
785
            "deps must be normalized"
786
        );
7874056×
        cbor::encode(&self.value_with(&mut |_| true, true))
7884056×
    }
789
790
    /// The encoding and the text blobs its large inserts are stored as,
791
    /// which must be stored with it.
792131×
    pub fn encode_parts(&self) -> (Vec<u8>, Vec<StoredText>) {
793131×
        debug_assert!(
794131×
            self.deps.windows(2).all(|w| w[0] < w[1]),
795
            "deps must be normalized"
796
        );
797131×
        let mut texts = Vec::new();
798131×
        let bytes = cbor::encode(&self.value_with(
7995×
            &mut |batch| {
8005×
                texts.extend(batch);
8015×
                true
8025×
            },
803
            true,
804
        ));
805131×
        (bytes, texts)
806131×
    }
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.
8114188×
    pub fn encode_streaming<E>(
8124188×
        &self,
8134188×
        mut store: impl FnMut(Vec<StoredText>) -> Result<(), E>,
8144188×
    ) -> Result<Vec<u8>, E> {
8154188×
        debug_assert!(
8164188×
            self.deps.windows(2).all(|w| w[0] < w[1]),
817
            "deps must be normalized"
818
        );
8194188×
        let mut failed = None;
8204188×
        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
        );
8304188×
        match failed {
8310×
            Some(e) => Err(e),
8324188×
            None => Ok(cbor::encode(&value)),
833
        }
8344188×
    }
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
8414049×
    pub fn hash(&self) -> ChangeHash {
8424049×
        hash_object(ObjectType::Change, &self.encode())
8434049×
    }
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).
8585942×
    pub fn decode_with(bytes: &[u8], resolve: &mut Resolver) -> Result<Change, ObjectError> {
8595942×
        let v = cbor::decode(bytes)?;
8605942×
        Self::from_value_with(&v, resolve)
8615942×
    }
862
86312654×
    pub fn from_value(v: &Value) -> Result<Change, ObjectError> {
86412654×
        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×
        })
87012654×
    }
871
87218596×
    pub(crate) fn from_value_with(
87318596×
        v: &Value,
87418596×
        resolve: &mut Resolver,
87518596×
    ) -> Result<Change, ObjectError> {
87618596×
        let m = map(v, "change")?;
87718596×
        let version = uint(field(m, 0, "version")?, "version")?;
87818596×
        if !(1..=CHANGE_VERSION).contains(&version) {
8791×
            return schema(format!("unsupported change format version {version}"));
88018595×
        }
88118595×
        let change_id = ChangeId::from_slice(bytes(field(m, 1, "change_id")?, "change_id")?)
88218595×
            .ok_or_else(|| ObjectError::Schema("change_id: expected 16 bytes".into()))?;
88318595×
        let deps = array(field(m, 2, "deps")?, "deps")?
88418595×
            .iter()
88518595×
            .map(|d| oref(d, "dep"))
88618595×
            .collect::<Result<Vec<_>, _>>()?;
88718595×
        if !deps.windows(2).all(|w| w[0] < w[1]) {
8881×
            return schema("deps must be sorted and unique");
88918594×
        }
89018594×
        if deps.iter().any(|d| d.is_zero()) {
8910×
            return schema("deps may not contain the self reference");
89218594×
        }
89318594×
        let extra = map(field(m, 9, "extra")?, "extra")?;
89418594×
        if !extra.is_empty() {
8951×
            return schema("extra must be empty in format version 1");
89618593×
        }
897
        Ok(Change {
89818593×
            version,
89918593×
            change_id,
90018593×
            deps,
90118593×
            author: oref(field(m, 3, "author")?, "author")?,
90218593×
            hlc: Hlc::from_value(field(m, 4, "hlc")?)?,
90318593×
            message: text(field(m, 5, "message")?, "message")?.to_owned(),
90418593×
            tree_ops: array(field(m, 6, "tree_ops")?, "tree_ops")?
90518593×
                .iter()
90618593×
                .map(TreeOp::from_value)
90718593×
                .collect::<Result<Vec<_>, _>>()?,
90818593×
            edits: array(field(m, 7, "edits")?, "edits")?
90918593×
                .iter()
91018593×
                .map(|e| Edit::from_value(e, version, resolve))
91118593×
                .collect::<Result<Vec<_>, _>>()?,
91218590×
            kind: ChangeKind::from_tag(uint(field(m, 8, "kind")?, "kind")?)?,
913
        })
91418596×
    }
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`]).
94432418×
pub fn inline_lines(array: &[u8]) -> Result<Lines, ObjectError> {
94532418×
    let v = cbor::decode(array)?;
94632418×
    let lines = array_lines(&v)?;
94732418×
    if lines.is_empty() {
9480×
        return schema("insert with no lines");
94932418×
    }
95032418×
    Ok(lines)
95132418×
}
952
953
/// The lines of a CBOR array of byte strings, copied once into one buffer.
95436620×
fn array_lines(v: &Value) -> Result<Lines, ObjectError> {
95536620×
    Ok(array(v, "lines")?
95636620×
        .iter()
95759498×
        .map(|l| bytes(l, "line"))
95836620×
        .collect::<Result<Vec<&[u8]>, _>>()?
95936620×
        .into_iter()
96036620×
        .collect())
96136620×
}
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.
9699380×
    pub fn decode_skeleton(
9709380×
        bytes: &[u8],
9719380×
        me: ChangeHash,
9729380×
    ) -> Result<(Change, Vec<TextRef>), ObjectError> {
9739380×
        let mut c = cbor::Cursor::new(bytes);
9749380×
        let (major, n) = c.head()?;
9759380×
        if major != 5 {
9760×
            return schema("change: expected map");
9779380×
        }
9789380×
        let mut fields = Map::new();
9799380×
        let mut edits = Vec::new();
9809380×
        let mut texts = Vec::new();
9819380×
        let mut version = None;
9829380×
        let mut last: Option<u64> = None;
9839380×
        for _ in 0..n {
98493798×
            let k = map_key(&mut c, &mut last)?;
98593798×
            if k == 7 {
9869380×
                let Some(v) = version else {
9870×
                    return schema("change: version must come first");
988
                };
9899380×
                let (am, an) = c.head()?;
9909380×
                if am != 4 {
9910×
                    return schema("edits: expected array");
9929380×
                }
9939380×
                for _ in 0..an {
99450635×
                    edits.push(edit_skeleton(&mut c, v, me, &mut texts)?);
995
                }
9969379×
                fields.insert(7, Value::Array(Vec::new()));
997
            } else {
99884418×
                let val = c.value()?;
99984418×
                if k == 0 {
10009380×
                    version = Some(uint(&val, "version")?);
100175038×
                }
100284418×
                fields.insert(k, val);
1003
            }
1004
        }
10059379×
        if !c.at_end() {
10060×
            return Err(ObjectError::Cbor(cbor::CborError::TrailingBytes));
10079379×
        }
10089379×
        let mut change = Change::from_value(&Value::Map(fields))?;
10099379×
        change.edits = edits;
10109379×
        Ok((change, texts))
10119380×
    }
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.
10183271×
    pub fn decode_meta(bytes: &[u8]) -> Result<crate::state::ChangeMeta, ObjectError> {
10193271×
        let mut c = cbor::Cursor::new(bytes);
10203271×
        let (major, n) = c.head()?;
10213271×
        if major != 5 {
10220×
            return schema("change: expected map");
10233271×
        }
10243271×
        let mut fields = Map::new();
10253271×
        let mut last: Option<u64> = None;
10263271×
        for _ in 0..n {
102732710×
            let k = map_key(&mut c, &mut last)?;
102832710×
            if k == 6 || k == 7 {
10296542×
                c.skip()?;
10306542×
                fields.insert(k, Value::Array(Vec::new()));
1031
            } else {
103226168×
                fields.insert(k, c.value()?);
1033
            }
1034
        }
10353271×
        if !c.at_end() {
10360×
            return Err(ObjectError::Cbor(cbor::CborError::TrailingBytes));
10373271×
        }
10383271×
        Ok(crate::state::ChangeMeta::of(&Change::from_value(
10393271×
            &Value::Map(fields),
10400×
        )?))
10413271×
    }
1042
}
1043
1044
/// A canonical map key: an unsigned integer above the previous one.
1045374235×
fn map_key(c: &mut cbor::Cursor, last: &mut Option<u64>) -> Result<u64, ObjectError> {
1046374235×
    let (km, k) = c.head()?;
1047374235×
    if km != 0 || last.is_some_and(|l| k <= l) {
10480×
        return Err(ObjectError::Cbor(cbor::CborError::BadMapKey));
1049374235×
    }
1050374235×
    *last = Some(k);
1051374235×
    Ok(k)
1052374235×
}
1053
1054
/// One edit of [`Change::decode_skeleton`]: an insert's lines are left out.
105550635×
fn edit_skeleton(
105650635×
    c: &mut cbor::Cursor,
105750635×
    version: u64,
105850635×
    me: ChangeHash,
105950635×
    texts: &mut Vec<TextRef>,
106050635×
) -> Result<Edit, ObjectError> {
106150635×
    let (major, n) = c.head()?;
106250635×
    if major != 5 {
10630×
        return schema("edit: expected map");
106450635×
    }
106550635×
    let mut fields = Map::new();
106650635×
    let mut inline: Option<(usize, usize, u64)> = None;
106750635×
    let mut last: Option<u64> = None;
106850635×
    for _ in 0..n {
1069247727×
        let k = map_key(c, &mut last)?;
1070247727×
        if k == 4 {
107147377×
            let start = c.pos();
107247377×
            let (am, count) = c.head()?;
107347377×
            if am != 4 {
10740×
                return schema("lines: expected array");
107547377×
            }
107647377×
            for _ in 0..count {
107763744×
                c.skip()?;
1078
            }
107947377×
            inline = Some((start, c.pos(), count));
108047377×
            continue;
1081200350×
        }
1082200350×
        fields.insert(k, c.value()?);
1083
    }
108450635×
    let Some((start, end, count)) = inline else {
10853258×
        return Edit::from_value(&Value::Map(fields), version, &mut |text, count, form| {
1086147×
            texts.push(TextRef::Blob(*text, count, form));
1087147×
            Ok(Lines::default())
1088147×
        });
1089
    };
109047377×
    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");
109247377×
    }
109347377×
    if count == 0 {
10940×
        return schema("insert with no lines");
109547377×
    }
109647377×
    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");
109847376×
    }
109947376×
    let (Ok(start), Ok(end)) = (u32::try_from(start), u32::try_from(end)) else {
11000×
        return schema("change too large");
1101
    };
110247376×
    texts.push(TextRef::Inline {
110347376×
        change: me,
110447376×
        start,
110547376×
        end,
110647376×
    });
1107
    Ok(Edit::Insert {
110847376×
        node: node_id(field(&fields, 1, "edit.node")?, "edit.node")?,
110947376×
        after: AtomRef::from_value(field(&fields, 2, "after")?, "after")?,
111047376×
        before: AtomRef::from_value(field(&fields, 3, "before")?, "before")?,
111147376×
        lines: Lines::default(),
1112
    })
111350635×
}
1114
1115
/// A large insert's lines as stored (spec §6.1): the blob and its content,
1116
/// the canonical CBOR array of the lines' byte strings.
1117
#[derive(Debug, Clone, PartialEq, Eq)]
1118
pub struct StoredText {
1119
    pub blob: Blob,
1120
    pub content: Vec<u8>,
1121
    pub form: TextForm,
1122
}
1123
1124
/// The form a change of `version` stores these lines in.
112573×
fn text_form(version: u64, lines: &Lines) -> TextForm {
112672×
    match version {
112773×
        ..=2 => TextForm::Cbor,
112872×
        _ if lines.is_split_form() => TextForm::Raw,
11291×
        _ => TextForm::CborFallback,
1130
    }
113173×
}
1132
1133
/// The lines a text blob's `content` holds, checked against the rules for
1134
/// one: canonical, as many as the insert claims, and not short enough to
1135
/// have been inline.
1136138×
pub fn text_lines(content: &[u8], count: u32, form: TextForm) -> Result<Lines, ObjectError> {
1137138×
    let lines = match form {
1138132×
        TextForm::Raw => Lines::split(content),
11396×
        TextForm::Cbor | TextForm::CborFallback => array_lines(&cbor::decode(content)?)?,
1140
    };
1141
    // One encoding per change: the size rule and the form are both fixed
1142
    // by the lines.
1143138×
    if cbor::byte_strings_len(&lines) < TEXT_BLOB_MIN {
11442×
        return schema(format!(
1145
            "a text blob of {} bytes is short enough to be inline",
11462×
            content.len()
1147
        ));
1148136×
    }
1149136×
    if form == TextForm::CborFallback && lines.is_split_form() {
11501×
        return schema("these lines are stored as their bytes in a version 3 change");
1151135×
    }
1152135×
    if lines.len() != count as usize {
11532×
        return schema(format!(
1154
            "a text blob holds {} lines, the insert says {count}",
11552×
            lines.len()
1156
        ));
1157133×
    }
1158133×
    Ok(lines)
1159138×
}
1160
1161
// ---------------------------------------------------------------- blob
1162
1163
/// File content as an ordered list of chunks (spec §13.2).
1164
#[derive(Debug, Clone, PartialEq, Eq)]
1165
pub struct Blob {
1166
    pub length: u64,
1167
    pub chunks: Vec<ObjectRef>,
1168
}
1169
1170
impl Blob {
1171
    /// The blob for `content`: its chunks as content-defined chunking cuts
1172
    /// them (spec §13.2).
1173486×
    pub fn of(content: &[u8]) -> Blob {
1174
        Blob {
1175486×
            length: content.len() as u64,
1176486×
            chunks: crate::chunk::chunks(content)
1177486×
                .into_iter()
1178609×
                .map(|c| hash_object(ObjectType::Chunk, c))
1179486×
                .collect(),
1180
        }
1181486×
    }
1182
1183614×
    pub fn encode(&self) -> Vec<u8> {
1184614×
        cbor::encode(&Value::map([
1185614×
            (0, Value::Uint(FORMAT_VERSION)),
1186614×
            (1, Value::Uint(self.length)),
1187
            (
1188
                2,
1189
                Value::Array(
1190614×
                    self.chunks
1191614×
                        .iter()
1192836×
                        .map(|c| Value::Bytes(c.0.to_vec()))
1193614×
                        .collect(),
1194
                ),
1195
            ),
1196
        ]))
1197614×
    }
1198392×
    pub fn hash(&self) -> ObjectRef {
1199392×
        hash_object(ObjectType::Blob, &self.encode())
1200392×
    }
1201449×
    pub fn decode(bytes: &[u8]) -> Result<Blob, ObjectError> {
1202449×
        let v = cbor::decode(bytes)?;
1203449×
        let m = map(&v, "blob")?;
1204449×
        check_version(m)?;
1205
        Ok(Blob {
1206449×
            length: uint(field(m, 1, "length")?, "length")?,
1207449×
            chunks: array(field(m, 2, "chunks")?, "chunks")?
1208449×
                .iter()
1209691×
                .map(|c| oref(c, "chunk"))
1210449×
                .collect::<Result<Vec<_>, _>>()?,
1211
        })
1212449×
    }
1213
}
1214
1215
// ---------------------------------------------------------------- checkpoint
1216
1217
/// A materialized state (spec §11): the heads it stands for, how many changes
1218
/// it holds, and a blob with the serialized graphs (`State::checkpoint_payload`).
1219
#[derive(Debug, Clone, PartialEq, Eq)]
1220
pub struct Checkpoint {
1221
    pub heads: Vec<ChangeHash>,
1222
    pub count: u64,
1223
    pub payload: ObjectRef,
1224
}
1225
1226
impl Checkpoint {
122712×
    pub fn encode(&self) -> Vec<u8> {
122812×
        cbor::encode(&Value::map([
122912×
            (0, Value::Uint(FORMAT_VERSION)),
1230
            (
1231
                1,
1232
                Value::Array(
123312×
                    self.heads
123412×
                        .iter()
123513×
                        .map(|h| Value::Bytes(h.0.to_vec()))
123612×
                        .collect(),
1237
                ),
1238
            ),
123912×
            (2, Value::Uint(self.count)),
124012×
            (3, Value::Bytes(self.payload.0.to_vec())),
1241
        ]))
124212×
    }
12430×
    pub fn hash(&self) -> ObjectRef {
12440×
        hash_object(ObjectType::Checkpoint, &self.encode())
12450×
    }
124689×
    pub fn decode(bytes: &[u8]) -> Result<Checkpoint, ObjectError> {
124789×
        let v = cbor::decode(bytes)?;
124889×
        let m = map(&v, "checkpoint")?;
124989×
        check_version(m)?;
1250
        Ok(Checkpoint {
125189×
            heads: array(field(m, 1, "heads")?, "heads")?
125289×
                .iter()
125391×
                .map(|h| oref(h, "head"))
125489×
                .collect::<Result<Vec<_>, _>>()?,
125589×
            count: uint(field(m, 2, "count")?, "count")?,
125689×
            payload: oref(field(m, 3, "payload")?, "payload")?,
1257
        })
125889×
    }
1259
}
1260
1261
// ---------------------------------------------------------------- state
1262
1263
/// A state named by its heads (spec §10.1): what a bookmark or tag points at.
1264
#[derive(Debug, Clone, PartialEq, Eq, Default)]
1265
pub struct StateObject {
1266
    pub heads: Vec<ChangeHash>,
1267
}
1268
1269
impl StateObject {
12703718×
    pub fn new(mut heads: Vec<ChangeHash>) -> StateObject {
12713718×
        heads.sort();
12723718×
        heads.dedup();
12733718×
        StateObject { heads }
12743718×
    }
12753717×
    pub fn encode(&self) -> Vec<u8> {
12763717×
        debug_assert!(self.heads.windows(2).all(|w| w[0] < w[1]));
12773717×
        cbor::encode(&Value::map([
12783717×
            (0, Value::Uint(FORMAT_VERSION)),
1279
            (
1280
                1,
1281
                Value::Array(
12823717×
                    self.heads
12833717×
                        .iter()
12844563×
                        .map(|h| Value::Bytes(h.0.to_vec()))
12853717×
                        .collect(),
1286
                ),
1287
            ),
1288
        ]))
12893717×
    }
12902×
    pub fn hash(&self) -> ObjectRef {
12912×
        hash_object(ObjectType::State, &self.encode())
12922×
    }
12936315×
    pub fn decode(bytes: &[u8]) -> Result<StateObject, ObjectError> {
12946315×
        let v = cbor::decode(bytes)?;
12956315×
        let m = map(&v, "state")?;
12966315×
        check_version(m)?;
12976315×
        let heads = array(field(m, 1, "heads")?, "heads")?
12986315×
            .iter()
129910171×
            .map(|h| oref(h, "head"))
13006315×
            .collect::<Result<Vec<_>, _>>()?;
13016315×
        if !heads.windows(2).all(|w| w[0] < w[1]) {
13020×
            return schema("state heads must be sorted and unique");
13036315×
        }
13046315×
        Ok(StateObject { heads })
13056315×
    }
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
}