OXYGENHUB

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

1065 of 1128 lines run, 222 of 298 functions · run #259 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
}
49
5018×
pub(crate) fn schema<T>(msg: impl Into<String>) -> Result<T, ObjectError> {
5118×
    Err(ObjectError::Schema(msg.into()))
5218×
}
53
54
pub(crate) type Map = BTreeMap<u64, Value>;
55
56877571×
pub(crate) fn field<'a>(m: &'a Map, k: u64, what: &str) -> Result<&'a Value, ObjectError> {
57877571×
    m.get(&k)
58877571×
        .ok_or_else(|| ObjectError::Schema(format!("missing field {k} ({what})")))
59877571×
}
60361086×
pub(crate) fn uint(v: &Value, what: &str) -> Result<u64, ObjectError> {
61361086×
    v.as_uint()
62361086×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected unsigned integer")))
63361086×
}
6463044×
pub(crate) fn u32_(v: &Value, what: &str) -> Result<u32, ObjectError> {
6563044×
    u32::try_from(uint(v, what)?).map_err(|_| ObjectError::Schema(format!("{what}: exceeds u32")))
6663044×
}
67118989×
pub(crate) fn text<'a>(v: &'a Value, what: &str) -> Result<&'a str, ObjectError> {
68118989×
    v.as_text()
69118989×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected text")))
70118989×
}
71264275×
pub(crate) fn array<'a>(v: &'a Value, what: &str) -> Result<&'a [Value], ObjectError> {
72264275×
    v.as_array()
73264275×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected array")))
74264275×
}
75128884×
pub(crate) fn map<'a>(v: &'a Value, what: &str) -> Result<&'a Map, ObjectError> {
76128884×
    v.as_map()
77128884×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected map")))
78128884×
}
79377075×
pub(crate) fn bytes<'a>(v: &'a Value, what: &str) -> Result<&'a [u8], ObjectError> {
80377075×
    v.as_bytes()
81377075×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected bytes")))
82377075×
}
83126474×
pub(crate) fn oref(v: &Value, what: &str) -> Result<ObjectRef, ObjectError> {
84126474×
    ObjectRef::from_slice(bytes(v, what)?)
85126473×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected 32 bytes")))
86126474×
}
87146717×
pub(crate) fn node_id(v: &Value, what: &str) -> Result<NodeId, ObjectError> {
88146717×
    NodeId::from_slice(bytes(v, what)?)
89146717×
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected 16 bytes")))
90146717×
}
9125703×
pub(crate) fn check_version(m: &Map) -> Result<(), ObjectError> {
9225703×
    let v = uint(field(m, 0, "version")?, "version")?;
9325703×
    if v != FORMAT_VERSION {
940×
        let exe = std::env::current_exe()
950×
            .map(|p| format!(" at {}", p.display()))
960×
            .unwrap_or_default();
970×
        let which = format!("oxy {}{exe}", crate::VERSION);
980×
        return schema(if v > FORMAT_VERSION {
990×
            format!(
100
                "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"
101
            )
102
        } else {
1030×
            format!(
104
                "this data is format {v}, written by an older oxy, and {which} reads format {FORMAT_VERSION} only"
105
            )
106
        });
10725703×
    }
10825703×
    Ok(())
10925703×
}
110
111
// ---------------------------------------------------------------- Hlc
112
113
/// Hybrid logical clock (spec §6.4).
114
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
115
pub struct Hlc {
116
    pub wall_ms: u64,
117
    pub logical: u32,
118
}
119
120
impl Hlc {
1215693×
    pub fn now() -> Hlc {
1225693×
        let wall_ms = std::time::SystemTime::now()
1235693×
            .duration_since(std::time::UNIX_EPOCH)
1245693×
            .map(|d| d.as_millis() as u64)
1255693×
            .unwrap_or(0);
1265693×
        Hlc {
1275693×
            wall_ms,
1285693×
            logical: 0,
1295693×
        }
1305693×
    }
13111168×
    pub(crate) fn to_value(self) -> Value {
13211168×
        Value::map([
13311168×
            (0, Value::Uint(self.wall_ms)),
13411168×
            (1, Value::Uint(self.logical as u64)),
13511168×
        ])
13611168×
    }
13733213×
    pub(crate) fn from_value(v: &Value) -> Result<Hlc, ObjectError> {
13833213×
        let m = map(v, "hlc")?;
139
        Ok(Hlc {
14033213×
            wall_ms: uint(field(m, 0, "hlc.wall_ms")?, "hlc.wall_ms")?,
14133213×
            logical: u32_(field(m, 1, "hlc.logical")?, "hlc.logical")?,
142
        })
14333213×
    }
144
}
145
146
// ---------------------------------------------------------------- tree
147
148
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
149
pub enum NodeKind {
150
    File,
151
    Dir,
152
    Symlink,
153
    /// A nested repository pinned to a state (spec §7.8); content is a pin.
154
    Subrepo,
155
}
156
157
impl NodeKind {
15873375×
    pub(crate) fn tag(self) -> u64 {
15973375×
        match self {
16072406×
            NodeKind::File => 0,
161946×
            NodeKind::Dir => 1,
1623×
            NodeKind::Symlink => 2,
16320×
            NodeKind::Subrepo => 3,
164
        }
16573375×
    }
16696800×
    pub(crate) fn from_tag(t: u64) -> Result<NodeKind, ObjectError> {
16796800×
        Ok(match t {
16894768×
            0 => NodeKind::File,
1691931×
            1 => NodeKind::Dir,
1709×
            2 => NodeKind::Symlink,
17192×
            3 => NodeKind::Subrepo,
1720×
            _ => return schema(format!("unknown node kind {t}")),
173
        })
17496800×
    }
175
}
176
177
/// Executable bit plus content mode (spec §7.1, §7.5).
178
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PartialOrd, Ord)]
179
pub struct Mode {
180
    pub exec: bool,
181
    pub opaque: bool,
182
}
183
184
impl Mode {
185
    pub const TEXT: Mode = Mode {
186
        exec: false,
187
        opaque: false,
188
    };
189
    pub const OPAQUE: Mode = Mode {
190
        exec: false,
191
        opaque: true,
192
    };
19373011×
    pub(crate) fn bits(self) -> u64 {
19473011×
        (self.exec as u64) | ((self.opaque as u64) << 1)
19573011×
    }
19696760×
    pub(crate) fn from_bits(b: u64) -> Result<Mode, ObjectError> {
19796760×
        if b > 3 {
1981×
            return schema(format!("unknown mode bits {b}"));
19996759×
        }
20096759×
        Ok(Mode {
20196759×
            exec: b & 1 != 0,
20296759×
            opaque: b & 2 != 0,
20396759×
        })
20496760×
    }
205
}
206
207
/// Reference to a tree operation of some change: the placement or mode atom it
208
/// introduced. `change == ObjectRef::ZERO` means this change.
209
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
210
pub struct OpRef {
211
    pub change: ChangeHash,
212
    pub index: u32,
213
}
214
215
impl OpRef {
216445×
    fn to_value(self) -> Value {
217445×
        Value::Array(vec![
218445×
            Value::Bytes(self.change.0.to_vec()),
219445×
            Value::Uint(self.index as u64),
220445×
        ])
221445×
    }
222744×
    fn from_value(v: &Value, what: &str) -> Result<OpRef, ObjectError> {
223744×
        let a = array(v, what)?;
224744×
        if a.len() != 2 {
2250×
            return schema(format!("{what}: expected [hash, index]"));
226744×
        }
227
        Ok(OpRef {
228744×
            change: oref(&a[0], what)?,
229744×
            index: u32_(&a[1], what)?,
230
        })
231744×
    }
232
    /// Replace a self reference with the concrete change hash.
233752×
    pub fn resolve(self, me: ChangeHash) -> OpRef {
234752×
        if self.change.is_zero() {
2351×
            OpRef { change: me, ..self }
236
        } else {
237751×
            self
238
        }
239752×
    }
240
}
241
242
#[derive(Debug, Clone, PartialEq, Eq)]
243
pub enum TreeOp {
244
    AddNode {
245
        node: NodeId,
246
        kind: NodeKind,
247
        mode: Mode,
248
        parent: NodeId,
249
        name: String,
250
    },
251
    RemoveNode {
252
        node: NodeId,
253
        placement: OpRef,
254
    },
255
    Move {
256
        node: NodeId,
257
        old: OpRef,
258
        parent: NodeId,
259
        name: String,
260
    },
261
    SetMode {
262
        node: NodeId,
263
        old: OpRef,
264
        mode: Mode,
265
    },
266
}
267
268
/// Names must be valid, non-empty, not `.`/`..`, and free of `/` and NUL (spec §7.1).
26946864×
pub fn validate_name(name: &str) -> Result<(), ObjectError> {
27046864×
    if name.is_empty() || name == "." || name == ".." || name.contains('/') || name.contains('\0') {
2716×
        return schema(format!("invalid placement name {name:?}"));
27246858×
    }
27346858×
    Ok(())
27446864×
}
275
276
impl TreeOp {
277104×
    pub fn node(&self) -> NodeId {
278104×
        match self {
27981×
            TreeOp::AddNode { node, .. }
28011×
            | TreeOp::RemoveNode { node, .. }
28111×
            | TreeOp::Move { node, .. }
282104×
            | TreeOp::SetMode { node, .. } => *node,
283
        }
284104×
    }
285
2866196×
    fn to_value(&self) -> Value {
28711978×
        let nid = |n: &NodeId| Value::Bytes(n.0.to_vec());
2886196×
        match self {
289
            TreeOp::AddNode {
2905751×
                node,
2915751×
                kind,
2925751×
                mode,
2935751×
                parent,
2945751×
                name,
2955751×
            } => Value::map([
2965751×
                (0, Value::Uint(0)),
2975751×
                (1, nid(node)),
2985751×
                (2, Value::Uint(kind.tag())),
2995751×
                (3, Value::Uint(mode.bits())),
3005751×
                (4, nid(parent)),
3015751×
                (5, Value::Text(name.clone())),
3025751×
            ]),
303350×
            TreeOp::RemoveNode { node, placement } => Value::map([
304350×
                (0, Value::Uint(1)),
305350×
                (1, nid(node)),
306350×
                (2, placement.to_value()),
307350×
            ]),
308
            TreeOp::Move {
30931×
                node,
31031×
                old,
31131×
                parent,
31231×
                name,
31331×
            } => Value::map([
31431×
                (0, Value::Uint(2)),
31531×
                (1, nid(node)),
31631×
                (2, old.to_value()),
31731×
                (4, nid(parent)),
31831×
                (5, Value::Text(name.clone())),
31931×
            ]),
32064×
            TreeOp::SetMode { node, old, mode } => Value::map([
32164×
                (0, Value::Uint(3)),
32264×
                (1, nid(node)),
32364×
                (2, old.to_value()),
32464×
                (3, Value::Uint(mode.bits())),
32564×
            ]),
326
        }
3276196×
    }
328
32947422×
    fn from_value(v: &Value) -> Result<TreeOp, ObjectError> {
33047422×
        let m = map(v, "tree_op")?;
33147422×
        let tag = uint(field(m, 0, "tree_op tag")?, "tree_op tag")?;
33247422×
        let node = node_id(field(m, 1, "tree_op.node")?, "tree_op.node")?;
33347422×
        let op = match tag {
334
            0 => {
33546678×
                let name = text(field(m, 5, "name")?, "name")?.to_owned();
33646678×
                validate_name(&name)?;
337
                TreeOp::AddNode {
33846678×
                    node,
33946678×
                    kind: NodeKind::from_tag(uint(field(m, 2, "kind")?, "kind")?)?,
34046678×
                    mode: Mode::from_bits(uint(field(m, 3, "mode")?, "mode")?)?,
34146678×
                    parent: node_id(field(m, 4, "parent")?, "parent")?,
34246678×
                    name,
343
                }
344
            }
345
            1 => TreeOp::RemoveNode {
346539×
                node,
347539×
                placement: OpRef::from_value(field(m, 2, "placement")?, "placement")?,
348
            },
349
            2 => {
350167×
                let name = text(field(m, 5, "name")?, "name")?.to_owned();
351167×
                validate_name(&name)?;
352
                TreeOp::Move {
353167×
                    node,
354167×
                    old: OpRef::from_value(field(m, 2, "old")?, "old")?,
355167×
                    parent: node_id(field(m, 4, "parent")?, "parent")?,
356167×
                    name,
357
                }
358
            }
359
            3 => TreeOp::SetMode {
36038×
                node,
36138×
                old: OpRef::from_value(field(m, 2, "old")?, "old")?,
36238×
                mode: Mode::from_bits(uint(field(m, 3, "mode")?, "mode")?)?,
363
            },
3640×
            _ => return schema(format!("unknown tree op tag {tag}")),
365
        };
36647422×
        if node.is_root() {
3670×
            return schema("tree op on the root node");
36847422×
        }
36947422×
        Ok(op)
37047422×
    }
371
}
372
373
// ---------------------------------------------------------------- edits
374
375
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
376
pub enum AtomRef {
377
    Start,
378
    End,
379
    Atom { change: ChangeHash, index: u32 },
380
}
381
382
impl AtomRef {
38314478×
    fn to_value(self) -> Value {
38414478×
        match self {
3855291×
            AtomRef::Start => Value::Uint(0),
3865535×
            AtomRef::End => Value::Uint(1),
3873652×
            AtomRef::Atom { change, index } => Value::Array(vec![
3883652×
                Value::Bytes(change.0.to_vec()),
3893652×
                Value::Uint(index as u64),
3903652×
            ]),
391
        }
39214478×
    }
39397916×
    fn from_value(v: &Value, what: &str) -> Result<AtomRef, ObjectError> {
3947524×
        match v {
39544459×
            Value::Uint(0) => Ok(AtomRef::Start),
39645933×
            Value::Uint(1) => Ok(AtomRef::End),
3977524×
            Value::Array(a) if a.len() == 2 => Ok(AtomRef::Atom {
3987524×
                change: oref(&a[0], what)?,
3997524×
                index: u32_(&a[1], what)?,
400
            }),
4010×
            _ => schema(format!("{what}: expected atom reference")),
402
        }
40397916×
    }
40460632×
    pub fn resolve(self, me: ChangeHash) -> AtomRef {
4058365×
        match self {
4068365×
            AtomRef::Atom { change, index } if change.is_zero() => {
40734×
                AtomRef::Atom { change: me, index }
408
            }
40960598×
            other => other,
410
        }
41160632×
    }
412
}
413
414
/// Half-open range of atoms introduced by one change.
415
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
416
pub struct AtomRange {
417
    pub change: ChangeHash,
418
    pub from: u32,
419
    pub to: u32,
420
}
421
422
impl AtomRange {
4232174×
    fn to_value(self) -> Value {
4242174×
        Value::Array(vec![
4252174×
            Value::Bytes(self.change.0.to_vec()),
4262174×
            Value::Uint(self.from as u64),
4272174×
            Value::Uint(self.to as u64),
4282174×
        ])
4292174×
    }
4303623×
    fn from_value(v: &Value) -> Result<AtomRange, ObjectError> {
4313623×
        let a = array(v, "atom range")?;
4323623×
        if a.len() != 3 {
4330×
            return schema("atom range: expected [hash, from, to]");
4343623×
        }
4353623×
        let r = AtomRange {
4363623×
            change: oref(&a[0], "range.change")?,
4373623×
            from: u32_(&a[1], "range.from")?,
4383623×
            to: u32_(&a[2], "range.to")?,
439
        };
4403623×
        if r.from >= r.to {
4410×
            return schema("atom range: empty or inverted");
4423623×
        }
4433623×
        Ok(r)
4443623×
    }
4454020×
    pub fn resolve(self, me: ChangeHash) -> AtomRange {
4464020×
        if self.change.is_zero() {
44718×
            AtomRange { change: me, ..self }
448
        } else {
4494002×
            self
450
        }
4514020×
    }
452
}
453
454
#[derive(Debug, Clone, PartialEq, Eq)]
455
pub enum Edit {
456
    Insert {
457
        node: NodeId,
458
        after: AtomRef,
459
        before: AtomRef,
460
        lines: crate::lines::Lines,
461
    },
462
    Delete {
463
        node: NodeId,
464
        atoms: Vec<AtomRange>,
465
    },
466
    Replace {
467
        node: NodeId,
468
        old: Option<ObjectRef>,
469
        new: Option<ObjectRef>,
470
    },
471
}
472
473
impl Edit {
47446228×
    pub fn node(&self) -> NodeId {
47546228×
        match self {
47643220×
            Edit::Insert { node, .. } | Edit::Delete { node, .. } | Edit::Replace { node, .. } => {
47746228×
                *node
478
            }
479
        }
48046228×
    }
481
482
    /// Whether this insert is stored as a text blob in a change of `version`.
4839194×
    fn stored_text(&self, version: u64) -> bool {
4847242×
        matches!(self, Edit::Insert { lines, .. }
4857242×
            if version >= 2 && cbor::byte_strings_len(lines) >= TEXT_BLOB_MIN)
4869194×
    }
487
488
    /// The edit's value; `stored` is the text blob of an insert stored as
489
    /// one, and its form (see [`Change::value_with`], which works them out).
490
    /// The edit's value; `compact` writes an inline insert's lines as
491
    /// their encoding rather than a value per line (same bytes encoded).
4929187×
    fn to_value(&self, stored: Option<(ObjectRef, TextForm)>, compact: bool) -> Value {
4939187×
        let nid = |n: &NodeId| Value::Bytes(n.0.to_vec());
4949187×
        let opt = |o: &Option<ObjectRef>| match o {
495176×
            Some(r) => Value::Bytes(r.0.to_vec()),
496116×
            None => Value::Null,
497292×
        };
4989187×
        match (self, stored) {
499
            (
500
                Edit::Insert {
50170×
                    node,
50270×
                    after,
50370×
                    before,
50470×
                    lines,
505
                },
50670×
                Some((r, form)),
507
            ) => {
50870×
                let mut fields = vec![
50970×
                    (0, Value::Uint(0)),
51070×
                    (1, nid(node)),
51170×
                    (2, after.to_value()),
51270×
                    (3, before.to_value()),
51370×
                    (5, Value::Bytes(r.0.to_vec())),
51470×
                    (6, Value::Uint(lines.len() as u64)),
515
                ];
51670×
                if form == TextForm::CborFallback {
5171×
                    fields.push((7, Value::Uint(1)));
51869×
                }
51970×
                Value::map(fields)
520
            }
521
            (
522
                Edit::Insert {
5237169×
                    node,
5247169×
                    after,
5257169×
                    before,
5267169×
                    lines,
527
                },
528
                None,
5297169×
            ) => Value::map([
5307169×
                (0, Value::Uint(0)),
5317169×
                (1, nid(node)),
5327169×
                (2, after.to_value()),
5337169×
                (3, before.to_value()),
534
                (
535
                    4,
5367169×
                    if compact {
5377163×
                        Value::Encoded(cbor::encode_byte_strings(lines))
538
                    } else {
5391008×
                        Value::Array(lines.iter().map(|l| Value::Bytes(l.to_vec())).collect())
540
                    },
541
                ),
542
            ]),
5431802×
            (Edit::Delete { node, atoms }, _) => Value::map([
5441802×
                (0, Value::Uint(1)),
5451802×
                (1, nid(node)),
546
                (
547
                    2,
5482174×
                    Value::Array(atoms.iter().map(|r| r.to_value()).collect()),
549
                ),
550
            ]),
551146×
            (Edit::Replace { node, old, new }, _) => Value::map([
552146×
                (0, Value::Uint(2)),
553146×
                (1, nid(node)),
554146×
                (2, opt(old)),
555146×
                (3, opt(new)),
556146×
            ]),
557
        }
5589187×
    }
559
5607497×
    fn from_value(v: &Value, version: u64, resolve: &mut Resolver) -> Result<Edit, ObjectError> {
5617497×
        let m = map(v, "edit")?;
5627497×
        let tag = uint(field(m, 0, "edit tag")?, "edit tag")?;
5637497×
        let node = node_id(field(m, 1, "edit.node")?, "edit.node")?;
5647497×
        let opt = |v: &Value, what: &str| -> Result<Option<ObjectRef>, ObjectError> {
5651590×
            if v.is_null() {
566697×
                Ok(None)
567
            } else {
568893×
                Ok(Some(oref(v, what)?))
569
            }
5701590×
        };
5717497×
        Ok(match tag {
572
            0 => {
5734008×
                let lines = match (m.get(&4), m.get(&5)) {
5743719×
                    (Some(inline), None) => {
5753719×
                        let lines = array_lines(inline)?;
5763719×
                        if version >= 2 && cbor::byte_strings_len(&lines) >= TEXT_BLOB_MIN {
5771×
                            return schema("an insert this large is stored as a text blob in a version 2 change");
5783718×
                        }
5793718×
                        if lines.is_empty() {
5800×
                            return schema("insert with no lines");
5813718×
                        }
5823718×
                        lines
583
                    }
584289×
                    (None, Some(text)) if version >= 2 => {
585289×
                        let text = oref(text, "insert text")?;
586289×
                        let count = u32_(field(m, 6, "insert line count")?, "insert line count")?;
587289×
                        if count == 0 {
5880×
                            return schema("insert with no lines");
589289×
                        }
590289×
                        let form = match (version, m.get(&7)) {
5911×
                            (2, None) => TextForm::Cbor,
592287×
                            (_, None) => TextForm::Raw,
5931×
                            (3.., Some(Value::Uint(1))) => TextForm::CborFallback,
5940×
                            _ => return schema("unknown text blob form"),
595
                        };
596
                        // The resolver checks the count (`text_lines`).
597289×
                        resolve(&text, count, form)?
598
                    }
599
                    _ => {
6000×
                        return schema(
601
                            "an insert has either its lines or, in a version 2 change, a text blob",
602
                        )
603
                    }
604
                };
605
                Edit::Insert {
6064005×
                    node,
6074005×
                    after: AtomRef::from_value(field(m, 2, "after")?, "after")?,
6084005×
                    before: AtomRef::from_value(field(m, 3, "before")?, "before")?,
6094005×
                    lines,
610
                }
611
            }
612
            1 => {
6132694×
                let atoms = array(field(m, 2, "atoms")?, "atoms")?
6142694×
                    .iter()
6152694×
                    .map(AtomRange::from_value)
6162694×
                    .collect::<Result<Vec<_>, _>>()?;
6172694×
                if atoms.is_empty() {
6180×
                    return schema("delete with no atoms");
6192694×
                }
6202694×
                Edit::Delete { node, atoms }
621
            }
622
            2 => Edit::Replace {
623795×
                node,
624795×
                old: opt(field(m, 2, "old")?, "old")?,
625795×
                new: opt(field(m, 3, "new")?, "new")?,
626
            },
6270×
            _ => return schema(format!("unknown edit tag {tag}")),
628
        })
6297497×
    }
630
}
631
632
// ---------------------------------------------------------------- change
633
634
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
635
pub enum ChangeKind {
636
    Normal,
637
    Resolution,
638
    WorkingCopy,
639
}
640
641
impl ChangeKind {
64211039×
    pub(crate) fn tag(self) -> u64 {
64311039×
        match self {
6448610×
            ChangeKind::Normal => 0,
64541×
            ChangeKind::Resolution => 1,
6462388×
            ChangeKind::WorkingCopy => 2,
647
        }
64811039×
    }
64917487×
    pub(crate) fn from_tag(t: u64) -> Result<ChangeKind, ObjectError> {
65017487×
        Ok(match t {
65114672×
            0 => ChangeKind::Normal,
652119×
            1 => ChangeKind::Resolution,
6532696×
            2 => ChangeKind::WorkingCopy,
6540×
            _ => return schema(format!("unknown change kind {t}")),
655
        })
65617487×
    }
657
}
658
659
/// A change (spec §6.1). `deps` is kept sorted and unique by `normalize`.
660
#[derive(Debug, Clone, PartialEq, Eq)]
661
pub struct Change {
662
    /// The format this change is encoded in: [`CHANGE_VERSION`] for a new
663
    /// one, whatever it was made in for one read back.
664
    pub version: u64,
665
    pub change_id: ChangeId,
666
    pub deps: Vec<ChangeHash>,
667
    pub author: KeyId,
668
    pub hlc: Hlc,
669
    pub message: String,
670
    pub tree_ops: Vec<TreeOp>,
671
    pub edits: Vec<Edit>,
672
    pub kind: ChangeKind,
673
}
674
675
impl Change {
6765566×
    pub fn normalize(&mut self) {
6775566×
        self.deps.sort();
6785566×
        self.deps.dedup();
6795566×
    }
680
6816×
    pub fn to_value(&self) -> Value {
6826×
        self.value_with(&mut |_| true, false)
6836×
    }
684
685
    /// The text blob of each edit stored as one, `None` for the others;
686
    /// the stored texts go to `texts`, in order, when it is given. Worked
687
    /// out on every core, a bounded batch at a time: chunking and hashing
688
    /// a whole tree's text is most of encoding a change that adds it.
6897499×
    fn stored_texts(&self, sink: &mut TextSink) -> Vec<Option<(ObjectRef, TextForm)>> {
690
        use rayon::prelude::*;
6917499×
        let mut refs: Vec<Option<(ObjectRef, TextForm)>> = vec![None; self.edits.len()];
6927499×
        let stored: Vec<usize> = (0..self.edits.len())
6939187×
            .filter(|i| self.edits[*i].stored_text(self.version))
6947499×
            .collect();
695
        // At most 256 texts or 32 MiB of them a batch: some directories
696
        // hold hundreds of generated files of megabytes each, and a batch
697
        // is copied and compressed at once.
6987499×
        let mut batches: Vec<&[usize]> = Vec::new();
6997499×
        let (mut start, mut bytes) = (0, 0usize);
7007499×
        for (k, i) in stored.iter().enumerate() {
70170×
            if let Edit::Insert { lines, .. } = &self.edits[*i] {
70270×
                bytes += lines.bytes().len();
70370×
            }
70470×
            if k + 1 - start == 256 || bytes >= 32 << 20 {
7050×
                batches.push(&stored[start..=k]);
7060×
                (start, bytes) = (k + 1, 0);
70770×
            }
708
        }
7097499×
        if start < stored.len() {
71069×
            batches.push(&stored[start..]);
7117430×
        }
7127499×
        for batch in batches {
71369×
            let made: Vec<StoredText> = batch
71469×
                .par_iter()
71570×
                .map(|i| {
71670×
                    let Edit::Insert { lines, .. } = &self.edits[*i] else {
7170×
                        unreachable!("only inserts are stored as text");
718
                    };
71970×
                    let form = text_form(self.version, lines);
72070×
                    let content = match form {
72168×
                        TextForm::Raw => lines.bytes().to_vec(),
7222×
                        TextForm::Cbor | TextForm::CborFallback => cbor::encode_byte_strings(lines),
723
                    };
72470×
                    StoredText {
72570×
                        blob: Blob::of(&content),
72670×
                        content,
72770×
                        form,
72870×
                    }
72970×
                })
73069×
                .collect();
73170×
            for (i, t) in batch.iter().zip(&made) {
73270×
                refs[*i] = Some((t.blob.hash(), t.form));
73370×
            }
73469×
            if !sink(made) {
7350×
                break;
73669×
            }
737
        }
7387499×
        refs
7397499×
    }
740
741
    /// The change's value, its stored texts handed to `sink`; `compact`
742
    /// as [`Edit::to_value`] takes it, for a value that is only encoded.
7437499×
    fn value_with(&self, sink: &mut TextSink, compact: bool) -> Value {
7447499×
        Value::map([
7457499×
            (0, Value::Uint(self.version)),
7467499×
            (1, Value::Bytes(self.change_id.0.to_vec())),
747
            (
748
                2,
749
                Value::Array(
7507499×
                    self.deps
7517499×
                        .iter()
7529026×
                        .map(|d| Value::Bytes(d.0.to_vec()))
7537499×
                        .collect(),
754
                ),
755
            ),
7567499×
            (3, Value::Bytes(self.author.0.to_vec())),
7577499×
            (4, self.hlc.to_value()),
7587499×
            (5, Value::Text(self.message.clone())),
759
            (
760
                6,
7617499×
                Value::Array(self.tree_ops.iter().map(|t| t.to_value()).collect()),
762
            ),
763
            (
764
                7,
765
                Value::Array(
7667499×
                    self.edits
7677499×
                        .iter()
7687499×
                        .zip(self.stored_texts(sink))
7699187×
                        .map(|(e, stored)| e.to_value(stored, compact))
7707499×
                        .collect(),
771
                ),
772
            ),
7737499×
            (8, Value::Uint(self.kind.tag())),
7747499×
            (9, Value::Map(BTreeMap::new())),
775
        ])
7767499×
    }
777
7783838×
    pub fn encode(&self) -> Vec<u8> {
7793838×
        debug_assert!(
7803838×
            self.deps.windows(2).all(|w| w[0] < w[1]),
781
            "deps must be normalized"
782
        );
7833838×
        cbor::encode(&self.value_with(&mut |_| true, true))
7843838×
    }
785
786
    /// The encoding and the text blobs its large inserts are stored as,
787
    /// which must be stored with it.
788116×
    pub fn encode_parts(&self) -> (Vec<u8>, Vec<StoredText>) {
789116×
        debug_assert!(
790116×
            self.deps.windows(2).all(|w| w[0] < w[1]),
791
            "deps must be normalized"
792
        );
793116×
        let mut texts = Vec::new();
794116×
        let bytes = cbor::encode(&self.value_with(
7955×
            &mut |batch| {
7965×
                texts.extend(batch);
7975×
                true
7985×
            },
799
            true,
800
        ));
801116×
        (bytes, texts)
802116×
    }
803
804
    /// The encoding, handing the stored texts to `store` a batch at a time
805
    /// as they are made, so a change adding a whole tree never holds all
806
    /// its text twice. The first error from `store` is returned.
8073539×
    pub fn encode_streaming<E>(
8083539×
        &self,
8093539×
        mut store: impl FnMut(Vec<StoredText>) -> Result<(), E>,
8103539×
    ) -> Result<Vec<u8>, E> {
8113539×
        debug_assert!(
8123539×
            self.deps.windows(2).all(|w| w[0] < w[1]),
813
            "deps must be normalized"
814
        );
8153539×
        let mut failed = None;
8163539×
        let value = self.value_with(
81759×
            &mut |batch| match store(batch) {
81859×
                Ok(()) => true,
8190×
                Err(e) => {
8200×
                    failed = Some(e);
8210×
                    false
822
                }
82359×
            },
824
            true,
825
        );
8263539×
        match failed {
8270×
            Some(e) => Err(e),
8283539×
            None => Ok(cbor::encode(&value)),
829
        }
8303539×
    }
831
832
    /// Whether any insert is stored as a text blob.
8333×
    pub fn has_stored_text(&self) -> bool {
8347×
        self.edits.iter().any(|e| e.stored_text(self.version))
8353×
    }
836
8373831×
    pub fn hash(&self) -> ChangeHash {
8383831×
        hash_object(ObjectType::Change, &self.encode())
8393831×
    }
840
841
    /// Decode a change that stores no text blob; one that does needs
842
    /// [`Change::decode_with`] and something to read them from.
8434×
    pub fn decode(bytes: &[u8]) -> Result<Change, ObjectError> {
8444×
        Self::decode_with(bytes, &mut |r, _, _| {
8451×
            schema(format!(
846
                "text blob {} needs a store to read it from",
8471×
                r.short(12)
848
            ))
8491×
        })
8504×
    }
851
852
    /// Decode a change, reading each stored insert's lines with `resolve`
853
    /// (given the text blob and the line count the insert claims).
8545129×
    pub fn decode_with(bytes: &[u8], resolve: &mut Resolver) -> Result<Change, ObjectError> {
8555129×
        let v = cbor::decode(bytes)?;
8565129×
        Self::from_value_with(&v, resolve)
8575129×
    }
858
85910308×
    pub fn from_value(v: &Value) -> Result<Change, ObjectError> {
86010308×
        Self::from_value_with(v, &mut |r, _, _| {
8610×
            schema(format!(
862
                "text blob {} needs a store to read it from",
8630×
                r.short(12)
864
            ))
8650×
        })
86610308×
    }
867
86815437×
    pub(crate) fn from_value_with(
86915437×
        v: &Value,
87015437×
        resolve: &mut Resolver,
87115437×
    ) -> Result<Change, ObjectError> {
87215437×
        let m = map(v, "change")?;
87315437×
        let version = uint(field(m, 0, "version")?, "version")?;
87415437×
        if !(1..=CHANGE_VERSION).contains(&version) {
8751×
            return schema(format!("unsupported change format version {version}"));
87615436×
        }
87715436×
        let change_id = ChangeId::from_slice(bytes(field(m, 1, "change_id")?, "change_id")?)
87815436×
            .ok_or_else(|| ObjectError::Schema("change_id: expected 16 bytes".into()))?;
87915436×
        let deps = array(field(m, 2, "deps")?, "deps")?
88015436×
            .iter()
88115436×
            .map(|d| oref(d, "dep"))
88215436×
            .collect::<Result<Vec<_>, _>>()?;
88315436×
        if !deps.windows(2).all(|w| w[0] < w[1]) {
8841×
            return schema("deps must be sorted and unique");
88515435×
        }
88615435×
        if deps.iter().any(|d| d.is_zero()) {
8870×
            return schema("deps may not contain the self reference");
88815435×
        }
88915435×
        let extra = map(field(m, 9, "extra")?, "extra")?;
89015435×
        if !extra.is_empty() {
8911×
            return schema("extra must be empty in format version 1");
89215434×
        }
893
        Ok(Change {
89415434×
            version,
89515434×
            change_id,
89615434×
            deps,
89715434×
            author: oref(field(m, 3, "author")?, "author")?,
89815434×
            hlc: Hlc::from_value(field(m, 4, "hlc")?)?,
89915434×
            message: text(field(m, 5, "message")?, "message")?.to_owned(),
90015434×
            tree_ops: array(field(m, 6, "tree_ops")?, "tree_ops")?
90115434×
                .iter()
90215434×
                .map(TreeOp::from_value)
90315434×
                .collect::<Result<Vec<_>, _>>()?,
90415434×
            edits: array(field(m, 7, "edits")?, "edits")?
90515434×
                .iter()
90615434×
                .map(|e| Edit::from_value(e, version, resolve))
90715434×
                .collect::<Result<Vec<_>, _>>()?,
90815431×
            kind: ChangeKind::from_tag(uint(field(m, 8, "kind")?, "kind")?)?,
909
        })
91015437×
    }
911
}
912
913
/// Reads a stored insert's lines, given the text blob and the line count
914
/// the insert claims; [`text_lines`] reads and checks a blob's content.
915
/// A resolver may also return no lines, leaving a placeholder for a reader
916
/// that fills it in later (history-only states, spec §11).
917
pub type Resolver<'a> = dyn FnMut(&ObjectRef, u32, TextForm) -> Result<Lines, ObjectError> + 'a;
918
919
/// Receives the stored texts of a change being encoded, a batch at a
920
/// time; returns false to stop making more.
921
type TextSink<'a> = dyn FnMut(Vec<StoredText>) -> bool + 'a;
922
923
/// Where a history-only load finds an insert's lines when it builds that
924
/// file's graph (spec §11): it keeps no line until then.
925
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
926
pub enum TextRef {
927
    /// A stored insert: its text blob, line count, and the blob's form.
928
    Blob(ObjectRef, u32, TextForm),
929
    /// An inline insert: the byte range of its lines' array in the
930
    /// encoding of `change`.
931
    Inline {
932
        change: ChangeHash,
933
        start: u32,
934
        end: u32,
935
    },
936
}
937
938
/// The lines of an inline insert from its array's bytes (see
939
/// [`TextRef::Inline`]).
94030939×
pub fn inline_lines(array: &[u8]) -> Result<Lines, ObjectError> {
94130939×
    let v = cbor::decode(array)?;
94230939×
    let lines = array_lines(&v)?;
94330939×
    if lines.is_empty() {
9440×
        return schema("insert with no lines");
94530939×
    }
94630939×
    Ok(lines)
94730939×
}
948
949
/// The lines of a CBOR array of byte strings, copied once into one buffer.
95034664×
fn array_lines(v: &Value) -> Result<Lines, ObjectError> {
95134664×
    Ok(array(v, "lines")?
95234664×
        .iter()
95356799×
        .map(|l| bytes(l, "line"))
95434664×
        .collect::<Result<Vec<&[u8]>, _>>()?
95534664×
        .into_iter()
95634664×
        .collect())
95734664×
}
958
959
impl Change {
960
    /// Decode a change for a history-only state (spec §11): every insert is
961
    /// left without its lines (an empty placeholder), and the result says
962
    /// where each one's lines are, in order. The inline lines are stepped
963
    /// over, not decoded: for a change that adds a whole tree, most of its
964
    /// bytes. `me` is the change's hash.
9657558×
    pub fn decode_skeleton(
9667558×
        bytes: &[u8],
9677558×
        me: ChangeHash,
9687558×
    ) -> Result<(Change, Vec<TextRef>), ObjectError> {
9697558×
        let mut c = cbor::Cursor::new(bytes);
9707558×
        let (major, n) = c.head()?;
9717558×
        if major != 5 {
9720×
            return schema("change: expected map");
9737558×
        }
9747558×
        let mut fields = Map::new();
9757558×
        let mut edits = Vec::new();
9767558×
        let mut texts = Vec::new();
9777558×
        let mut version = None;
9787558×
        let mut last: Option<u64> = None;
9797558×
        for _ in 0..n {
98075578×
            let k = map_key(&mut c, &mut last)?;
98175578×
            if k == 7 {
9827558×
                let Some(v) = version else {
9830×
                    return schema("change: version must come first");
984
                };
9857558×
                let (am, an) = c.head()?;
9867558×
                if am != 4 {
9870×
                    return schema("edits: expected array");
9887558×
                }
9897558×
                for _ in 0..an {
99047595×
                    edits.push(edit_skeleton(&mut c, v, me, &mut texts)?);
991
                }
9927557×
                fields.insert(7, Value::Array(Vec::new()));
993
            } else {
99468020×
                let val = c.value()?;
99568020×
                if k == 0 {
9967558×
                    version = Some(uint(&val, "version")?);
99760462×
                }
99868020×
                fields.insert(k, val);
999
            }
1000
        }
10017557×
        if !c.at_end() {
10020×
            return Err(ObjectError::Cbor(cbor::CborError::TrailingBytes));
10037557×
        }
10047557×
        let mut change = Change::from_value(&Value::Map(fields))?;
10057557×
        change.edits = edits;
10067557×
        Ok((change, texts))
10077558×
    }
1008
}
1009
1010
impl Change {
1011
    /// A change's metadata alone: its tree operations and edits are
1012
    /// stepped over, not decoded. For log, signature checks and walks of
1013
    /// the dependency graph, which read nothing else.
10142747×
    pub fn decode_meta(bytes: &[u8]) -> Result<crate::state::ChangeMeta, ObjectError> {
10152747×
        let mut c = cbor::Cursor::new(bytes);
10162747×
        let (major, n) = c.head()?;
10172747×
        if major != 5 {
10180×
            return schema("change: expected map");
10192747×
        }
10202747×
        let mut fields = Map::new();
10212747×
        let mut last: Option<u64> = None;
10222747×
        for _ in 0..n {
102327470×
            let k = map_key(&mut c, &mut last)?;
102427470×
            if k == 6 || k == 7 {
10255494×
                c.skip()?;
10265494×
                fields.insert(k, Value::Array(Vec::new()));
1027
            } else {
102821976×
                fields.insert(k, c.value()?);
1029
            }
1030
        }
10312747×
        if !c.at_end() {
10320×
            return Err(ObjectError::Cbor(cbor::CborError::TrailingBytes));
10332747×
        }
10342747×
        Ok(crate::state::ChangeMeta::of(&Change::from_value(
10352747×
            &Value::Map(fields),
10360×
        )?))
10372747×
    }
1038
}
1039
1040
/// A canonical map key: an unsigned integer above the previous one.
1041336703×
fn map_key(c: &mut cbor::Cursor, last: &mut Option<u64>) -> Result<u64, ObjectError> {
1042336703×
    let (km, k) = c.head()?;
1043336703×
    if km != 0 || last.is_some_and(|l| k <= l) {
10440×
        return Err(ObjectError::Cbor(cbor::CborError::BadMapKey));
1045336703×
    }
1046336703×
    *last = Some(k);
1047336703×
    Ok(k)
1048336703×
}
1049
1050
/// One edit of [`Change::decode_skeleton`]: an insert's lines are left out.
105147595×
fn edit_skeleton(
105247595×
    c: &mut cbor::Cursor,
105347595×
    version: u64,
105447595×
    me: ChangeHash,
105547595×
    texts: &mut Vec<TextRef>,
105647595×
) -> Result<Edit, ObjectError> {
105747595×
    let (major, n) = c.head()?;
105847595×
    if major != 5 {
10590×
        return schema("edit: expected map");
106047595×
    }
106147595×
    let mut fields = Map::new();
106247595×
    let mut inline: Option<(usize, usize, u64)> = None;
106347595×
    let mut last: Option<u64> = None;
106447595×
    for _ in 0..n {
1065233655×
        let k = map_key(c, &mut last)?;
1066233655×
        if k == 4 {
106744954×
            let start = c.pos();
106844954×
            let (am, count) = c.head()?;
106944954×
            if am != 4 {
10700×
                return schema("lines: expected array");
107144954×
            }
107244954×
            for _ in 0..count {
107360228×
                c.skip()?;
1074
            }
107544954×
            inline = Some((start, c.pos(), count));
107644954×
            continue;
1077188701×
        }
1078188701×
        fields.insert(k, c.value()?);
1079
    }
108047595×
    let Some((start, end, count)) = inline else {
10812641×
        return Edit::from_value(&Value::Map(fields), version, &mut |text, count, form| {
1082120×
            texts.push(TextRef::Blob(*text, count, form));
1083120×
            Ok(Lines::default())
1084120×
        });
1085
    };
108644954×
    if uint(field(&fields, 0, "edit tag")?, "edit tag")? != 0 || fields.contains_key(&5) {
10870×
        return schema("only an insert has inline lines, and not with a text blob");
108844954×
    }
108944954×
    if count == 0 {
10900×
        return schema("insert with no lines");
109144954×
    }
109244954×
    if version >= 2 && end - start >= TEXT_BLOB_MIN {
10931×
        return schema("an insert this large is stored as a text blob in a version 2 change");
109444953×
    }
109544953×
    let (Ok(start), Ok(end)) = (u32::try_from(start), u32::try_from(end)) else {
10960×
        return schema("change too large");
1097
    };
109844953×
    texts.push(TextRef::Inline {
109944953×
        change: me,
110044953×
        start,
110144953×
        end,
110244953×
    });
1103
    Ok(Edit::Insert {
110444953×
        node: node_id(field(&fields, 1, "edit.node")?, "edit.node")?,
110544953×
        after: AtomRef::from_value(field(&fields, 2, "after")?, "after")?,
110644953×
        before: AtomRef::from_value(field(&fields, 3, "before")?, "before")?,
110744953×
        lines: Lines::default(),
1108
    })
110947595×
}
1110
1111
/// A large insert's lines as stored (spec §6.1): the blob and its content,
1112
/// the canonical CBOR array of the lines' byte strings.
1113
#[derive(Debug, Clone, PartialEq, Eq)]
1114
pub struct StoredText {
1115
    pub blob: Blob,
1116
    pub content: Vec<u8>,
1117
    pub form: TextForm,
1118
}
1119
1120
/// The form a change of `version` stores these lines in.
112170×
fn text_form(version: u64, lines: &Lines) -> TextForm {
112269×
    match version {
112370×
        ..=2 => TextForm::Cbor,
112469×
        _ if lines.is_split_form() => TextForm::Raw,
11251×
        _ => TextForm::CborFallback,
1126
    }
112770×
}
1128
1129
/// The lines a text blob's `content` holds, checked against the rules for
1130
/// one: canonical, as many as the insert claims, and not short enough to
1131
/// have been inline.
1132186×
pub fn text_lines(content: &[u8], count: u32, form: TextForm) -> Result<Lines, ObjectError> {
1133186×
    let lines = match form {
1134180×
        TextForm::Raw => Lines::split(content),
11356×
        TextForm::Cbor | TextForm::CborFallback => array_lines(&cbor::decode(content)?)?,
1136
    };
1137
    // One encoding per change: the size rule and the form are both fixed
1138
    // by the lines.
1139186×
    if cbor::byte_strings_len(&lines) < TEXT_BLOB_MIN {
11402×
        return schema(format!(
1141
            "a text blob of {} bytes is short enough to be inline",
11422×
            content.len()
1143
        ));
1144184×
    }
1145184×
    if form == TextForm::CborFallback && lines.is_split_form() {
11461×
        return schema("these lines are stored as their bytes in a version 3 change");
1147183×
    }
1148183×
    if lines.len() != count as usize {
11492×
        return schema(format!(
1150
            "a text blob holds {} lines, the insert says {count}",
11512×
            lines.len()
1152
        ));
1153181×
    }
1154181×
    Ok(lines)
1155186×
}
1156
1157
// ---------------------------------------------------------------- blob
1158
1159
/// File content as an ordered list of chunks (spec §13.2).
1160
#[derive(Debug, Clone, PartialEq, Eq)]
1161
pub struct Blob {
1162
    pub length: u64,
1163
    pub chunks: Vec<ObjectRef>,
1164
}
1165
1166
impl Blob {
1167
    /// The blob for `content`: its chunks as content-defined chunking cuts
1168
    /// them (spec §13.2).
1169459×
    pub fn of(content: &[u8]) -> Blob {
1170
        Blob {
1171459×
            length: content.len() as u64,
1172459×
            chunks: crate::chunk::chunks(content)
1173459×
                .into_iter()
1174564×
                .map(|c| hash_object(ObjectType::Chunk, c))
1175459×
                .collect(),
1176
        }
1177459×
    }
1178
1179581×
    pub fn encode(&self) -> Vec<u8> {
1180581×
        cbor::encode(&Value::map([
1181581×
            (0, Value::Uint(FORMAT_VERSION)),
1182581×
            (1, Value::Uint(self.length)),
1183
            (
1184
                2,
1185
                Value::Array(
1186581×
                    self.chunks
1187581×
                        .iter()
1188785×
                        .map(|c| Value::Bytes(c.0.to_vec()))
1189581×
                        .collect(),
1190
                ),
1191
            ),
1192
        ]))
1193581×
    }
1194376×
    pub fn hash(&self) -> ObjectRef {
1195376×
        hash_object(ObjectType::Blob, &self.encode())
1196376×
    }
1197463×
    pub fn decode(bytes: &[u8]) -> Result<Blob, ObjectError> {
1198463×
        let v = cbor::decode(bytes)?;
1199463×
        let m = map(&v, "blob")?;
1200463×
        check_version(m)?;
1201
        Ok(Blob {
1202463×
            length: uint(field(m, 1, "length")?, "length")?,
1203463×
            chunks: array(field(m, 2, "chunks")?, "chunks")?
1204463×
                .iter()
1205692×
                .map(|c| oref(c, "chunk"))
1206463×
                .collect::<Result<Vec<_>, _>>()?,
1207
        })
1208463×
    }
1209
}
1210
1211
// ---------------------------------------------------------------- checkpoint
1212
1213
/// A materialized state (spec §11): the heads it stands for, how many changes
1214
/// it holds, and a blob with the serialized graphs (`State::checkpoint_payload`).
1215
#[derive(Debug, Clone, PartialEq, Eq)]
1216
pub struct Checkpoint {
1217
    pub heads: Vec<ChangeHash>,
1218
    pub count: u64,
1219
    pub payload: ObjectRef,
1220
}
1221
1222
impl Checkpoint {
122312×
    pub fn encode(&self) -> Vec<u8> {
122412×
        cbor::encode(&Value::map([
122512×
            (0, Value::Uint(FORMAT_VERSION)),
1226
            (
1227
                1,
1228
                Value::Array(
122912×
                    self.heads
123012×
                        .iter()
123113×
                        .map(|h| Value::Bytes(h.0.to_vec()))
123212×
                        .collect(),
1233
                ),
1234
            ),
123512×
            (2, Value::Uint(self.count)),
123612×
            (3, Value::Bytes(self.payload.0.to_vec())),
1237
        ]))
123812×
    }
12390×
    pub fn hash(&self) -> ObjectRef {
12400×
        hash_object(ObjectType::Checkpoint, &self.encode())
12410×
    }
124289×
    pub fn decode(bytes: &[u8]) -> Result<Checkpoint, ObjectError> {
124389×
        let v = cbor::decode(bytes)?;
124489×
        let m = map(&v, "checkpoint")?;
124589×
        check_version(m)?;
1246
        Ok(Checkpoint {
124789×
            heads: array(field(m, 1, "heads")?, "heads")?
124889×
                .iter()
124991×
                .map(|h| oref(h, "head"))
125089×
                .collect::<Result<Vec<_>, _>>()?,
125189×
            count: uint(field(m, 2, "count")?, "count")?,
125289×
            payload: oref(field(m, 3, "payload")?, "payload")?,
1253
        })
125489×
    }
1255
}
1256
1257
// ---------------------------------------------------------------- state
1258
1259
/// A state named by its heads (spec §10.1): what a bookmark or tag points at.
1260
#[derive(Debug, Clone, PartialEq, Eq, Default)]
1261
pub struct StateObject {
1262
    pub heads: Vec<ChangeHash>,
1263
}
1264
1265
impl StateObject {
12663069×
    pub fn new(mut heads: Vec<ChangeHash>) -> StateObject {
12673069×
        heads.sort();
12683069×
        heads.dedup();
12693069×
        StateObject { heads }
12703069×
    }
12713068×
    pub fn encode(&self) -> Vec<u8> {
12723068×
        debug_assert!(self.heads.windows(2).all(|w| w[0] < w[1]));
12733068×
        cbor::encode(&Value::map([
12743068×
            (0, Value::Uint(FORMAT_VERSION)),
1275
            (
1276
                1,
1277
                Value::Array(
12783068×
                    self.heads
12793068×
                        .iter()
12803736×
                        .map(|h| Value::Bytes(h.0.to_vec()))
12813068×
                        .collect(),
1282
                ),
1283
            ),
1284
        ]))
12853068×
    }
12862×
    pub fn hash(&self) -> ObjectRef {
12872×
        hash_object(ObjectType::State, &self.encode())
12882×
    }
12895176×
    pub fn decode(bytes: &[u8]) -> Result<StateObject, ObjectError> {
12905176×
        let v = cbor::decode(bytes)?;
12915176×
        let m = map(&v, "state")?;
12925176×
        check_version(m)?;
12935176×
        let heads = array(field(m, 1, "heads")?, "heads")?
12945176×
            .iter()
12958298×
            .map(|h| oref(h, "head"))
12965176×
            .collect::<Result<Vec<_>, _>>()?;
12975176×
        if !heads.windows(2).all(|w| w[0] < w[1]) {
12980×
            return schema("state heads must be sorted and unique");
12995176×
        }
13005176×
        Ok(StateObject { heads })
13015176×
    }
1302
}
1303
1304
#[cfg(test)]
1305
pub(crate) mod tests {
1306
    use super::*;
1307
130816×
    pub(crate) fn sample_change() -> Change {
130916×
        let n = NodeId([7; 16]);
131016×
        let dep = ObjectRef([1; 32]);
131116×
        let mut c = Change {
131216×
            version: crate::objects::CHANGE_VERSION,
131316×
            change_id: ChangeId([9; 16]),
131416×
            deps: vec![ObjectRef([2; 32]), dep],
131516×
            author: ObjectRef([3; 32]),
131616×
            hlc: Hlc {
131716×
                wall_ms: 1_700_000_000_000,
131816×
                logical: 4,
131916×
            },
132016×
            message: "Add greeting".into(),
132116×
            tree_ops: vec![
132216×
                TreeOp::AddNode {
132316×
                    node: n,
132416×
                    kind: NodeKind::File,
132516×
                    mode: Mode::TEXT,
132616×
                    parent: NodeId::ROOT,
132716×
                    name: "hello.txt".into(),
132816×
                },
132916×
                TreeOp::SetMode {
133016×
                    node: n,
133116×
                    old: OpRef {
133216×
                        change: ObjectRef::ZERO,
133316×
                        index: 0,
133416×
                    },
133516×
                    mode: Mode {
133616×
                        exec: true,
133716×
                        opaque: false,
133816×
                    },
133916×
                },
134016×
            ],
134116×
            edits: vec![
134216×
                Edit::Insert {
134316×
                    node: n,
134416×
                    after: AtomRef::Start,
134516×
                    before: AtomRef::End,
134616×
                    lines: vec![b"hello\n".to_vec(), b"world\n".to_vec()].into(),
134716×
                },
134816×
                Edit::Delete {
134916×
                    node: n,
135016×
                    atoms: vec![AtomRange {
135116×
                        change: dep,
135216×
                        from: 0,
135316×
                        to: 2,
135416×
                    }],
135516×
                },
135616×
                Edit::Replace {
135716×
                    node: n,
135816×
                    old: None,
135916×
                    new: Some(ObjectRef([5; 32])),
136016×
                },
136116×
            ],
136216×
            kind: ChangeKind::Normal,
136316×
        };
136416×
        c.normalize();
136516×
        c
136616×
    }
1367
1368
    #[test]
13691×
    fn change_round_trips_and_hash_is_stable() {
13701×
        let c = sample_change();
13711×
        let bytes = c.encode();
13721×
        let d = Change::decode(&bytes).unwrap();
13731×
        assert_eq!(c, d);
13741×
        assert_eq!(c.hash(), d.hash());
13751×
        assert_eq!(d.encode(), bytes);
1376
        // Any semantic difference changes the hash.
13771×
        let mut e = c.clone();
13781×
        e.message.push('!');
13791×
        assert_ne!(e.hash(), c.hash());
13801×
    }
1381
1382
    #[test]
13831×
    fn compact_encoding_is_the_plain_one() {
1384
        // Inline lines written as their encoding give the same bytes, so
1385
        // the same hash, as a value per line.
13861×
        let c = sample_change();
13871×
        assert!(!c.has_stored_text(), "the sample's insert is inline");
13881×
        let plain = cbor::encode(&c.to_value());
13891×
        assert_eq!(c.encode(), plain);
13901×
        assert_eq!(c.encode_parts().0, plain);
13911×
        let streamed: Result<Vec<u8>, ()> = c.encode_streaming(|_| Ok(()));
13921×
        assert_eq!(streamed.unwrap(), plain);
13931×
        assert_eq!(Change::decode(&plain).unwrap(), c);
13941×
    }
1395
1396
    #[test]
13971×
    fn decode_rejects_bad_changes() {
13981×
        let c = sample_change();
13991×
        let mut v = c.to_value();
14001×
        if let Value::Map(m) = &mut v {
14011×
            m.insert(0, Value::Uint(4));
14021×
        }
14031×
        assert!(
14041×
            matches!(Change::from_value(&v), Err(ObjectError::Schema(s)) if s.contains("version"))
1405
        );
1406
14071×
        let mut v = c.to_value();
14081×
        if let Value::Map(m) = &mut v {
14091×
            m.insert(
14101×
                2,
14111×
                Value::Array(vec![Value::Bytes(vec![2; 32]), Value::Bytes(vec![1; 32])]),
14121×
            );
14131×
        }
14141×
        assert!(
14151×
            matches!(Change::from_value(&v), Err(ObjectError::Schema(s)) if s.contains("sorted"))
1416
        );
1417
14181×
        let mut v = c.to_value();
14191×
        if let Value::Map(m) = &mut v {
14201×
            m.insert(9, Value::map([(0, Value::Null)]));
14211×
        }
14221×
        assert!(
14231×
            matches!(Change::from_value(&v), Err(ObjectError::Schema(s)) if s.contains("extra"))
1424
        );
14251×
    }
1426
14276×
    fn big_lines(n: usize) -> Lines {
14286×
        (0..n)
14293000×
            .map(|i| format!("line {i} of a large insert\n").into_bytes())
14306×
            .collect()
14316×
    }
1432
14336×
    fn with_insert(mut c: Change, lines: Lines) -> Change {
14346×
        c.edits[0] = Edit::Insert {
14356×
            node: NodeId([7; 16]),
14366×
            after: AtomRef::Start,
14376×
            before: AtomRef::End,
14386×
            lines,
14396×
        };
14406×
        c
14416×
    }
1442
1443
    #[test]
14441×
    fn large_inserts_are_stored_as_text_blobs() {
14451×
        assert!(
14461×
            !sample_change().has_stored_text(),
1447
            "a small insert stays inline"
1448
        );
14491×
        let lines = big_lines(500);
14501×
        let c = with_insert(sample_change(), lines.clone());
14511×
        assert!(c.has_stored_text());
14521×
        let (bytes, texts) = c.encode_parts();
14531×
        assert_eq!(bytes, c.encode());
14541×
        assert!(bytes.len() < 1024, "{}", bytes.len());
14551×
        assert_eq!(texts.len(), 1);
1456
        // Version 3: the lines' bytes themselves.
14571×
        assert_eq!(texts[0].form, TextForm::Raw);
14581×
        assert_eq!(texts[0].content, lines.bytes());
14591×
        assert_eq!(texts[0].blob, Blob::of(&texts[0].content));
14601×
        assert!(Change::decode(&bytes).is_err(), "reading it needs the text");
14611×
        let d = Change::decode_with(&bytes, &mut |r, n, form| {
14621×
            assert_eq!(*r, texts[0].blob.hash());
14631×
            assert_eq!(form, TextForm::Raw);
14641×
            text_lines(&texts[0].content, n, form)
14651×
        })
14661×
        .unwrap();
14671×
        assert_eq!(d, c);
14681×
        assert_eq!(d.hash(), c.hash());
1469
        // Version 2 held the same lines as a CBOR array, and still reads.
14701×
        let mut v2 = c.clone();
14711×
        v2.version = 2;
14721×
        let (b2, t2) = v2.encode_parts();
14731×
        assert_eq!(t2[0].form, TextForm::Cbor);
14741×
        assert_eq!(t2[0].content, cbor::encode_byte_strings(&lines));
14751×
        let d2 = Change::decode_with(&b2, &mut |_, n, form| text_lines(&t2[0].content, n, form))
14761×
            .unwrap();
14771×
        assert_eq!(d2, v2);
1478
        // Lines the line rule would not split back stay a CBOR array,
1479
        // marked; and a marked array of lines that would is refused.
14801×
        let odd: Lines = (0..500)
1481500×
            .map(|i| format!("no newline {i}").into_bytes())
14821×
            .collect();
14831×
        let c3 = with_insert(sample_change(), odd.clone());
14841×
        let (b3, t3) = c3.encode_parts();
14851×
        assert_eq!(t3[0].form, TextForm::CborFallback);
14861×
        let d3 = Change::decode_with(&b3, &mut |_, n, form| text_lines(&t3[0].content, n, form))
14871×
            .unwrap();
14881×
        assert_eq!(d3, c3);
14891×
        let marked = cbor::encode_byte_strings(&lines);
14901×
        assert!(text_lines(&marked, 500, TextForm::CborFallback).is_err());
14911×
    }
1492
1493
    #[test]
14941×
    fn version_1_changes_keep_their_inline_inserts_and_hashes() {
14951×
        let mut c = with_insert(sample_change(), big_lines(500));
14961×
        c.version = 1;
14971×
        let bytes = c.encode();
14981×
        assert!(bytes.len() > TEXT_BLOB_MIN);
14991×
        let (again, texts) = c.encode_parts();
15001×
        assert!(texts.is_empty());
15011×
        assert_eq!(again, bytes);
15021×
        let d = Change::decode(&bytes).unwrap();
15031×
        assert_eq!(d.version, 1);
15041×
        assert_eq!(d.encode(), bytes);
1505
        // The same inline insert in a version 2 change is not canonical.
15061×
        let mut v = c.to_value();
15071×
        if let Value::Map(m) = &mut v {
15081×
            m.insert(0, Value::Uint(2));
15091×
        }
15101×
        assert!(
15111×
            matches!(Change::from_value(&v), Err(ObjectError::Schema(s)) if s.contains("text blob"))
1512
        );
15131×
    }
1514
1515
    #[test]
15161×
    fn a_skeleton_leaves_every_insert_out_and_says_where_its_lines_are() {
15171×
        let mut c = with_insert(sample_change(), big_lines(500));
15181×
        c.edits.push(Edit::Insert {
15191×
            node: NodeId([8; 16]),
15201×
            after: AtomRef::Start,
15211×
            before: AtomRef::End,
15221×
            lines: vec![b"small\n".to_vec(), b"insert\n".to_vec()].into(),
15231×
        });
15241×
        let (bytes, stored) = c.encode_parts();
15251×
        let me = ObjectRef([4; 32]);
15261×
        let (skel, texts) = Change::decode_skeleton(&bytes, me).unwrap();
15271×
        assert_eq!(texts.len(), 2);
15281×
        let mut filled = skel.clone();
15291×
        let mut next = texts.iter();
15304×
        for e in filled.edits.iter_mut() {
15314×
            if let Edit::Insert { lines, .. } = e {
15322×
                assert!(lines.is_empty(), "no line kept");
15332×
                *lines = match next.next().unwrap() {
15341×
                    TextRef::Blob(r, n, form) => {
15351×
                        assert_eq!(*r, stored[0].blob.hash());
15361×
                        text_lines(&stored[0].content, *n, *form).unwrap()
1537
                    }
15381×
                    TextRef::Inline { change, start, end } => {
15391×
                        assert_eq!(*change, me);
15401×
                        inline_lines(&bytes[*start as usize..*end as usize]).unwrap()
1541
                    }
1542
                };
15432×
            }
1544
        }
15451×
        assert_eq!(filled, c, "filled in, it is the change");
1546
        // A version 1 change's large inline insert is fine; in version 2 it is not.
15471×
        let mut v1 = with_insert(sample_change(), big_lines(500));
15481×
        v1.version = 1;
15491×
        assert!(Change::decode_skeleton(&v1.encode(), me).is_ok());
15501×
        let mut v = v1.to_value();
15511×
        if let Value::Map(m) = &mut v {
15521×
            m.insert(0, Value::Uint(2));
15531×
        }
15541×
        assert!(Change::decode_skeleton(&cbor::encode(&v), me).is_err());
15551×
    }
1556
1557
    #[test]
15581×
    fn metadata_reads_without_the_operations() {
15591×
        let c = with_insert(sample_change(), big_lines(500));
15601×
        let (bytes, _) = c.encode_parts();
15611×
        let m = Change::decode_meta(&bytes).unwrap();
15621×
        assert_eq!(m, crate::state::ChangeMeta::of(&c));
15631×
    }
1564
1565
    #[test]
15661×
    fn text_blobs_are_checked() {
15671×
        let lines = big_lines(500);
15681×
        let content = cbor::encode_byte_strings(&lines);
15691×
        assert_eq!(content.len(), cbor::byte_strings_len(&lines));
15701×
        assert_eq!(
1571
            content,
15721×
            cbor::encode(&Value::Array(
1573500×
                lines.iter().map(|l| Value::Bytes(l.to_vec())).collect()
1574
            ))
1575
        );
15761×
        assert_eq!(text_lines(&content, 500, TextForm::Cbor).unwrap(), lines);
15771×
        assert!(text_lines(&content, 499, TextForm::Cbor).is_err());
15781×
        assert_eq!(
15791×
            text_lines(lines.bytes(), 500, TextForm::Raw).unwrap(),
1580
            lines
1581
        );
15821×
        assert!(text_lines(lines.bytes(), 501, TextForm::Raw).is_err());
15831×
        let small = cbor::encode_byte_strings(&vec![b"x\n".to_vec()].into());
15841×
        assert!(
15851×
            text_lines(&small, 1, TextForm::Cbor).is_err(),
1586
            "short enough to be inline"
1587
        );
15881×
        assert!(
15891×
            text_lines(b"x\n", 1, TextForm::Raw).is_err(),
1590
            "short enough to be inline"
1591
        );
15921×
    }
1593
1594
    #[test]
15951×
    fn names_are_validated() {
15965×
        for bad in ["", ".", "..", "a/b", "a\0b"] {
15975×
            assert!(validate_name(bad).is_err(), "{bad:?}");
1598
        }
15991×
        assert!(validate_name("Foo.c").is_ok());
16001×
        assert!(validate_name("...").is_ok());
16011×
    }
1602
1603
    #[test]
16041×
    fn mode_and_kind_tags() {
16053×
        for m in [
16061×
            Mode::TEXT,
16071×
            Mode::OPAQUE,
16081×
            Mode {
16091×
                exec: true,
16101×
                opaque: true,
16111×
            },
16121×
        ] {
16133×
            assert_eq!(Mode::from_bits(m.bits()).unwrap(), m);
1614
        }
16151×
        assert!(Mode::from_bits(4).is_err());
16164×
        for k in [
16171×
            NodeKind::File,
16181×
            NodeKind::Dir,
16191×
            NodeKind::Symlink,
16201×
            NodeKind::Subrepo,
16211×
        ] {
16224×
            assert_eq!(NodeKind::from_tag(k.tag()).unwrap(), k);
1623
        }
16241×
    }
1625
1626
    #[test]
16271×
    fn self_references_resolve() {
16281×
        let me = ObjectRef([8; 32]);
16291×
        assert_eq!(
16301×
            AtomRef::Atom {
16311×
                change: ObjectRef::ZERO,
16321×
                index: 3
16331×
            }
16341×
            .resolve(me),
16351×
            AtomRef::Atom {
16361×
                change: me,
16371×
                index: 3
16381×
            }
1639
        );
16401×
        assert_eq!(AtomRef::Start.resolve(me), AtomRef::Start);
16411×
        let other = ObjectRef([1; 32]);
16421×
        assert_eq!(
16431×
            OpRef {
16441×
                change: other,
16451×
                index: 1
16461×
            }
16471×
            .resolve(me)
1648
            .change,
1649
            other
1650
        );
16511×
    }
1652
1653
    #[test]
16541×
    fn state_object_round_trip() {
16551×
        let st = StateObject::new(vec![
16561×
            ObjectRef([2; 32]),
16571×
            ObjectRef([1; 32]),
16581×
            ObjectRef([2; 32]),
1659
        ]);
16601×
        assert_eq!(st.heads, vec![ObjectRef([1; 32]), ObjectRef([2; 32])]);
16611×
        assert_eq!(StateObject::decode(&st.encode()).unwrap(), st);
16621×
        assert_eq!(StateObject::new(vec![]).heads, vec![]);
16631×
        assert_ne!(StateObject::new(vec![]).hash(), st.hash());
16641×
    }
1665
1666
    #[test]
16671×
    fn blob_round_trip() {
16681×
        let b = Blob {
16691×
            length: 10,
16701×
            chunks: vec![ObjectRef([1; 32]), ObjectRef([2; 32])],
16711×
        };
16721×
        assert_eq!(Blob::decode(&b.encode()).unwrap(), b);
16731×
    }
1674
}