OXYGENHUB
# 332c1241a11c oxygen / crates / oxy-core / src / objects.rs
47.5 KiB · Rust · last changed Encode a large change once, and store it on every core 1 month ago source blame history raw
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 std::collections::BTreeMap;
14
15
pub const FORMAT_VERSION: u64 = 1;
16
17
/// The change format writers produce (spec §6.1). Version 2 stores each
18
/// large insert's lines as a text blob; readers accept 1 and 2, and a
19
/// change keeps the version it was made in, so its hash never moves.
20
pub const CHANGE_VERSION: u64 = 2;
21
22
/// In a version 2 change, an insert whose lines encode (as a CBOR array of
23
/// byte strings) to at least this many bytes is stored as a text blob
24
/// holding exactly that encoding; a shorter one is inline (spec §6.1).
25
pub const TEXT_BLOB_MIN: usize = 4096;
26
27
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
28
pub enum ObjectError {
29
    #[error("cbor: {0}")]
30
    Cbor(#[from] cbor::CborError),
31
    #[error("schema: {0}")]
32
    Schema(String),
33
}
34
35
pub(crate) fn schema<T>(msg: impl Into<String>) -> Result<T, ObjectError> {
36
    Err(ObjectError::Schema(msg.into()))
37
}
38
39
pub(crate) type Map = BTreeMap<u64, Value>;
40
41
pub(crate) fn field<'a>(m: &'a Map, k: u64, what: &str) -> Result<&'a Value, ObjectError> {
42
    m.get(&k)
43
        .ok_or_else(|| ObjectError::Schema(format!("missing field {k} ({what})")))
44
}
45
pub(crate) fn uint(v: &Value, what: &str) -> Result<u64, ObjectError> {
46
    v.as_uint()
47
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected unsigned integer")))
48
}
49
pub(crate) fn u32_(v: &Value, what: &str) -> Result<u32, ObjectError> {
50
    u32::try_from(uint(v, what)?).map_err(|_| ObjectError::Schema(format!("{what}: exceeds u32")))
51
}
52
pub(crate) fn text<'a>(v: &'a Value, what: &str) -> Result<&'a str, ObjectError> {
53
    v.as_text()
54
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected text")))
55
}
56
pub(crate) fn array<'a>(v: &'a Value, what: &str) -> Result<&'a [Value], ObjectError> {
57
    v.as_array()
58
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected array")))
59
}
60
pub(crate) fn map<'a>(v: &'a Value, what: &str) -> Result<&'a Map, ObjectError> {
61
    v.as_map()
62
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected map")))
63
}
64
pub(crate) fn bytes<'a>(v: &'a Value, what: &str) -> Result<&'a [u8], ObjectError> {
65
    v.as_bytes()
66
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected bytes")))
67
}
68
pub(crate) fn oref(v: &Value, what: &str) -> Result<ObjectRef, ObjectError> {
69
    ObjectRef::from_slice(bytes(v, what)?)
70
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected 32 bytes")))
71
}
72
pub(crate) fn node_id(v: &Value, what: &str) -> Result<NodeId, ObjectError> {
73
    NodeId::from_slice(bytes(v, what)?)
74
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected 16 bytes")))
75
}
76
pub(crate) fn check_version(m: &Map) -> Result<(), ObjectError> {
77
    let v = uint(field(m, 0, "version")?, "version")?;
78
    if v != FORMAT_VERSION {
79
        return schema(format!("unsupported format version {v}"));
80
    }
81
    Ok(())
82
}
83
84
// ---------------------------------------------------------------- Hlc
85
86
/// Hybrid logical clock (spec §6.4).
87
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
88
pub struct Hlc {
89
    pub wall_ms: u64,
90
    pub logical: u32,
91
}
92
93
impl Hlc {
94
    pub fn now() -> Hlc {
95
        let wall_ms = std::time::SystemTime::now()
96
            .duration_since(std::time::UNIX_EPOCH)
97
            .map(|d| d.as_millis() as u64)
98
            .unwrap_or(0);
99
        Hlc {
100
            wall_ms,
101
            logical: 0,
102
        }
103
    }
104
    pub(crate) fn to_value(self) -> Value {
105
        Value::map([
106
            (0, Value::Uint(self.wall_ms)),
107
            (1, Value::Uint(self.logical as u64)),
108
        ])
109
    }
110
    pub(crate) fn from_value(v: &Value) -> Result<Hlc, ObjectError> {
111
        let m = map(v, "hlc")?;
112
        Ok(Hlc {
113
            wall_ms: uint(field(m, 0, "hlc.wall_ms")?, "hlc.wall_ms")?,
114
            logical: u32_(field(m, 1, "hlc.logical")?, "hlc.logical")?,
115
        })
116
    }
117
}
118
119
// ---------------------------------------------------------------- tree
120
121
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
122
pub enum NodeKind {
123
    File,
124
    Dir,
125
    Symlink,
126
    /// A nested repository pinned to a state (spec §7.8); content is a pin.
127
    Subrepo,
128
}
129
130
impl NodeKind {
131
    pub(crate) fn tag(self) -> u64 {
132
        match self {
133
            NodeKind::File => 0,
134
            NodeKind::Dir => 1,
135
            NodeKind::Symlink => 2,
136
            NodeKind::Subrepo => 3,
137
        }
138
    }
139
    pub(crate) fn from_tag(t: u64) -> Result<NodeKind, ObjectError> {
140
        Ok(match t {
141
            0 => NodeKind::File,
142
            1 => NodeKind::Dir,
143
            2 => NodeKind::Symlink,
144
            3 => NodeKind::Subrepo,
145
            _ => return schema(format!("unknown node kind {t}")),
146
        })
147
    }
148
}
149
150
/// Executable bit plus content mode (spec §7.1, §7.5).
151
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PartialOrd, Ord)]
152
pub struct Mode {
153
    pub exec: bool,
154
    pub opaque: bool,
155
}
156
157
impl Mode {
158
    pub const TEXT: Mode = Mode {
159
        exec: false,
160
        opaque: false,
161
    };
162
    pub const OPAQUE: Mode = Mode {
163
        exec: false,
164
        opaque: true,
165
    };
166
    pub(crate) fn bits(self) -> u64 {
167
        (self.exec as u64) | ((self.opaque as u64) << 1)
168
    }
169
    pub(crate) fn from_bits(b: u64) -> Result<Mode, ObjectError> {
170
        if b > 3 {
171
            return schema(format!("unknown mode bits {b}"));
172
        }
173
        Ok(Mode {
174
            exec: b & 1 != 0,
175
            opaque: b & 2 != 0,
176
        })
177
    }
178
}
179
180
/// Reference to a tree operation of some change: the placement or mode atom it
181
/// introduced. `change == ObjectRef::ZERO` means this change.
182
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
183
pub struct OpRef {
184
    pub change: ChangeHash,
185
    pub index: u32,
186
}
187
188
impl OpRef {
189
    fn to_value(self) -> Value {
190
        Value::Array(vec![
191
            Value::Bytes(self.change.0.to_vec()),
192
            Value::Uint(self.index as u64),
193
        ])
194
    }
195
    fn from_value(v: &Value, what: &str) -> Result<OpRef, ObjectError> {
196
        let a = array(v, what)?;
197
        if a.len() != 2 {
198
            return schema(format!("{what}: expected [hash, index]"));
199
        }
200
        Ok(OpRef {
201
            change: oref(&a[0], what)?,
202
            index: u32_(&a[1], what)?,
203
        })
204
    }
205
    /// Replace a self reference with the concrete change hash.
206
    pub fn resolve(self, me: ChangeHash) -> OpRef {
207
        if self.change.is_zero() {
208
            OpRef { change: me, ..self }
209
        } else {
210
            self
211
        }
212
    }
213
}
214
215
#[derive(Debug, Clone, PartialEq, Eq)]
216
pub enum TreeOp {
217
    AddNode {
218
        node: NodeId,
219
        kind: NodeKind,
220
        mode: Mode,
221
        parent: NodeId,
222
        name: String,
223
    },
224
    RemoveNode {
225
        node: NodeId,
226
        placement: OpRef,
227
    },
228
    Move {
229
        node: NodeId,
230
        old: OpRef,
231
        parent: NodeId,
232
        name: String,
233
    },
234
    SetMode {
235
        node: NodeId,
236
        old: OpRef,
237
        mode: Mode,
238
    },
239
}
240
241
/// Names must be valid, non-empty, not `.`/`..`, and free of `/` and NUL (spec §7.1).
242
pub fn validate_name(name: &str) -> Result<(), ObjectError> {
243
    if name.is_empty() || name == "." || name == ".." || name.contains('/') || name.contains('\0') {
244
        return schema(format!("invalid placement name {name:?}"));
245
    }
246
    Ok(())
247
}
248
249
impl TreeOp {
250
    pub fn node(&self) -> NodeId {
251
        match self {
252
            TreeOp::AddNode { node, .. }
253
            | TreeOp::RemoveNode { node, .. }
254
            | TreeOp::Move { node, .. }
255
            | TreeOp::SetMode { node, .. } => *node,
256
        }
257
    }
258
259
    fn to_value(&self) -> Value {
260
        let nid = |n: &NodeId| Value::Bytes(n.0.to_vec());
261
        match self {
262
            TreeOp::AddNode {
263
                node,
264
                kind,
265
                mode,
266
                parent,
267
                name,
268
            } => Value::map([
269
                (0, Value::Uint(0)),
270
                (1, nid(node)),
271
                (2, Value::Uint(kind.tag())),
272
                (3, Value::Uint(mode.bits())),
273
                (4, nid(parent)),
274
                (5, Value::Text(name.clone())),
275
            ]),
276
            TreeOp::RemoveNode { node, placement } => Value::map([
277
                (0, Value::Uint(1)),
278
                (1, nid(node)),
279
                (2, placement.to_value()),
280
            ]),
281
            TreeOp::Move {
282
                node,
283
                old,
284
                parent,
285
                name,
286
            } => Value::map([
287
                (0, Value::Uint(2)),
288
                (1, nid(node)),
289
                (2, old.to_value()),
290
                (4, nid(parent)),
291
                (5, Value::Text(name.clone())),
292
            ]),
293
            TreeOp::SetMode { node, old, mode } => Value::map([
294
                (0, Value::Uint(3)),
295
                (1, nid(node)),
296
                (2, old.to_value()),
297
                (3, Value::Uint(mode.bits())),
298
            ]),
299
        }
300
    }
301
302
    fn from_value(v: &Value) -> Result<TreeOp, ObjectError> {
303
        let m = map(v, "tree_op")?;
304
        let tag = uint(field(m, 0, "tree_op tag")?, "tree_op tag")?;
305
        let node = node_id(field(m, 1, "tree_op.node")?, "tree_op.node")?;
306
        let op = match tag {
307
            0 => {
308
                let name = text(field(m, 5, "name")?, "name")?.to_owned();
309
                validate_name(&name)?;
310
                TreeOp::AddNode {
311
                    node,
312
                    kind: NodeKind::from_tag(uint(field(m, 2, "kind")?, "kind")?)?,
313
                    mode: Mode::from_bits(uint(field(m, 3, "mode")?, "mode")?)?,
314
                    parent: node_id(field(m, 4, "parent")?, "parent")?,
315
                    name,
316
                }
317
            }
318
            1 => TreeOp::RemoveNode {
319
                node,
320
                placement: OpRef::from_value(field(m, 2, "placement")?, "placement")?,
321
            },
322
            2 => {
323
                let name = text(field(m, 5, "name")?, "name")?.to_owned();
324
                validate_name(&name)?;
325
                TreeOp::Move {
326
                    node,
327
                    old: OpRef::from_value(field(m, 2, "old")?, "old")?,
328
                    parent: node_id(field(m, 4, "parent")?, "parent")?,
329
                    name,
330
                }
331
            }
332
            3 => TreeOp::SetMode {
333
                node,
334
                old: OpRef::from_value(field(m, 2, "old")?, "old")?,
335
                mode: Mode::from_bits(uint(field(m, 3, "mode")?, "mode")?)?,
336
            },
337
            _ => return schema(format!("unknown tree op tag {tag}")),
338
        };
339
        if node.is_root() {
340
            return schema("tree op on the root node");
341
        }
342
        Ok(op)
343
    }
344
}
345
346
// ---------------------------------------------------------------- edits
347
348
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
349
pub enum AtomRef {
350
    Start,
351
    End,
352
    Atom { change: ChangeHash, index: u32 },
353
}
354
355
impl AtomRef {
356
    fn to_value(self) -> Value {
357
        match self {
358
            AtomRef::Start => Value::Uint(0),
359
            AtomRef::End => Value::Uint(1),
360
            AtomRef::Atom { change, index } => Value::Array(vec![
361
                Value::Bytes(change.0.to_vec()),
362
                Value::Uint(index as u64),
363
            ]),
364
        }
365
    }
366
    fn from_value(v: &Value, what: &str) -> Result<AtomRef, ObjectError> {
367
        match v {
368
            Value::Uint(0) => Ok(AtomRef::Start),
369
            Value::Uint(1) => Ok(AtomRef::End),
370
            Value::Array(a) if a.len() == 2 => Ok(AtomRef::Atom {
371
                change: oref(&a[0], what)?,
372
                index: u32_(&a[1], what)?,
373
            }),
374
            _ => schema(format!("{what}: expected atom reference")),
375
        }
376
    }
377
    pub fn resolve(self, me: ChangeHash) -> AtomRef {
378
        match self {
379
            AtomRef::Atom { change, index } if change.is_zero() => {
380
                AtomRef::Atom { change: me, index }
381
            }
382
            other => other,
383
        }
384
    }
385
}
386
387
/// Half-open range of atoms introduced by one change.
388
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
389
pub struct AtomRange {
390
    pub change: ChangeHash,
391
    pub from: u32,
392
    pub to: u32,
393
}
394
395
impl AtomRange {
396
    fn to_value(self) -> Value {
397
        Value::Array(vec![
398
            Value::Bytes(self.change.0.to_vec()),
399
            Value::Uint(self.from as u64),
400
            Value::Uint(self.to as u64),
401
        ])
402
    }
403
    fn from_value(v: &Value) -> Result<AtomRange, ObjectError> {
404
        let a = array(v, "atom range")?;
405
        if a.len() != 3 {
406
            return schema("atom range: expected [hash, from, to]");
407
        }
408
        let r = AtomRange {
409
            change: oref(&a[0], "range.change")?,
410
            from: u32_(&a[1], "range.from")?,
411
            to: u32_(&a[2], "range.to")?,
412
        };
413
        if r.from >= r.to {
414
            return schema("atom range: empty or inverted");
415
        }
416
        Ok(r)
417
    }
418
    pub fn resolve(self, me: ChangeHash) -> AtomRange {
419
        if self.change.is_zero() {
420
            AtomRange { change: me, ..self }
421
        } else {
422
            self
423
        }
424
    }
425
}
426
427
#[derive(Debug, Clone, PartialEq, Eq)]
428
pub enum Edit {
429
    Insert {
430
        node: NodeId,
431
        after: AtomRef,
432
        before: AtomRef,
433
        lines: Vec<Vec<u8>>,
434
    },
435
    Delete {
436
        node: NodeId,
437
        atoms: Vec<AtomRange>,
438
    },
439
    Replace {
440
        node: NodeId,
441
        old: Option<ObjectRef>,
442
        new: Option<ObjectRef>,
443
    },
444
}
445
446
impl Edit {
447
    pub fn node(&self) -> NodeId {
448
        match self {
449
            Edit::Insert { node, .. } | Edit::Delete { node, .. } | Edit::Replace { node, .. } => {
450
                *node
451
            }
452
        }
453
    }
454
455
    /// Whether this insert is stored as a text blob in a change of `version`.
456
    fn stored_text(&self, version: u64) -> bool {
457
        matches!(self, Edit::Insert { lines, .. }
458
            if version >= 2 && cbor::byte_strings_len(lines) >= TEXT_BLOB_MIN)
459
    }
460
461
    /// The edit's value; `stored` is the text blob of an insert stored as
462
    /// one (see [`Change::value_with`], which works them out).
463
    fn to_value(&self, stored: Option<ObjectRef>) -> Value {
464
        let nid = |n: &NodeId| Value::Bytes(n.0.to_vec());
465
        let opt = |o: &Option<ObjectRef>| match o {
466
            Some(r) => Value::Bytes(r.0.to_vec()),
467
            None => Value::Null,
468
        };
469
        match (self, stored) {
470
            (
471
                Edit::Insert {
472
                    node,
473
                    after,
474
                    before,
475
                    lines,
476
                },
477
                Some(r),
478
            ) => Value::map([
479
                (0, Value::Uint(0)),
480
                (1, nid(node)),
481
                (2, after.to_value()),
482
                (3, before.to_value()),
483
                (5, Value::Bytes(r.0.to_vec())),
484
                (6, Value::Uint(lines.len() as u64)),
485
            ]),
486
            (
487
                Edit::Insert {
488
                    node,
489
                    after,
490
                    before,
491
                    lines,
492
                },
493
                None,
494
            ) => Value::map([
495
                (0, Value::Uint(0)),
496
                (1, nid(node)),
497
                (2, after.to_value()),
498
                (3, before.to_value()),
499
                (
500
                    4,
501
                    Value::Array(lines.iter().map(|l| Value::Bytes(l.clone())).collect()),
502
                ),
503
            ]),
504
            (Edit::Delete { node, atoms }, _) => Value::map([
505
                (0, Value::Uint(1)),
506
                (1, nid(node)),
507
                (
508
                    2,
509
                    Value::Array(atoms.iter().map(|r| r.to_value()).collect()),
510
                ),
511
            ]),
512
            (Edit::Replace { node, old, new }, _) => Value::map([
513
                (0, Value::Uint(2)),
514
                (1, nid(node)),
515
                (2, opt(old)),
516
                (3, opt(new)),
517
            ]),
518
        }
519
    }
520
521
    fn from_value(v: &Value, version: u64, resolve: &mut Resolver) -> Result<Edit, ObjectError> {
522
        let m = map(v, "edit")?;
523
        let tag = uint(field(m, 0, "edit tag")?, "edit tag")?;
524
        let node = node_id(field(m, 1, "edit.node")?, "edit.node")?;
525
        let opt = |v: &Value, what: &str| -> Result<Option<ObjectRef>, ObjectError> {
526
            if v.is_null() {
527
                Ok(None)
528
            } else {
529
                Ok(Some(oref(v, what)?))
530
            }
531
        };
532
        Ok(match tag {
533
            0 => {
534
                let lines = match (m.get(&4), m.get(&5)) {
535
                    (Some(inline), None) => {
536
                        let lines = array(inline, "lines")?
537
                            .iter()
538
                            .map(|l| bytes(l, "line").map(|b| b.to_vec()))
539
                            .collect::<Result<Vec<_>, _>>()?;
540
                        if version >= 2 && cbor::byte_strings_len(&lines) >= TEXT_BLOB_MIN {
541
                            return schema("an insert this large is stored as a text blob in a version 2 change");
542
                        }
543
                        if lines.is_empty() {
544
                            return schema("insert with no lines");
545
                        }
546
                        lines
547
                    }
548
                    (None, Some(text)) if version >= 2 => {
549
                        let text = oref(text, "insert text")?;
550
                        let count = u32_(field(m, 6, "insert line count")?, "insert line count")?;
551
                        if count == 0 {
552
                            return schema("insert with no lines");
553
                        }
554
                        // The resolver checks the count (`text_lines`).
555
                        resolve(&text, count)?
556
                    }
557
                    _ => {
558
                        return schema(
559
                            "an insert has either its lines or, in a version 2 change, a text blob",
560
                        )
561
                    }
562
                };
563
                Edit::Insert {
564
                    node,
565
                    after: AtomRef::from_value(field(m, 2, "after")?, "after")?,
566
                    before: AtomRef::from_value(field(m, 3, "before")?, "before")?,
567
                    lines,
568
                }
569
            }
570
            1 => {
571
                let atoms = array(field(m, 2, "atoms")?, "atoms")?
572
                    .iter()
573
                    .map(AtomRange::from_value)
574
                    .collect::<Result<Vec<_>, _>>()?;
575
                if atoms.is_empty() {
576
                    return schema("delete with no atoms");
577
                }
578
                Edit::Delete { node, atoms }
579
            }
580
            2 => Edit::Replace {
581
                node,
582
                old: opt(field(m, 2, "old")?, "old")?,
583
                new: opt(field(m, 3, "new")?, "new")?,
584
            },
585
            _ => return schema(format!("unknown edit tag {tag}")),
586
        })
587
    }
588
}
589
590
// ---------------------------------------------------------------- change
591
592
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
593
pub enum ChangeKind {
594
    Normal,
595
    Resolution,
596
    WorkingCopy,
597
}
598
599
impl ChangeKind {
600
    pub(crate) fn tag(self) -> u64 {
601
        match self {
602
            ChangeKind::Normal => 0,
603
            ChangeKind::Resolution => 1,
604
            ChangeKind::WorkingCopy => 2,
605
        }
606
    }
607
    pub(crate) fn from_tag(t: u64) -> Result<ChangeKind, ObjectError> {
608
        Ok(match t {
609
            0 => ChangeKind::Normal,
610
            1 => ChangeKind::Resolution,
611
            2 => ChangeKind::WorkingCopy,
612
            _ => return schema(format!("unknown change kind {t}")),
613
        })
614
    }
615
}
616
617
/// A change (spec §6.1). `deps` is kept sorted and unique by `normalize`.
618
#[derive(Debug, Clone, PartialEq, Eq)]
619
pub struct Change {
620
    /// The format this change is encoded in: [`CHANGE_VERSION`] for a new
621
    /// one, whatever it was made in for one read back.
622
    pub version: u64,
623
    pub change_id: ChangeId,
624
    pub deps: Vec<ChangeHash>,
625
    pub author: KeyId,
626
    pub hlc: Hlc,
627
    pub message: String,
628
    pub tree_ops: Vec<TreeOp>,
629
    pub edits: Vec<Edit>,
630
    pub kind: ChangeKind,
631
}
632
633
impl Change {
634
    pub fn normalize(&mut self) {
635
        self.deps.sort();
636
        self.deps.dedup();
637
    }
638
639
    pub fn to_value(&self) -> Value {
640
        self.value_with(&mut None)
641
    }
642
643
    /// The text blob of each edit stored as one, `None` for the others;
644
    /// the stored texts go to `texts`, in order, when it is given. Worked
645
    /// out on every core, a bounded batch at a time: chunking and hashing
646
    /// a whole tree's text is most of encoding a change that adds it.
647
    fn stored_texts(&self, texts: &mut Option<&mut Vec<StoredText>>) -> Vec<Option<ObjectRef>> {
648
        use rayon::prelude::*;
649
        let mut refs = vec![None; self.edits.len()];
650
        let stored: Vec<usize> = (0..self.edits.len())
651
            .filter(|i| self.edits[*i].stored_text(self.version))
652
            .collect();
653
        for batch in stored.chunks(256) {
654
            let made: Vec<StoredText> = batch
655
                .par_iter()
656
                .map(|i| {
657
                    let Edit::Insert { lines, .. } = &self.edits[*i] else {
658
                        unreachable!("only inserts are stored as text");
659
                    };
660
                    let content = cbor::encode_byte_strings(lines);
661
                    StoredText {
662
                        blob: Blob::of(&content),
663
                        content,
664
                    }
665
                })
666
                .collect();
667
            for (i, t) in batch.iter().zip(made) {
668
                refs[*i] = Some(t.blob.hash());
669
                if let Some(sink) = texts {
670
                    sink.push(t);
671
                }
672
            }
673
        }
674
        refs
675
    }
676
677
    fn value_with(&self, texts: &mut Option<&mut Vec<StoredText>>) -> Value {
678
        Value::map([
679
            (0, Value::Uint(self.version)),
680
            (1, Value::Bytes(self.change_id.0.to_vec())),
681
            (
682
                2,
683
                Value::Array(
684
                    self.deps
685
                        .iter()
686
                        .map(|d| Value::Bytes(d.0.to_vec()))
687
                        .collect(),
688
                ),
689
            ),
690
            (3, Value::Bytes(self.author.0.to_vec())),
691
            (4, self.hlc.to_value()),
692
            (5, Value::Text(self.message.clone())),
693
            (
694
                6,
695
                Value::Array(self.tree_ops.iter().map(|t| t.to_value()).collect()),
696
            ),
697
            (
698
                7,
699
                Value::Array(
700
                    self.edits
701
                        .iter()
702
                        .zip(self.stored_texts(texts))
703
                        .map(|(e, stored)| e.to_value(stored))
704
                        .collect(),
705
                ),
706
            ),
707
            (8, Value::Uint(self.kind.tag())),
708
            (9, Value::Map(BTreeMap::new())),
709
        ])
710
    }
711
712
    pub fn encode(&self) -> Vec<u8> {
713
        debug_assert!(
714
            self.deps.windows(2).all(|w| w[0] < w[1]),
715
            "deps must be normalized"
716
        );
717
        cbor::encode(&self.to_value())
718
    }
719
720
    /// The encoding and the text blobs its large inserts are stored as,
721
    /// which must be stored with it.
722
    pub fn encode_parts(&self) -> (Vec<u8>, Vec<StoredText>) {
723
        debug_assert!(
724
            self.deps.windows(2).all(|w| w[0] < w[1]),
725
            "deps must be normalized"
726
        );
727
        let mut texts = Vec::new();
728
        let bytes = cbor::encode(&self.value_with(&mut Some(&mut texts)));
729
        (bytes, texts)
730
    }
731
732
    /// Whether any insert is stored as a text blob.
733
    pub fn has_stored_text(&self) -> bool {
734
        self.edits.iter().any(|e| e.stored_text(self.version))
735
    }
736
737
    pub fn hash(&self) -> ChangeHash {
738
        hash_object(ObjectType::Change, &self.encode())
739
    }
740
741
    /// Decode a change that stores no text blob; one that does needs
742
    /// [`Change::decode_with`] and something to read them from.
743
    pub fn decode(bytes: &[u8]) -> Result<Change, ObjectError> {
744
        Self::decode_with(bytes, &mut |r, _| {
745
            schema(format!(
746
                "text blob {} needs a store to read it from",
747
                r.short(12)
748
            ))
749
        })
750
    }
751
752
    /// Decode a change, reading each stored insert's lines with `resolve`
753
    /// (given the text blob and the line count the insert claims).
754
    pub fn decode_with(bytes: &[u8], resolve: &mut Resolver) -> Result<Change, ObjectError> {
755
        let v = cbor::decode(bytes)?;
756
        Self::from_value_with(&v, resolve)
757
    }
758
759
    pub fn from_value(v: &Value) -> Result<Change, ObjectError> {
760
        Self::from_value_with(v, &mut |r, _| {
761
            schema(format!(
762
                "text blob {} needs a store to read it from",
763
                r.short(12)
764
            ))
765
        })
766
    }
767
768
    pub(crate) fn from_value_with(
769
        v: &Value,
770
        resolve: &mut Resolver,
771
    ) -> Result<Change, ObjectError> {
772
        let m = map(v, "change")?;
773
        let version = uint(field(m, 0, "version")?, "version")?;
774
        if !(1..=CHANGE_VERSION).contains(&version) {
775
            return schema(format!("unsupported change format version {version}"));
776
        }
777
        let change_id = ChangeId::from_slice(bytes(field(m, 1, "change_id")?, "change_id")?)
778
            .ok_or_else(|| ObjectError::Schema("change_id: expected 16 bytes".into()))?;
779
        let deps = array(field(m, 2, "deps")?, "deps")?
780
            .iter()
781
            .map(|d| oref(d, "dep"))
782
            .collect::<Result<Vec<_>, _>>()?;
783
        if !deps.windows(2).all(|w| w[0] < w[1]) {
784
            return schema("deps must be sorted and unique");
785
        }
786
        if deps.iter().any(|d| d.is_zero()) {
787
            return schema("deps may not contain the self reference");
788
        }
789
        let extra = map(field(m, 9, "extra")?, "extra")?;
790
        if !extra.is_empty() {
791
            return schema("extra must be empty in format version 1");
792
        }
793
        Ok(Change {
794
            version,
795
            change_id,
796
            deps,
797
            author: oref(field(m, 3, "author")?, "author")?,
798
            hlc: Hlc::from_value(field(m, 4, "hlc")?)?,
799
            message: text(field(m, 5, "message")?, "message")?.to_owned(),
800
            tree_ops: array(field(m, 6, "tree_ops")?, "tree_ops")?
801
                .iter()
802
                .map(TreeOp::from_value)
803
                .collect::<Result<Vec<_>, _>>()?,
804
            edits: array(field(m, 7, "edits")?, "edits")?
805
                .iter()
806
                .map(|e| Edit::from_value(e, version, resolve))
807
                .collect::<Result<Vec<_>, _>>()?,
808
            kind: ChangeKind::from_tag(uint(field(m, 8, "kind")?, "kind")?)?,
809
        })
810
    }
811
}
812
813
/// Reads a stored insert's lines, given the text blob and the line count
814
/// the insert claims; [`text_lines`] reads and checks a blob's content.
815
/// A resolver may also return no lines, leaving a placeholder for a reader
816
/// that fills it in later (history-only states, spec §11).
817
pub type Resolver<'a> = dyn FnMut(&ObjectRef, u32) -> Result<Vec<Vec<u8>>, ObjectError> + 'a;
818
819
/// Where a history-only load finds an insert's lines when it builds that
820
/// file's graph (spec §11): it keeps no line until then.
821
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
822
pub enum TextRef {
823
    /// A stored insert: its text blob and line count.
824
    Blob(ObjectRef, u32),
825
    /// An inline insert: the byte range of its lines' array in the
826
    /// encoding of `change`.
827
    Inline {
828
        change: ChangeHash,
829
        start: u32,
830
        end: u32,
831
    },
832
}
833
834
/// The lines of an inline insert from its array's bytes (see
835
/// [`TextRef::Inline`]).
836
pub fn inline_lines(array: &[u8]) -> Result<Vec<Vec<u8>>, ObjectError> {
837
    let v = cbor::decode(array)?;
838
    let lines = array_lines(&v)?;
839
    if lines.is_empty() {
840
        return schema("insert with no lines");
841
    }
842
    Ok(lines)
843
}
844
845
fn array_lines(v: &Value) -> Result<Vec<Vec<u8>>, ObjectError> {
846
    array(v, "lines")?
847
        .iter()
848
        .map(|l| bytes(l, "line").map(|b| b.to_vec()))
849
        .collect()
850
}
851
852
impl Change {
853
    /// Decode a change for a history-only state (spec §11): every insert is
854
    /// left without its lines (an empty placeholder), and the result says
855
    /// where each one's lines are, in order. The inline lines are stepped
856
    /// over, not decoded: for a change that adds a whole tree, most of its
857
    /// bytes. `me` is the change's hash.
858
    pub fn decode_skeleton(
859
        bytes: &[u8],
860
        me: ChangeHash,
861
    ) -> Result<(Change, Vec<TextRef>), ObjectError> {
862
        let mut c = cbor::Cursor::new(bytes);
863
        let (major, n) = c.head()?;
864
        if major != 5 {
865
            return schema("change: expected map");
866
        }
867
        let mut fields = Map::new();
868
        let mut edits = Vec::new();
869
        let mut texts = Vec::new();
870
        let mut version = None;
871
        let mut last: Option<u64> = None;
872
        for _ in 0..n {
873
            let k = map_key(&mut c, &mut last)?;
874
            if k == 7 {
875
                let Some(v) = version else {
876
                    return schema("change: version must come first");
877
                };
878
                let (am, an) = c.head()?;
879
                if am != 4 {
880
                    return schema("edits: expected array");
881
                }
882
                for _ in 0..an {
883
                    edits.push(edit_skeleton(&mut c, v, me, &mut texts)?);
884
                }
885
                fields.insert(7, Value::Array(Vec::new()));
886
            } else {
887
                let val = c.value()?;
888
                if k == 0 {
889
                    version = Some(uint(&val, "version")?);
890
                }
891
                fields.insert(k, val);
892
            }
893
        }
894
        if !c.at_end() {
895
            return Err(ObjectError::Cbor(cbor::CborError::TrailingBytes));
896
        }
897
        let mut change = Change::from_value(&Value::Map(fields))?;
898
        change.edits = edits;
899
        Ok((change, texts))
900
    }
901
}
902
903
/// A canonical map key: an unsigned integer above the previous one.
904
fn map_key(c: &mut cbor::Cursor, last: &mut Option<u64>) -> Result<u64, ObjectError> {
905
    let (km, k) = c.head()?;
906
    if km != 0 || last.is_some_and(|l| k <= l) {
907
        return Err(ObjectError::Cbor(cbor::CborError::BadMapKey));
908
    }
909
    *last = Some(k);
910
    Ok(k)
911
}
912
913
/// One edit of [`Change::decode_skeleton`]: an insert's lines are left out.
914
fn edit_skeleton(
915
    c: &mut cbor::Cursor,
916
    version: u64,
917
    me: ChangeHash,
918
    texts: &mut Vec<TextRef>,
919
) -> Result<Edit, ObjectError> {
920
    let (major, n) = c.head()?;
921
    if major != 5 {
922
        return schema("edit: expected map");
923
    }
924
    let mut fields = Map::new();
925
    let mut inline: Option<(usize, usize, u64)> = None;
926
    let mut last: Option<u64> = None;
927
    for _ in 0..n {
928
        let k = map_key(c, &mut last)?;
929
        if k == 4 {
930
            let start = c.pos();
931
            let (am, count) = c.head()?;
932
            if am != 4 {
933
                return schema("lines: expected array");
934
            }
935
            for _ in 0..count {
936
                c.skip()?;
937
            }
938
            inline = Some((start, c.pos(), count));
939
            continue;
940
        }
941
        fields.insert(k, c.value()?);
942
    }
943
    let Some((start, end, count)) = inline else {
944
        return Edit::from_value(&Value::Map(fields), version, &mut |text, count| {
945
            texts.push(TextRef::Blob(*text, count));
946
            Ok(Vec::new())
947
        });
948
    };
949
    if uint(field(&fields, 0, "edit tag")?, "edit tag")? != 0 || fields.contains_key(&5) {
950
        return schema("only an insert has inline lines, and not with a text blob");
951
    }
952
    if count == 0 {
953
        return schema("insert with no lines");
954
    }
955
    if version >= 2 && end - start >= TEXT_BLOB_MIN {
956
        return schema("an insert this large is stored as a text blob in a version 2 change");
957
    }
958
    let (Ok(start), Ok(end)) = (u32::try_from(start), u32::try_from(end)) else {
959
        return schema("change too large");
960
    };
961
    texts.push(TextRef::Inline {
962
        change: me,
963
        start,
964
        end,
965
    });
966
    Ok(Edit::Insert {
967
        node: node_id(field(&fields, 1, "edit.node")?, "edit.node")?,
968
        after: AtomRef::from_value(field(&fields, 2, "after")?, "after")?,
969
        before: AtomRef::from_value(field(&fields, 3, "before")?, "before")?,
970
        lines: Vec::new(),
971
    })
972
}
973
974
/// A large insert's lines as stored (spec §6.1): the blob and its content,
975
/// the canonical CBOR array of the lines' byte strings.
976
#[derive(Debug, Clone, PartialEq, Eq)]
977
pub struct StoredText {
978
    pub blob: Blob,
979
    pub content: Vec<u8>,
980
}
981
982
/// The lines a text blob's `content` holds, checked against the rules for
983
/// one: canonical, as many as the insert claims, and not short enough to
984
/// have been inline.
985
pub fn text_lines(content: &[u8], count: u32) -> Result<Vec<Vec<u8>>, ObjectError> {
986
    if content.len() < TEXT_BLOB_MIN {
987
        return schema(format!(
988
            "a text blob of {} bytes is short enough to be inline",
989
            content.len()
990
        ));
991
    }
992
    let v = cbor::decode(content)?;
993
    let lines = array(&v, "text blob")?
994
        .iter()
995
        .map(|l| bytes(l, "line").map(|b| b.to_vec()))
996
        .collect::<Result<Vec<_>, _>>()?;
997
    if lines.len() != count as usize {
998
        return schema(format!(
999
            "a text blob holds {} lines, the insert says {count}",
1000
            lines.len()
1001
        ));
1002
    }
1003
    Ok(lines)
1004
}
1005
1006
// ---------------------------------------------------------------- blob
1007
1008
/// File content as an ordered list of chunks (spec §13.2).
1009
#[derive(Debug, Clone, PartialEq, Eq)]
1010
pub struct Blob {
1011
    pub length: u64,
1012
    pub chunks: Vec<ObjectRef>,
1013
}
1014
1015
impl Blob {
1016
    /// The blob for `content`: its chunks as content-defined chunking cuts
1017
    /// them (spec §13.2).
1018
    pub fn of(content: &[u8]) -> Blob {
1019
        Blob {
1020
            length: content.len() as u64,
1021
            chunks: crate::chunk::chunks(content)
1022
                .into_iter()
1023
                .map(|c| hash_object(ObjectType::Chunk, c))
1024
                .collect(),
1025
        }
1026
    }
1027
1028
    pub fn encode(&self) -> Vec<u8> {
1029
        cbor::encode(&Value::map([
1030
            (0, Value::Uint(FORMAT_VERSION)),
1031
            (1, Value::Uint(self.length)),
1032
            (
1033
                2,
1034
                Value::Array(
1035
                    self.chunks
1036
                        .iter()
1037
                        .map(|c| Value::Bytes(c.0.to_vec()))
1038
                        .collect(),
1039
                ),
1040
            ),
1041
        ]))
1042
    }
1043
    pub fn hash(&self) -> ObjectRef {
1044
        hash_object(ObjectType::Blob, &self.encode())
1045
    }
1046
    pub fn decode(bytes: &[u8]) -> Result<Blob, ObjectError> {
1047
        let v = cbor::decode(bytes)?;
1048
        let m = map(&v, "blob")?;
1049
        check_version(m)?;
1050
        Ok(Blob {
1051
            length: uint(field(m, 1, "length")?, "length")?,
1052
            chunks: array(field(m, 2, "chunks")?, "chunks")?
1053
                .iter()
1054
                .map(|c| oref(c, "chunk"))
1055
                .collect::<Result<Vec<_>, _>>()?,
1056
        })
1057
    }
1058
}
1059
1060
// ---------------------------------------------------------------- checkpoint
1061
1062
/// A materialized state (spec §11): the heads it stands for, how many changes
1063
/// it holds, and a blob with the serialized graphs (`State::checkpoint_payload`).
1064
#[derive(Debug, Clone, PartialEq, Eq)]
1065
pub struct Checkpoint {
1066
    pub heads: Vec<ChangeHash>,
1067
    pub count: u64,
1068
    pub payload: ObjectRef,
1069
}
1070
1071
impl Checkpoint {
1072
    pub fn encode(&self) -> Vec<u8> {
1073
        cbor::encode(&Value::map([
1074
            (0, Value::Uint(FORMAT_VERSION)),
1075
            (
1076
                1,
1077
                Value::Array(
1078
                    self.heads
1079
                        .iter()
1080
                        .map(|h| Value::Bytes(h.0.to_vec()))
1081
                        .collect(),
1082
                ),
1083
            ),
1084
            (2, Value::Uint(self.count)),
1085
            (3, Value::Bytes(self.payload.0.to_vec())),
1086
        ]))
1087
    }
1088
    pub fn hash(&self) -> ObjectRef {
1089
        hash_object(ObjectType::Checkpoint, &self.encode())
1090
    }
1091
    pub fn decode(bytes: &[u8]) -> Result<Checkpoint, ObjectError> {
1092
        let v = cbor::decode(bytes)?;
1093
        let m = map(&v, "checkpoint")?;
1094
        check_version(m)?;
1095
        Ok(Checkpoint {
1096
            heads: array(field(m, 1, "heads")?, "heads")?
1097
                .iter()
1098
                .map(|h| oref(h, "head"))
1099
                .collect::<Result<Vec<_>, _>>()?,
1100
            count: uint(field(m, 2, "count")?, "count")?,
1101
            payload: oref(field(m, 3, "payload")?, "payload")?,
1102
        })
1103
    }
1104
}
1105
1106
// ---------------------------------------------------------------- state
1107
1108
/// A state named by its heads (spec §10.1): what a bookmark or tag points at.
1109
#[derive(Debug, Clone, PartialEq, Eq, Default)]
1110
pub struct StateObject {
1111
    pub heads: Vec<ChangeHash>,
1112
}
1113
1114
impl StateObject {
1115
    pub fn new(mut heads: Vec<ChangeHash>) -> StateObject {
1116
        heads.sort();
1117
        heads.dedup();
1118
        StateObject { heads }
1119
    }
1120
    pub fn encode(&self) -> Vec<u8> {
1121
        debug_assert!(self.heads.windows(2).all(|w| w[0] < w[1]));
1122
        cbor::encode(&Value::map([
1123
            (0, Value::Uint(FORMAT_VERSION)),
1124
            (
1125
                1,
1126
                Value::Array(
1127
                    self.heads
1128
                        .iter()
1129
                        .map(|h| Value::Bytes(h.0.to_vec()))
1130
                        .collect(),
1131
                ),
1132
            ),
1133
        ]))
1134
    }
1135
    pub fn hash(&self) -> ObjectRef {
1136
        hash_object(ObjectType::State, &self.encode())
1137
    }
1138
    pub fn decode(bytes: &[u8]) -> Result<StateObject, ObjectError> {
1139
        let v = cbor::decode(bytes)?;
1140
        let m = map(&v, "state")?;
1141
        check_version(m)?;
1142
        let heads = array(field(m, 1, "heads")?, "heads")?
1143
            .iter()
1144
            .map(|h| oref(h, "head"))
1145
            .collect::<Result<Vec<_>, _>>()?;
1146
        if !heads.windows(2).all(|w| w[0] < w[1]) {
1147
            return schema("state heads must be sorted and unique");
1148
        }
1149
        Ok(StateObject { heads })
1150
    }
1151
}
1152
1153
#[cfg(test)]
1154
pub(crate) mod tests {
1155
    use super::*;
1156
1157
    pub(crate) fn sample_change() -> Change {
1158
        let n = NodeId([7; 16]);
1159
        let dep = ObjectRef([1; 32]);
1160
        let mut c = Change {
1161
            version: crate::objects::CHANGE_VERSION,
1162
            change_id: ChangeId([9; 16]),
1163
            deps: vec![ObjectRef([2; 32]), dep],
1164
            author: ObjectRef([3; 32]),
1165
            hlc: Hlc {
1166
                wall_ms: 1_700_000_000_000,
1167
                logical: 4,
1168
            },
1169
            message: "Add greeting".into(),
1170
            tree_ops: vec![
1171
                TreeOp::AddNode {
1172
                    node: n,
1173
                    kind: NodeKind::File,
1174
                    mode: Mode::TEXT,
1175
                    parent: NodeId::ROOT,
1176
                    name: "hello.txt".into(),
1177
                },
1178
                TreeOp::SetMode {
1179
                    node: n,
1180
                    old: OpRef {
1181
                        change: ObjectRef::ZERO,
1182
                        index: 0,
1183
                    },
1184
                    mode: Mode {
1185
                        exec: true,
1186
                        opaque: false,
1187
                    },
1188
                },
1189
            ],
1190
            edits: vec![
1191
                Edit::Insert {
1192
                    node: n,
1193
                    after: AtomRef::Start,
1194
                    before: AtomRef::End,
1195
                    lines: vec![b"hello\n".to_vec(), b"world\n".to_vec()],
1196
                },
1197
                Edit::Delete {
1198
                    node: n,
1199
                    atoms: vec![AtomRange {
1200
                        change: dep,
1201
                        from: 0,
1202
                        to: 2,
1203
                    }],
1204
                },
1205
                Edit::Replace {
1206
                    node: n,
1207
                    old: None,
1208
                    new: Some(ObjectRef([5; 32])),
1209
                },
1210
            ],
1211
            kind: ChangeKind::Normal,
1212
        };
1213
        c.normalize();
1214
        c
1215
    }
1216
1217
    #[test]
1218
    fn change_round_trips_and_hash_is_stable() {
1219
        let c = sample_change();
1220
        let bytes = c.encode();
1221
        let d = Change::decode(&bytes).unwrap();
1222
        assert_eq!(c, d);
1223
        assert_eq!(c.hash(), d.hash());
1224
        assert_eq!(d.encode(), bytes);
1225
        // Any semantic difference changes the hash.
1226
        let mut e = c.clone();
1227
        e.message.push('!');
1228
        assert_ne!(e.hash(), c.hash());
1229
    }
1230
1231
    #[test]
1232
    fn decode_rejects_bad_changes() {
1233
        let c = sample_change();
1234
        let mut v = c.to_value();
1235
        if let Value::Map(m) = &mut v {
1236
            m.insert(0, Value::Uint(3));
1237
        }
1238
        assert!(
1239
            matches!(Change::from_value(&v), Err(ObjectError::Schema(s)) if s.contains("version"))
1240
        );
1241
1242
        let mut v = c.to_value();
1243
        if let Value::Map(m) = &mut v {
1244
            m.insert(
1245
                2,
1246
                Value::Array(vec![Value::Bytes(vec![2; 32]), Value::Bytes(vec![1; 32])]),
1247
            );
1248
        }
1249
        assert!(
1250
            matches!(Change::from_value(&v), Err(ObjectError::Schema(s)) if s.contains("sorted"))
1251
        );
1252
1253
        let mut v = c.to_value();
1254
        if let Value::Map(m) = &mut v {
1255
            m.insert(9, Value::map([(0, Value::Null)]));
1256
        }
1257
        assert!(
1258
            matches!(Change::from_value(&v), Err(ObjectError::Schema(s)) if s.contains("extra"))
1259
        );
1260
    }
1261
1262
    fn big_lines(n: usize) -> Vec<Vec<u8>> {
1263
        (0..n)
1264
            .map(|i| format!("line {i} of a large insert\n").into_bytes())
1265
            .collect()
1266
    }
1267
1268
    fn with_insert(mut c: Change, lines: Vec<Vec<u8>>) -> Change {
1269
        c.edits[0] = Edit::Insert {
1270
            node: NodeId([7; 16]),
1271
            after: AtomRef::Start,
1272
            before: AtomRef::End,
1273
            lines,
1274
        };
1275
        c
1276
    }
1277
1278
    #[test]
1279
    fn large_inserts_are_stored_as_text_blobs() {
1280
        assert!(
1281
            !sample_change().has_stored_text(),
1282
            "a small insert stays inline"
1283
        );
1284
        let lines = big_lines(500);
1285
        let c = with_insert(sample_change(), lines.clone());
1286
        assert!(c.has_stored_text());
1287
        let (bytes, texts) = c.encode_parts();
1288
        assert_eq!(bytes, c.encode());
1289
        assert!(bytes.len() < 1024, "{}", bytes.len());
1290
        assert_eq!(texts.len(), 1);
1291
        assert_eq!(texts[0].content, cbor::encode_byte_strings(&lines));
1292
        assert_eq!(texts[0].blob, Blob::of(&texts[0].content));
1293
        assert!(Change::decode(&bytes).is_err(), "reading it needs the text");
1294
        let d = Change::decode_with(&bytes, &mut |r, n| {
1295
            assert_eq!(*r, texts[0].blob.hash());
1296
            text_lines(&texts[0].content, n)
1297
        })
1298
        .unwrap();
1299
        assert_eq!(d, c);
1300
        assert_eq!(d.hash(), c.hash());
1301
    }
1302
1303
    #[test]
1304
    fn version_1_changes_keep_their_inline_inserts_and_hashes() {
1305
        let mut c = with_insert(sample_change(), big_lines(500));
1306
        c.version = 1;
1307
        let bytes = c.encode();
1308
        assert!(bytes.len() > TEXT_BLOB_MIN);
1309
        let (again, texts) = c.encode_parts();
1310
        assert!(texts.is_empty());
1311
        assert_eq!(again, bytes);
1312
        let d = Change::decode(&bytes).unwrap();
1313
        assert_eq!(d.version, 1);
1314
        assert_eq!(d.encode(), bytes);
1315
        // The same inline insert in a version 2 change is not canonical.
1316
        let mut v = c.to_value();
1317
        if let Value::Map(m) = &mut v {
1318
            m.insert(0, Value::Uint(2));
1319
        }
1320
        assert!(
1321
            matches!(Change::from_value(&v), Err(ObjectError::Schema(s)) if s.contains("text blob"))
1322
        );
1323
    }
1324
1325
    #[test]
1326
    fn a_skeleton_leaves_every_insert_out_and_says_where_its_lines_are() {
1327
        let mut c = with_insert(sample_change(), big_lines(500));
1328
        c.edits.push(Edit::Insert {
1329
            node: NodeId([8; 16]),
1330
            after: AtomRef::Start,
1331
            before: AtomRef::End,
1332
            lines: vec![b"small\n".to_vec(), b"insert\n".to_vec()],
1333
        });
1334
        let (bytes, stored) = c.encode_parts();
1335
        let me = ObjectRef([4; 32]);
1336
        let (skel, texts) = Change::decode_skeleton(&bytes, me).unwrap();
1337
        assert_eq!(texts.len(), 2);
1338
        let mut filled = skel.clone();
1339
        let mut next = texts.iter();
1340
        for e in filled.edits.iter_mut() {
1341
            if let Edit::Insert { lines, .. } = e {
1342
                assert!(lines.is_empty(), "no line kept");
1343
                *lines = match next.next().unwrap() {
1344
                    TextRef::Blob(r, n) => {
1345
                        assert_eq!(*r, stored[0].blob.hash());
1346
                        text_lines(&stored[0].content, *n).unwrap()
1347
                    }
1348
                    TextRef::Inline { change, start, end } => {
1349
                        assert_eq!(*change, me);
1350
                        inline_lines(&bytes[*start as usize..*end as usize]).unwrap()
1351
                    }
1352
                };
1353
            }
1354
        }
1355
        assert_eq!(filled, c, "filled in, it is the change");
1356
        // A version 1 change's large inline insert is fine; in version 2 it is not.
1357
        let mut v1 = with_insert(sample_change(), big_lines(500));
1358
        v1.version = 1;
1359
        assert!(Change::decode_skeleton(&v1.encode(), me).is_ok());
1360
        let mut v = v1.to_value();
1361
        if let Value::Map(m) = &mut v {
1362
            m.insert(0, Value::Uint(2));
1363
        }
1364
        assert!(Change::decode_skeleton(&cbor::encode(&v), me).is_err());
1365
    }
1366
1367
    #[test]
1368
    fn text_blobs_are_checked() {
1369
        let lines = big_lines(500);
1370
        let content = cbor::encode_byte_strings(&lines);
1371
        assert_eq!(content.len(), cbor::byte_strings_len(&lines));
1372
        assert_eq!(
1373
            content,
1374
            cbor::encode(&Value::Array(
1375
                lines.iter().map(|l| Value::Bytes(l.clone())).collect()
1376
            ))
1377
        );
1378
        assert_eq!(text_lines(&content, 500).unwrap(), lines);
1379
        assert!(text_lines(&content, 499).is_err());
1380
        let small = cbor::encode_byte_strings(&[b"x\n".to_vec()]);
1381
        assert!(text_lines(&small, 1).is_err(), "short enough to be inline");
1382
    }
1383
1384
    #[test]
1385
    fn names_are_validated() {
1386
        for bad in ["", ".", "..", "a/b", "a\0b"] {
1387
            assert!(validate_name(bad).is_err(), "{bad:?}");
1388
        }
1389
        assert!(validate_name("Foo.c").is_ok());
1390
        assert!(validate_name("...").is_ok());
1391
    }
1392
1393
    #[test]
1394
    fn mode_and_kind_tags() {
1395
        for m in [
1396
            Mode::TEXT,
1397
            Mode::OPAQUE,
1398
            Mode {
1399
                exec: true,
1400
                opaque: true,
1401
            },
1402
        ] {
1403
            assert_eq!(Mode::from_bits(m.bits()).unwrap(), m);
1404
        }
1405
        assert!(Mode::from_bits(4).is_err());
1406
        for k in [
1407
            NodeKind::File,
1408
            NodeKind::Dir,
1409
            NodeKind::Symlink,
1410
            NodeKind::Subrepo,
1411
        ] {
1412
            assert_eq!(NodeKind::from_tag(k.tag()).unwrap(), k);
1413
        }
1414
    }
1415
1416
    #[test]
1417
    fn self_references_resolve() {
1418
        let me = ObjectRef([8; 32]);
1419
        assert_eq!(
1420
            AtomRef::Atom {
1421
                change: ObjectRef::ZERO,
1422
                index: 3
1423
            }
1424
            .resolve(me),
1425
            AtomRef::Atom {
1426
                change: me,
1427
                index: 3
1428
            }
1429
        );
1430
        assert_eq!(AtomRef::Start.resolve(me), AtomRef::Start);
1431
        let other = ObjectRef([1; 32]);
1432
        assert_eq!(
1433
            OpRef {
1434
                change: other,
1435
                index: 1
1436
            }
1437
            .resolve(me)
1438
            .change,
1439
            other
1440
        );
1441
    }
1442
1443
    #[test]
1444
    fn state_object_round_trip() {
1445
        let st = StateObject::new(vec![
1446
            ObjectRef([2; 32]),
1447
            ObjectRef([1; 32]),
1448
            ObjectRef([2; 32]),
1449
        ]);
1450
        assert_eq!(st.heads, vec![ObjectRef([1; 32]), ObjectRef([2; 32])]);
1451
        assert_eq!(StateObject::decode(&st.encode()).unwrap(), st);
1452
        assert_eq!(StateObject::new(vec![]).heads, vec![]);
1453
        assert_ne!(StateObject::new(vec![]).hash(), st.hash());
1454
    }
1455
1456
    #[test]
1457
    fn blob_round_trip() {
1458
        let b = Blob {
1459
            length: 10,
1460
            chunks: vec![ObjectRef([1; 32]), ObjectRef([2; 32])],
1461
        };
1462
        assert_eq!(Blob::decode(&b.encode()).unwrap(), b);
1463
    }
1464
}