OXYGENHUB

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

1065 of 1128 lines run, 223 of 298 functions · run #369 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
601019141×
pub(crate) fn field<'a>(m: &'a Map, k: u64, what: &str) -> Result<&'a Value, ObjectError> {
611019141×
    m.get(&k)
621019141×
        .ok_or_else(|| ObjectError::Schema(format!("missing field {k} ({what})")))
631019141×
}
64412156×
pub(crate) fn uint(v: &Value, what: &str) -> Result<u64, ObjectError> {
65412156×
    v.as_uint()
66412156×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected unsigned integer")))
67412156×
}
6873386×
pub(crate) fn u32_(v: &Value, what: &str) -> Result<u32, ObjectError> {
6973386×
    u32::try_from(uint(v, what)?).map_err(|_| ObjectError::Schema(format!("{what}: exceeds u32")))
7073386×
}
71142827×
pub(crate) fn text<'a>(v: &'a Value, what: &str) -> Result<&'a str, ObjectError> {
72142827×
    v.as_text()
73142827×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected text")))
74142827×
}
75318373×
pub(crate) fn array<'a>(v: &'a Value, what: &str) -> Result<&'a [Value], ObjectError> {
76318373×
    v.as_array()
77318373×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected array")))
78318373×
}
79150762×
pub(crate) fn map<'a>(v: &'a Value, what: &str) -> Result<&'a Map, ObjectError> {
80150762×
    v.as_map()
81150762×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected map")))
82150762×
}
83452864×
pub(crate) fn bytes<'a>(v: &'a Value, what: &str) -> Result<&'a [u8], ObjectError> {
84452864×
    v.as_bytes()
85452864×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected bytes")))
86452864×
}
87154626×
pub(crate) fn oref(v: &Value, what: &str) -> Result<ObjectRef, ObjectError> {
88154626×
    ObjectRef::from_slice(bytes(v, what)?)
89154625×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected 32 bytes")))
90154626×
}
91154261×
pub(crate) fn node_id(v: &Value, what: &str) -> Result<NodeId, ObjectError> {
92154261×
    NodeId::from_slice(bytes(v, what)?)
93154261×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected 16 bytes")))
94154261×
}
9534086×
pub(crate) fn check_version(m: &Map) -> Result<(), ObjectError> {
9634086×
    let v = uint(field(m, 0, "version")?, "version")?;
9734086×
    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
        });
11134086×
    }
11234086×
    Ok(())
11334086×
}
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 {
1257100×
    pub fn now() -> Hlc {
1267100×
        let wall_ms = std::time::SystemTime::now()
1277100×
            .duration_since(std::time::UNIX_EPOCH)
1287100×
            .map(|d| d.as_millis() as u64)
1297100×
            .unwrap_or(0);
1307100×
        Hlc {
1317100×
            wall_ms,
1327100×
            logical: 0,
1337100×
        }
1347100×
    }
13514143×
    pub(crate) fn to_value(self) -> Value {
13614143×
        Value::map([
13714143×
            (0, Value::Uint(self.wall_ms)),
13814143×
            (1, Value::Uint(self.logical as u64)),
13914143×
        ])
14014143×
    }
14140837×
    pub(crate) fn from_value(v: &Value) -> Result<Hlc, ObjectError> {
14240837×
        let m = map(v, "hlc")?;
143
        Ok(Hlc {
14440837×
            wall_ms: uint(field(m, 0, "hlc.wall_ms")?, "hlc.wall_ms")?,
14540837×
            logical: u32_(field(m, 1, "hlc.logical")?, "hlc.logical")?,
146
        })
14740837×
    }
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 {
16274296×
    pub(crate) fn tag(self) -> u64 {
16374296×
        match self {
16473216×
            NodeKind::File => 0,
1651052×
            NodeKind::Dir => 1,
1663×
            NodeKind::Symlink => 2,
16725×
            NodeKind::Subrepo => 3,
168
        }
16974296×
    }
17098979×
    pub(crate) fn from_tag(t: u64) -> Result<NodeKind, ObjectError> {
17198979×
        Ok(match t {
17296758×
            0 => NodeKind::File,
1732089×
            1 => NodeKind::Dir,
1749×
            2 => NodeKind::Symlink,
175123×
            3 => NodeKind::Subrepo,
1760×
            _ => return schema(format!("unknown node kind {t}")),
177
        })
17898979×
    }
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
    };
19773904×
    pub(crate) fn bits(self) -> u64 {
19873904×
        (self.exec as u64) | ((self.opaque as u64) << 1)
19973904×
    }
20098939×
    pub(crate) fn from_bits(b: u64) -> Result<Mode, ObjectError> {
20198939×
        if b > 3 {
2021×
            return schema(format!("unknown mode bits {b}"));
20398938×
        }
20498938×
        Ok(Mode {
20598938×
            exec: b & 1 != 0,
20698938×
            opaque: b & 2 != 0,
20798938×
        })
20898939×
    }
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 {
220721×
    fn to_value(self) -> Value {
221721×
        Value::Array(vec![
222721×
            Value::Bytes(self.change.0.to_vec()),
223721×
            Value::Uint(self.index as u64),
224721×
        ])
225721×
    }
2261162×
    fn from_value(v: &Value, what: &str) -> Result<OpRef, ObjectError> {
2271162×
        let a = array(v, what)?;
2281162×
        if a.len() != 2 {
2290×
            return schema(format!("{what}: expected [hash, index]"));
2301162×
        }
231
        Ok(OpRef {
2321162×
            change: oref(&a[0], what)?,
2331162×
            index: u32_(&a[1], what)?,
234
        })
2351162×
    }
236
    /// Replace a self reference with the concrete change hash.
2371150×
    pub fn resolve(self, me: ChangeHash) -> OpRef {
2381150×
        if self.change.is_zero() {
2391×
            OpRef { change: me, ..self }
240
        } else {
2411149×
            self
242
        }
2431150×
    }
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).
27348899×
pub fn validate_name(name: &str) -> Result<(), ObjectError> {
27448899×
    if name.is_empty() || name == "." || name == ".." || name.contains('/') || name.contains('\0') {
2756×
        return schema(format!("invalid placement name {name:?}"));
27648893×
    }
27748893×
    Ok(())
27848899×
}
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
2907145×
    fn to_value(&self) -> Value {
29113629×
        let nid = |n: &NodeId| Value::Bytes(n.0.to_vec());
2927145×
        match self {
293
            TreeOp::AddNode {
2946424×
                node,
2956424×
                kind,
2966424×
                mode,
2976424×
                parent,
2986424×
                name,
2996424×
            } => Value::map([
3006424×
                (0, Value::Uint(0)),
3016424×
                (1, nid(node)),
3026424×
                (2, Value::Uint(kind.tag())),
3036424×
                (3, Value::Uint(mode.bits())),
3046424×
                (4, nid(parent)),
3056424×
                (5, Value::Text(name.clone())),
3066424×
            ]),
307594×
            TreeOp::RemoveNode { node, placement } => Value::map([
308594×
                (0, Value::Uint(1)),
309594×
                (1, nid(node)),
310594×
                (2, placement.to_value()),
311594×
            ]),
312
            TreeOp::Move {
31360×
                node,
31460×
                old,
31560×
                parent,
31660×
                name,
31760×
            } => Value::map([
31860×
                (0, Value::Uint(2)),
31960×
                (1, nid(node)),
32060×
                (2, old.to_value()),
32160×
                (4, nid(parent)),
32260×
                (5, Value::Text(name.clone())),
32360×
            ]),
32467×
            TreeOp::SetMode { node, old, mode } => Value::map([
32567×
                (0, Value::Uint(3)),
32667×
                (1, nid(node)),
32767×
                (2, old.to_value()),
32867×
                (3, Value::Uint(mode.bits())),
32967×
            ]),
330
        }
3317145×
    }
332
33349838×
    fn from_value(v: &Value) -> Result<TreeOp, ObjectError> {
33449838×
        let m = map(v, "tree_op")?;
33549838×
        let tag = uint(field(m, 0, "tree_op tag")?, "tree_op tag")?;
33649838×
        let node = node_id(field(m, 1, "tree_op.node")?, "tree_op.node")?;
33749838×
        let op = match tag {
338
            0 => {
33948676×
                let name = text(field(m, 5, "name")?, "name")?.to_owned();
34048676×
                validate_name(&name)?;
341
                TreeOp::AddNode {
34248676×
                    node,
34348676×
                    kind: NodeKind::from_tag(uint(field(m, 2, "kind")?, "kind")?)?,
34448676×
                    mode: Mode::from_bits(uint(field(m, 3, "mode")?, "mode")?)?,
34548676×
                    parent: node_id(field(m, 4, "parent")?, "parent")?,
34648676×
                    name,
347
                }
348
            }
349
            1 => TreeOp::RemoveNode {
350927×
                node,
351927×
                placement: OpRef::from_value(field(m, 2, "placement")?, "placement")?,
352
            },
353
            2 => {
354196×
                let name = text(field(m, 5, "name")?, "name")?.to_owned();
355196×
                validate_name(&name)?;
356
                TreeOp::Move {
357196×
                    node,
358196×
                    old: OpRef::from_value(field(m, 2, "old")?, "old")?,
359196×
                    parent: node_id(field(m, 4, "parent")?, "parent")?,
360196×
                    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
        };
37049838×
        if node.is_root() {
3710×
            return schema("tree op on the root node");
37249838×
        }
37349838×
        Ok(op)
37449838×
    }
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 {
38716590×
    fn to_value(self) -> Value {
38816590×
        match self {
3895990×
            AtomRef::Start => Value::Uint(0),
3906266×
            AtomRef::End => Value::Uint(1),
3914334×
            AtomRef::Atom { change, index } => Value::Array(vec![
3924334×
                Value::Bytes(change.0.to_vec()),
3934334×
                Value::Uint(index as u64),
3944334×
            ]),
395
        }
39616590×
    }
397102990×
    fn from_value(v: &Value, what: &str) -> Result<AtomRef, ObjectError> {
3988650×
        match v {
39946379×
            Value::Uint(0) => Ok(AtomRef::Start),
40047961×
            Value::Uint(1) => Ok(AtomRef::End),
4018650×
            Value::Array(a) if a.len() == 2 => Ok(AtomRef::Atom {
4028650×
                change: oref(&a[0], what)?,
4038650×
                index: u32_(&a[1], what)?,
404
            }),
4050×
            _ => schema(format!("{what}: expected atom reference")),
406
        }
407102990×
    }
40864268×
    pub fn resolve(self, me: ChangeHash) -> AtomRef {
4099147×
        match self {
4109147×
            AtomRef::Atom { change, index } if change.is_zero() => {
41138×
                AtomRef::Atom { change: me, index }
412
            }
41364230×
            other => other,
414
        }
41564268×
    }
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 {
4272566×
    fn to_value(self) -> Value {
4282566×
        Value::Array(vec![
4292566×
            Value::Bytes(self.change.0.to_vec()),
4302566×
            Value::Uint(self.from as u64),
4312566×
            Value::Uint(self.to as u64),
4322566×
        ])
4332566×
    }
4344151×
    fn from_value(v: &Value) -> Result<AtomRange, ObjectError> {
4354151×
        let a = array(v, "atom range")?;
4364151×
        if a.len() != 3 {
4370×
            return schema("atom range: expected [hash, from, to]");
4384151×
        }
4394151×
        let r = AtomRange {
4404151×
            change: oref(&a[0], "range.change")?,
4414151×
            from: u32_(&a[1], "range.from")?,
4424151×
            to: u32_(&a[2], "range.to")?,
443
        };
4444151×
        if r.from >= r.to {
4450×
            return schema("atom range: empty or inverted");
4464151×
        }
4474151×
        Ok(r)
4484151×
    }
4494448×
    pub fn resolve(self, me: ChangeHash) -> AtomRange {
4504448×
        if self.change.is_zero() {
45118×
            AtomRange { change: me, ..self }
452
        } else {
4534430×
            self
454
        }
4554448×
    }
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 {
47848749×
    pub fn node(&self) -> NodeId {
47948749×
        match self {
48045290×
            Edit::Insert { node, .. } | Edit::Delete { node, .. } | Edit::Replace { node, .. } => {
48148749×
                *node
482
            }
483
        }
48448749×
    }
485
486
    /// Whether this insert is stored as a text blob in a change of `version`.
48710657×
    fn stored_text(&self, version: u64) -> bool {
4888298×
        matches!(self, Edit::Insert { lines, .. }
4898298×
            if version >= 2 && cbor::byte_strings_len(lines) >= TEXT_BLOB_MIN)
49010657×
    }
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).
49610650×
    fn to_value(&self, stored: Option<(ObjectRef, TextForm)>, compact: bool) -> Value {
49710650×
        let nid = |n: &NodeId| Value::Bytes(n.0.to_vec());
49810650×
        let opt = |o: &Option<ObjectRef>| match o {
499204×
            Some(r) => Value::Bytes(r.0.to_vec()),
500140×
            None => Value::Null,
501344×
        };
50210650×
        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 {
5278196×
                    node,
5288196×
                    after,
5298196×
                    before,
5308196×
                    lines,
531
                },
532
                None,
5338196×
            ) => Value::map([
5348196×
                (0, Value::Uint(0)),
5358196×
                (1, nid(node)),
5368196×
                (2, after.to_value()),
5378196×
                (3, before.to_value()),
538
                (
539
                    4,
5408196×
                    if compact {
5418190×
                        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
            ]),
5472183×
            (Edit::Delete { node, atoms }, _) => Value::map([
5482183×
                (0, Value::Uint(1)),
5492183×
                (1, nid(node)),
550
                (
551
                    2,
5522566×
                    Value::Array(atoms.iter().map(|r| r.to_value()).collect()),
553
                ),
554
            ]),
555172×
            (Edit::Replace { node, old, new }, _) => Value::map([
556172×
                (0, Value::Uint(2)),
557172×
                (1, nid(node)),
558172×
                (2, opt(old)),
559172×
                (3, opt(new)),
560172×
            ]),
561
        }
56210650×
    }
563
5648384×
    fn from_value(v: &Value, version: u64, resolve: &mut Resolver) -> Result<Edit, ObjectError> {
5658384×
        let m = map(v, "edit")?;
5668384×
        let tag = uint(field(m, 0, "edit tag")?, "edit tag")?;
5678384×
        let node = node_id(field(m, 1, "edit.node")?, "edit.node")?;
5688384×
        let opt = |v: &Value, what: &str| -> Result<Option<ObjectRef>, ObjectError> {
5691708×
            if v.is_null() {
570755×
                Ok(None)
571
            } else {
572953×
                Ok(Some(oref(v, what)?))
573
            }
5741708×
        };
5758384×
        Ok(match tag {
576
            0 => {
5774331×
                let lines = match (m.get(&4), m.get(&5)) {
5784065×
                    (Some(inline), None) => {
5794065×
                        let lines = array_lines(inline)?;
5804065×
                        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");
5824064×
                        }
5834064×
                        if lines.is_empty() {
5840×
                            return schema("insert with no lines");
5854064×
                        }
5864064×
                        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 {
6104328×
                    node,
6114328×
                    after: AtomRef::from_value(field(m, 2, "after")?, "after")?,
6124328×
                    before: AtomRef::from_value(field(m, 3, "before")?, "before")?,
6134328×
                    lines,
614
                }
615
            }
616
            1 => {
6173199×
                let atoms = array(field(m, 2, "atoms")?, "atoms")?
6183199×
                    .iter()
6193199×
                    .map(AtomRange::from_value)
6203199×
                    .collect::<Result<Vec<_>, _>>()?;
6213199×
                if atoms.is_empty() {
6220×
                    return schema("delete with no atoms");
6233199×
                }
6243199×
                Edit::Delete { node, atoms }
625
            }
626
            2 => Edit::Replace {
627854×
                node,
628854×
                old: opt(field(m, 2, "old")?, "old")?,
629854×
                new: opt(field(m, 3, "new")?, "new")?,
630
            },
6310×
            _ => return schema(format!("unknown edit tag {tag}")),
632
        })
6338384×
    }
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 {
64617887×
    pub(crate) fn tag(self) -> u64 {
64717887×
        match self {
64815012×
            ChangeKind::Normal => 0,
64944×
            ChangeKind::Resolution => 1,
6502831×
            ChangeKind::WorkingCopy => 2,
651
        }
65217887×
    }
65330909×
    pub(crate) fn from_tag(t: u64) -> Result<ChangeKind, ObjectError> {
65430909×
        Ok(match t {
65527604×
            0 => ChangeKind::Normal,
656148×
            1 => ChangeKind::Resolution,
6573157×
            2 => ChangeKind::WorkingCopy,
6580×
            _ => return schema(format!("unknown change kind {t}")),
659
        })
66030909×
    }
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 {
6806236×
    pub fn normalize(&mut self) {
6816236×
        self.deps.sort();
6826236×
        self.deps.dedup();
6836236×
    }
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.
6938844×
    fn stored_texts(&self, sink: &mut TextSink) -> Vec<Option<(ObjectRef, TextForm)>> {
694
        use rayon::prelude::*;
6958844×
        let mut refs: Vec<Option<(ObjectRef, TextForm)>> = vec![None; self.edits.len()];
6968844×
        let stored: Vec<usize> = (0..self.edits.len())
69710650×
            .filter(|i| self.edits[*i].stored_text(self.version))
6988844×
            .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.
7028844×
        let mut batches: Vec<&[usize]> = Vec::new();
7038844×
        let (mut start, mut bytes) = (0, 0usize);
7048844×
        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
        }
7138844×
        if start < stored.len() {
71498×
            batches.push(&stored[start..]);
7158746×
        }
7168844×
        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
        }
7428844×
        refs
7438844×
    }
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.
7478844×
    fn value_with(&self, sink: &mut TextSink, compact: bool) -> Value {
7488844×
        Value::map([
7498844×
            (0, Value::Uint(self.version)),
7508844×
            (1, Value::Bytes(self.change_id.0.to_vec())),
751
            (
752
                2,
753
                Value::Array(
7548844×
                    self.deps
7558844×
                        .iter()
75610214×
                        .map(|d| Value::Bytes(d.0.to_vec()))
7578844×
                        .collect(),
758
                ),
759
            ),
7608844×
            (3, Value::Bytes(self.author.0.to_vec())),
7618844×
            (4, self.hlc.to_value()),
7628844×
            (5, Value::Text(self.message.clone())),
763
            (
764
                6,
7658844×
                Value::Array(self.tree_ops.iter().map(|t| t.to_value()).collect()),
766
            ),
767
            (
768
                7,
769
                Value::Array(
7708844×
                    self.edits
7718844×
                        .iter()
7728844×
                        .zip(self.stored_texts(sink))
77310650×
                        .map(|(e, stored)| e.to_value(stored, compact))
7748844×
                        .collect(),
775
                ),
776
            ),
7778844×
            (8, Value::Uint(self.kind.tag())),
7788844×
            (9, Value::Map(BTreeMap::new())),
779
        ])
7808844×
    }
781
7824519×
    pub fn encode(&self) -> Vec<u8> {
7834519×
        debug_assert!(
7844519×
            self.deps.windows(2).all(|w| w[0] < w[1]),
785
            "deps must be normalized"
786
        );
7874519×
        cbor::encode(&self.value_with(&mut |_| true, true))
7884519×
    }
789
790
    /// The encoding and the text blobs its large inserts are stored as,
791
    /// which must be stored with it.
792132×
    pub fn encode_parts(&self) -> (Vec<u8>, Vec<StoredText>) {
793132×
        debug_assert!(
794132×
            self.deps.windows(2).all(|w| w[0] < w[1]),
795
            "deps must be normalized"
796
        );
797132×
        let mut texts = Vec::new();
798132×
        let bytes = cbor::encode(&self.value_with(
7995×
            &mut |batch| {
8005×
                texts.extend(batch);
8015×
                true
8025×
            },
803
            true,
804
        ));
805132×
        (bytes, texts)
806132×
    }
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.
8114187×
    pub fn encode_streaming<E>(
8124187×
        &self,
8134187×
        mut store: impl FnMut(Vec<StoredText>) -> Result<(), E>,
8144187×
    ) -> Result<Vec<u8>, E> {
8154187×
        debug_assert!(
8164187×
            self.deps.windows(2).all(|w| w[0] < w[1]),
817
            "deps must be normalized"
818
        );
8194187×
        let mut failed = None;
8204187×
        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
        );
8304187×
        match failed {
8310×
            Some(e) => Err(e),
8324187×
            None => Ok(cbor::encode(&value)),
833
        }
8344187×
    }
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
8414076×
    pub fn hash(&self) -> ChangeHash {
8424076×
        hash_object(ObjectType::Change, &self.encode())
8434076×
    }
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).
8585845×
    pub fn decode_with(bytes: &[u8], resolve: &mut Resolver) -> Result<Change, ObjectError> {
8595845×
        let v = cbor::decode(bytes)?;
8605845×
        Self::from_value_with(&v, resolve)
8615845×
    }
862
86312726×
    pub fn from_value(v: &Value) -> Result<Change, ObjectError> {
86412726×
        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×
        })
87012726×
    }
871
87218571×
    pub(crate) fn from_value_with(
87318571×
        v: &Value,
87418571×
        resolve: &mut Resolver,
87518571×
    ) -> Result<Change, ObjectError> {
87618571×
        let m = map(v, "change")?;
87718571×
        let version = uint(field(m, 0, "version")?, "version")?;
87818571×
        if !(1..=CHANGE_VERSION).contains(&version) {
8791×
            return schema(format!("unsupported change format version {version}"));
88018570×
        }
88118570×
        let change_id = ChangeId::from_slice(bytes(field(m, 1, "change_id")?, "change_id")?)
88218570×
            .ok_or_else(|| ObjectError::Schema("change_id: expected 16 bytes".into()))?;
88318570×
        let deps = array(field(m, 2, "deps")?, "deps")?
88418570×
            .iter()
88518570×
            .map(|d| oref(d, "dep"))
88618570×
            .collect::<Result<Vec<_>, _>>()?;
88718570×
        if !deps.windows(2).all(|w| w[0] < w[1]) {
8881×
            return schema("deps must be sorted and unique");
88918569×
        }
89018569×
        if deps.iter().any(|d| d.is_zero()) {
8910×
            return schema("deps may not contain the self reference");
89218569×
        }
89318569×
        let extra = map(field(m, 9, "extra")?, "extra")?;
89418569×
        if !extra.is_empty() {
8951×
            return schema("extra must be empty in format version 1");
89618568×
        }
897
        Ok(Change {
89818568×
            version,
89918568×
            change_id,
90018568×
            deps,
90118568×
            author: oref(field(m, 3, "author")?, "author")?,
90218568×
            hlc: Hlc::from_value(field(m, 4, "hlc")?)?,
90318568×
            message: text(field(m, 5, "message")?, "message")?.to_owned(),
90418568×
            tree_ops: array(field(m, 6, "tree_ops")?, "tree_ops")?
90518568×
                .iter()
90618568×
                .map(TreeOp::from_value)
90718568×
                .collect::<Result<Vec<_>, _>>()?,
90818568×
            edits: array(field(m, 7, "edits")?, "edits")?
90918568×
                .iter()
91018568×
                .map(|e| Edit::from_value(e, version, resolve))
91118568×
                .collect::<Result<Vec<_>, _>>()?,
91218565×
            kind: ChangeKind::from_tag(uint(field(m, 8, "kind")?, "kind")?)?,
913
        })
91418571×
    }
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`]).
94432338×
pub fn inline_lines(array: &[u8]) -> Result<Lines, ObjectError> {
94532338×
    let v = cbor::decode(array)?;
94632338×
    let lines = array_lines(&v)?;
94732338×
    if lines.is_empty() {
9480×
        return schema("insert with no lines");
94932338×
    }
95032338×
    Ok(lines)
95132338×
}
952
953
/// The lines of a CBOR array of byte strings, copied once into one buffer.
95436409×
fn array_lines(v: &Value) -> Result<Lines, ObjectError> {
95536409×
    Ok(array(v, "lines")?
95636409×
        .iter()
95759223×
        .map(|l| bytes(l, "line"))
95836409×
        .collect::<Result<Vec<&[u8]>, _>>()?
95936409×
        .into_iter()
96036409×
        .collect())
96136409×
}
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.
9699392×
    pub fn decode_skeleton(
9709392×
        bytes: &[u8],
9719392×
        me: ChangeHash,
9729392×
    ) -> Result<(Change, Vec<TextRef>), ObjectError> {
9739392×
        let mut c = cbor::Cursor::new(bytes);
9749392×
        let (major, n) = c.head()?;
9759392×
        if major != 5 {
9760×
            return schema("change: expected map");
9779392×
        }
9789392×
        let mut fields = Map::new();
9799392×
        let mut edits = Vec::new();
9809392×
        let mut texts = Vec::new();
9819392×
        let mut version = None;
9829392×
        let mut last: Option<u64> = None;
9839392×
        for _ in 0..n {
98493918×
            let k = map_key(&mut c, &mut last)?;
98593918×
            if k == 7 {
9869392×
                let Some(v) = version else {
9870×
                    return schema("change: version must come first");
988
                };
9899392×
                let (am, an) = c.head()?;
9909392×
                if am != 4 {
9910×
                    return schema("edits: expected array");
9929392×
                }
9939392×
                for _ in 0..an {
99450297×
                    edits.push(edit_skeleton(&mut c, v, me, &mut texts)?);
995
                }
9969391×
                fields.insert(7, Value::Array(Vec::new()));
997
            } else {
99884526×
                let val = c.value()?;
99984526×
                if k == 0 {
10009392×
                    version = Some(uint(&val, "version")?);
100175134×
                }
100284526×
                fields.insert(k, val);
1003
            }
1004
        }
10059391×
        if !c.at_end() {
10060×
            return Err(ObjectError::Cbor(cbor::CborError::TrailingBytes));
10079391×
        }
10089391×
        let mut change = Change::from_value(&Value::Map(fields))?;
10099391×
        change.edits = edits;
10109391×
        Ok((change, texts))
10119392×
    }
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.
10183331×
    pub fn decode_meta(bytes: &[u8]) -> Result<crate::state::ChangeMeta, ObjectError> {
10193331×
        let mut c = cbor::Cursor::new(bytes);
10203331×
        let (major, n) = c.head()?;
10213331×
        if major != 5 {
10220×
            return schema("change: expected map");
10233331×
        }
10243331×
        let mut fields = Map::new();
10253331×
        let mut last: Option<u64> = None;
10263331×
        for _ in 0..n {
102733310×
            let k = map_key(&mut c, &mut last)?;
102833310×
            if k == 6 || k == 7 {
10296662×
                c.skip()?;
10306662×
                fields.insert(k, Value::Array(Vec::new()));
1031
            } else {
103226648×
                fields.insert(k, c.value()?);
1033
            }
1034
        }
10353331×
        if !c.at_end() {
10360×
            return Err(ObjectError::Cbor(cbor::CborError::TrailingBytes));
10373331×
        }
10383331×
        Ok(crate::state::ChangeMeta::of(&Change::from_value(
10393331×
            &Value::Map(fields),
10400×
        )?))
10413331×
    }
1042
}
1043
1044
/// A canonical map key: an unsigned integer above the previous one.
1045373543×
fn map_key(c: &mut cbor::Cursor, last: &mut Option<u64>) -> Result<u64, ObjectError> {
1046373543×
    let (km, k) = c.head()?;
1047373543×
    if km != 0 || last.is_some_and(|l| k <= l) {
10480×
        return Err(ObjectError::Cbor(cbor::CborError::BadMapKey));
1049373543×
    }
1050373543×
    *last = Some(k);
1051373543×
    Ok(k)
1052373543×
}
1053
1054
/// One edit of [`Change::decode_skeleton`]: an insert's lines are left out.
105550297×
fn edit_skeleton(
105650297×
    c: &mut cbor::Cursor,
105750297×
    version: u64,
105850297×
    me: ChangeHash,
105950297×
    texts: &mut Vec<TextRef>,
106050297×
) -> Result<Edit, ObjectError> {
106150297×
    let (major, n) = c.head()?;
106250297×
    if major != 5 {
10630×
        return schema("edit: expected map");
106450297×
    }
106550297×
    let mut fields = Map::new();
106650297×
    let mut inline: Option<(usize, usize, u64)> = None;
106750297×
    let mut last: Option<u64> = None;
106850297×
    for _ in 0..n {
1069246315×
        let k = map_key(c, &mut last)?;
1070246315×
        if k == 4 {
107147168×
            let start = c.pos();
107247168×
            let (am, count) = c.head()?;
107347168×
            if am != 4 {
10740×
                return schema("lines: expected array");
107547168×
            }
107647168×
            for _ in 0..count {
107763398×
                c.skip()?;
1078
            }
107947168×
            inline = Some((start, c.pos(), count));
108047168×
            continue;
1081199147×
        }
1082199147×
        fields.insert(k, c.value()?);
1083
    }
108450297×
    let Some((start, end, count)) = inline else {
10853129×
        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
    };
109047168×
    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");
109247168×
    }
109347168×
    if count == 0 {
10940×
        return schema("insert with no lines");
109547168×
    }
109647168×
    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");
109847167×
    }
109947167×
    let (Ok(start), Ok(end)) = (u32::try_from(start), u32::try_from(end)) else {
11000×
        return schema("change too large");
1101
    };
110247167×
    texts.push(TextRef::Inline {
110347167×
        change: me,
110447167×
        start,
110547167×
        end,
110647167×
    });
1107
    Ok(Edit::Insert {
110847167×
        node: node_id(field(&fields, 1, "edit.node")?, "edit.node")?,
110947167×
        after: AtomRef::from_value(field(&fields, 2, "after")?, "after")?,
111047167×
        before: AtomRef::from_value(field(&fields, 3, "before")?, "before")?,
111147167×
        lines: Lines::default(),
1112
    })
111350297×
}
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).
1173520×
    pub fn of(content: &[u8]) -> Blob {
1174
        Blob {
1175520×
            length: content.len() as u64,
1176520×
            chunks: crate::chunk::chunks(content)
1177520×
                .into_iter()
1178670×
                .map(|c| hash_object(ObjectType::Chunk, c))
1179520×
                .collect(),
1180
        }
1181520×
    }
1182
1183648×
    pub fn encode(&self) -> Vec<u8> {
1184648×
        cbor::encode(&Value::map([
1185648×
            (0, Value::Uint(FORMAT_VERSION)),
1186648×
            (1, Value::Uint(self.length)),
1187
            (
1188
                2,
1189
                Value::Array(
1190648×
                    self.chunks
1191648×
                        .iter()
1192897×
                        .map(|c| Value::Bytes(c.0.to_vec()))
1193648×
                        .collect(),
1194
                ),
1195
            ),
1196
        ]))
1197648×
    }
1198418×
    pub fn hash(&self) -> ObjectRef {
1199418×
        hash_object(ObjectType::Blob, &self.encode())
1200418×
    }
1201465×
    pub fn decode(bytes: &[u8]) -> Result<Blob, ObjectError> {
1202465×
        let v = cbor::decode(bytes)?;
1203465×
        let m = map(&v, "blob")?;
1204465×
        check_version(m)?;
1205
        Ok(Blob {
1206465×
            length: uint(field(m, 1, "length")?, "length")?,
1207465×
            chunks: array(field(m, 2, "chunks")?, "chunks")?
1208465×
                .iter()
1209711×
                .map(|c| oref(c, "chunk"))
1210465×
                .collect::<Result<Vec<_>, _>>()?,
1211
        })
1212465×
    }
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 {
12703683×
    pub fn new(mut heads: Vec<ChangeHash>) -> StateObject {
12713683×
        heads.sort();
12723683×
        heads.dedup();
12733683×
        StateObject { heads }
12743683×
    }
12753682×
    pub fn encode(&self) -> Vec<u8> {
12763682×
        debug_assert!(self.heads.windows(2).all(|w| w[0] < w[1]));
12773682×
        cbor::encode(&Value::map([
12783682×
            (0, Value::Uint(FORMAT_VERSION)),
1279
            (
1280
                1,
1281
                Value::Array(
12823682×
                    self.heads
12833682×
                        .iter()
12844524×
                        .map(|h| Value::Bytes(h.0.to_vec()))
12853682×
                        .collect(),
1286
                ),
1287
            ),
1288
        ]))
12893682×
    }
12902×
    pub fn hash(&self) -> ObjectRef {
12912×
        hash_object(ObjectType::State, &self.encode())
12922×
    }
12936233×
    pub fn decode(bytes: &[u8]) -> Result<StateObject, ObjectError> {
12946233×
        let v = cbor::decode(bytes)?;
12956233×
        let m = map(&v, "state")?;
12966233×
        check_version(m)?;
12976233×
        let heads = array(field(m, 1, "heads")?, "heads")?
12986233×
            .iter()
12999995×
            .map(|h| oref(h, "head"))
13006233×
            .collect::<Result<Vec<_>, _>>()?;
13016233×
        if !heads.windows(2).all(|w| w[0] < w[1]) {
13020×
            return schema("state heads must be sorted and unique");
13036233×
        }
13046233×
        Ok(StateObject { heads })
13056233×
    }
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
}