frdt 0.2.0

Edit and inspect Resonite FrDT (.brson) documents without expanding them to JSON
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
//! Edit handle over one decompressed BSON buffer.
//!
//! `Document` and `SlotHandle` share the buffer through `Arc`. A handle follows
//! an internal slot key, not the BSON `ID` string. After an edit shifts byte
//! offsets, the next call resolves that key again.

use std::collections::HashMap;
use std::io::Write;
use std::sync::{Arc, Mutex, MutexGuard};

use crate::container::{self, DEFAULT_QUALITY};
use crate::datatree;
use crate::edit;
use crate::empty;
use crate::error::{Error, Result};
use crate::import;
use crate::index::{self, Index};
use crate::merge;
use crate::typetable;
use crate::value::Value;
use crate::work;

struct Inner {
    bytes: Vec<u8>,
    index: Index,
    /// Bumped on every committed edit. Handles cache an offset only while this
    /// still matches; otherwise they look the slot up by its key.
    generation: u64,
}

/// An open FrDT document. Mutations update this buffer in place.
#[derive(Clone)]
pub struct Document {
    inner: Arc<Mutex<Inner>>,
}

/// A slot inside a [`Document`].
///
/// The cached offset is valid only for `generation`. `key` stays with the slot
/// when its BSON `ID` field changes, so a duplicate id cannot retarget it.
#[derive(Clone)]
pub struct SlotHandle {
    inner: Arc<Mutex<Inner>>,
    key: u64,
    offset: usize,
    generation: u64,
}

/// `Type` index, resolved name, and reference targets of one component.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ComponentInfo {
    pub type_index: i64,
    pub type_name: String,
    pub references: Vec<String>,
}

/// One entry of the root `Asset` array.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AssetInfo {
    pub id: String,
    pub type_index: Option<i64>,
}

/// What [`Document::import`] copied.
pub struct Import {
    slots: Vec<SlotHandle>,
    ids: HashMap<String, String>,
    unresolved: Vec<String>,
    asset_count: usize,
}

impl Import {
    /// The copied slots in the destination, in the order they were passed.
    pub fn slots(&self) -> &[SlotHandle] {
        &self.slots
    }

    /// The destination identifier that replaced a source identifier.
    ///
    /// Covers every slot, component, field, and asset identifier that was
    /// copied, so a caller can point a new reference (for example a new
    /// `Static.ChildrenParent`) at a copied target.
    pub fn new_id(&self, source_id: &str) -> Option<&str> {
        self.ids.get(source_id).map(String::as_str)
    }

    /// Source identifiers that the copy still names but that were not copied.
    /// Those strings are left unchanged. Sorted.
    pub fn unresolved(&self) -> &[String] {
        &self.unresolved
    }

    /// Number of asset entries copied because the subtrees use them.
    pub fn asset_count(&self) -> usize {
        self.asset_count
    }
}

impl Document {
    /// A document with one empty root slot named `root_name`.
    ///
    /// `version_number` must read as `year.month.day[.build]`. Feature flags are
    /// written as int64, in the order given. `Types`, `TypeVersions`, and
    /// `Assets` start empty. The root's `ParentReference` is a fresh id.
    pub fn empty<I, K>(root_name: &str, version_number: &str, feature_flags: I) -> Result<Document>
    where
        I: IntoIterator<Item = (K, i64)>,
        K: AsRef<str>,
    {
        let bson = empty::empty_bson(root_name, version_number, feature_flags)?;
        let index = index::build(&bson)?;
        Ok(Document {
            inner: Arc::new(Mutex::new(Inner {
                bytes: bson,
                index,
                generation: 0,
            })),
        })
    }

    /// Open a Resonite `.brson` (`FrDT`) or a tool working file (`FRWK`).
    pub fn open(bytes: &[u8]) -> Result<Document> {
        let (bson, index) = if bytes.starts_with(work::MAGIC) {
            work::read(bytes)?
        } else {
            let bson = container::decompress(bytes)?;
            let index = index::build(&bson)?;
            (bson, index)
        };
        Ok(Document {
            inner: Arc::new(Mutex::new(Inner {
                bytes: bson,
                index,
                generation: 0,
            })),
        })
    }

    pub fn root(&self) -> SlotHandle {
        let guard = self.lock().expect("frdt document lock");
        handle_at(&self.inner, &guard, guard.index.root_slot).expect("root slot")
    }

    /// Graft `child` under `parent`. `parent` must belong to this document.
    ///
    /// The returned handle is the grafted slot inside this document. Handles
    /// into `child`'s document are not updated.
    pub fn append(&mut self, parent: SlotHandle, child: SlotHandle) -> Result<SlotHandle> {
        if !Arc::ptr_eq(&self.inner, &parent.inner) {
            return Err(Error::Invalid(
                "parent handle is from a different document".into(),
            ));
        }
        // Snapshot the child before locking the destination. The same document
        // would deadlock if both guards were held, and a failed merge must not
        // leave the destination half-updated.
        let (child_bytes, child_off) = {
            let guard = child.inner.lock()?;
            let off = resolve(&guard, &child)?;
            (guard.bytes.clone(), off)
        };
        let mut guard = self.inner.lock()?;
        let parent_off = resolve(&guard, &parent)?;
        let mut bytes = guard.bytes.clone();
        let new_off = merge::append_slot(&mut bytes, parent_off, &child_bytes, child_off)?;
        let index = index::rebuild(&bytes, &guard.index)?;
        let key = index
            .slots
            .iter()
            .find(|slot| slot.offset == new_off)
            .map(|slot| slot.key)
            .ok_or_else(|| Error::Invalid("grafted slot is missing from the index".into()))?;
        let generation = guard.generation.wrapping_add(1);
        guard.bytes = bytes;
        guard.index = index;
        guard.generation = generation;
        Ok(SlotHandle {
            inner: Arc::clone(&self.inner),
            key,
            offset: new_off,
            generation,
        })
    }

    /// Copy `slots` (all from one document) to the end of `parent`'s children.
    ///
    /// Components and fields come with each slot. Every identifier in the
    /// copies, and in the assets they reference, is replaced from one map, so
    /// references among the copied slots and assets keep their targets. A
    /// reference to anything else in the source is left as it was and listed
    /// in [`Import::unresolved`]. Assets that nothing copied references stay
    /// behind. Type names the destination lacks are appended to `Types`, with
    /// their `TypeVersions` entry when the destination has none. `FeatureFlags`
    /// and `VersionNumber` of the destination are not changed.
    ///
    /// The source document is not modified. On error neither document changes.
    pub fn import(&mut self, parent: &SlotHandle, slots: &[SlotHandle]) -> Result<Import> {
        if !Arc::ptr_eq(&self.inner, &parent.inner) {
            return Err(Error::Invalid(
                "parent handle is from a different document".into(),
            ));
        }
        let Some(first) = slots.first() else {
            return Ok(Import {
                slots: Vec::new(),
                ids: HashMap::new(),
                unresolved: Vec::new(),
                asset_count: 0,
            });
        };
        if slots.iter().any(|s| !Arc::ptr_eq(&s.inner, &first.inner)) {
            return Err(Error::Invalid(
                "imported slots must come from one document".into(),
            ));
        }
        let (src_bytes, spans) = {
            let guard = first.inner.lock()?;
            let mut spans = Vec::with_capacity(slots.len());
            for slot in slots {
                let offset = resolve(&guard, slot)?;
                let loc = guard.index.slot_by_offset(offset).ok_or(Error::NotFound)?;
                spans.push((loc.offset, loc.end));
            }
            (guard.bytes.clone(), spans)
        };
        let mut guard = self.inner.lock()?;
        let parent_off = resolve(&guard, parent)?;
        let mut bytes = guard.bytes.clone();
        let outcome =
            import::import_slots(&mut bytes, &guard.index, parent_off, &src_bytes, &spans)?;
        let index = index::rebuild(&bytes, &guard.index)?;
        let generation = guard.generation.wrapping_add(1);
        let mut handles = Vec::with_capacity(outcome.roots.len());
        for id in &outcome.roots {
            let slot = index
                .slots
                .iter()
                .find(|slot| slot.id == *id)
                .ok_or_else(|| Error::Invalid("imported slot is missing from the index".into()))?;
            handles.push(SlotHandle {
                inner: Arc::clone(&self.inner),
                key: slot.key,
                offset: slot.offset,
                generation,
            });
        }
        guard.bytes = bytes;
        guard.index = index;
        guard.generation = generation;
        Ok(Import {
            slots: handles,
            ids: outcome.ids,
            unresolved: outcome.unresolved,
            asset_count: outcome.assets,
        })
    }

    /// Add an empty slot named `name` as the last child of `parent`.
    ///
    /// The slot is laid out like [`Document::empty`]'s root, with
    /// `ParentReference` set to the parent's id.
    pub fn add_slot(&mut self, parent: &SlotHandle, name: &str) -> Result<SlotHandle> {
        self.own(parent)?;
        let mut guard = self.inner.lock()?;
        let parent_off = resolve(&guard, parent)?;
        let parent_pos = guard.index.position(parent_off).ok_or(Error::NotFound)?;
        let mut bytes = guard.bytes.clone();
        let id = edit::add_slot(&mut bytes, &guard.index, parent_off, name)?;
        let key = guard.index.next_key();
        let keys = edit::keys_after_add(&guard.index, parent_pos, key);
        let index = index::rebuild_keys(&bytes, &guard.index, &keys, key + 1)?;
        let offset = index
            .slot_by_key(key)
            .map(|s| s.offset)
            .ok_or(Error::NotFound)?;
        debug_assert_eq!(
            index.slot_by_offset(offset).map(|s| s.id.as_str()),
            Some(id.as_str())
        );
        let generation = commit(&mut guard, bytes, index);
        Ok(SlotHandle {
            inner: Arc::clone(&self.inner),
            key,
            offset,
            generation,
        })
    }

    /// Append a component to `slot`.
    ///
    /// Each field is written as `{ID, Data}` with a new id; `None` writes
    /// null. The component gets new `ID` and `persistent-ID` values, and its
    /// `Type` is int64. The type name is appended to `Types` when missing, and
    /// `type_version` (when given) is added to `TypeVersions` when the name
    /// has no entry. Returns the component's position in
    /// [`SlotHandle::components`] and its id.
    pub fn add_component(
        &mut self,
        slot: &SlotHandle,
        type_name: &str,
        type_version: Option<i64>,
        fields: &[(&str, Option<Value>)],
    ) -> Result<(usize, String)> {
        self.own(slot)?;
        let mut guard = self.inner.lock()?;
        let offset = resolve(&guard, slot)?;
        let mut bytes = guard.bytes.clone();
        let added = edit::add_component(
            &mut bytes,
            &guard.index,
            offset,
            type_name,
            type_version,
            fields,
        )?;
        let keys = guard.index.keys();
        let index = index::rebuild_keys(&bytes, &guard.index, &keys, 0)?;
        commit(&mut guard, bytes, index);
        Ok(added)
    }

    /// Make `slot` the last child of `new_parent`, in this document.
    ///
    /// The subtree keeps its ids; only its `ParentReference` changes. Handles
    /// to slots in the subtree stay valid. The root cannot move, and a slot
    /// cannot move under itself.
    pub fn move_slot(&mut self, slot: &SlotHandle, new_parent: &SlotHandle) -> Result<()> {
        self.own(slot)?;
        self.own(new_parent)?;
        let mut guard = self.inner.lock()?;
        let offset = resolve(&guard, slot)?;
        let parent_off = resolve(&guard, new_parent)?;
        if edit::contains(&guard.index, offset, parent_off)? {
            return Err(Error::Invalid("a slot cannot move under itself".into()));
        }
        let pos = guard.index.position(offset).ok_or(Error::NotFound)?;
        let parent_pos = guard.index.position(parent_off).ok_or(Error::NotFound)?;
        let parent_key = guard.index.slots[parent_pos].key;
        let parent_id = guard.index.slots[parent_pos].id.clone();
        let keys = edit::keys_after_move(&guard.index, pos, parent_pos);

        let mut bytes = guard.bytes.clone();
        let removed = edit::remove_slot(&mut bytes, &guard.index, offset)?;
        let after_remove = edit::keys_after_remove(&guard.index, pos);
        let middle = index::rebuild_keys(&bytes, &guard.index, &after_remove, 0)?;
        let parent_off = middle
            .slot_by_key(parent_key)
            .map(|s| s.offset)
            .ok_or(Error::NotFound)?;
        let moved = edit::with_parent(&removed, &parent_id)?;
        edit::insert_child(&mut bytes, &middle, parent_off, &moved)?;
        let index = index::rebuild_keys(&bytes, &guard.index, &keys, 0)?;
        commit(&mut guard, bytes, index);
        Ok(())
    }

    /// Remove `slot` and everything under it. The root cannot be removed.
    ///
    /// References elsewhere that named the removed slots are left as they
    /// are. Call [`Document::rebuild_types`] afterwards to drop type names
    /// that nothing uses any more.
    pub fn remove_slot(&mut self, slot: &SlotHandle) -> Result<()> {
        self.own(slot)?;
        let mut guard = self.inner.lock()?;
        let offset = resolve(&guard, slot)?;
        let pos = guard.index.position(offset).ok_or(Error::NotFound)?;
        let keys = edit::keys_after_remove(&guard.index, pos);
        let mut bytes = guard.bytes.clone();
        edit::remove_slot(&mut bytes, &guard.index, offset)?;
        let index = index::rebuild_keys(&bytes, &guard.index, &keys, 0)?;
        commit(&mut guard, bytes, index);
        Ok(())
    }

    fn own(&self, handle: &SlotHandle) -> Result<()> {
        if Arc::ptr_eq(&self.inner, &handle.inner) {
            Ok(())
        } else {
            Err(Error::Invalid(
                "slot handle is from a different document".into(),
            ))
        }
    }

    /// Rebuild `Types` from the components and assets that remain.
    ///
    /// Names keep their first-use order (slots depth first, components in
    /// order, then assets). Every component `Type`, and every type field such
    /// as `GizmoLink._type`, is renumbered in place. `TypeVersions` keeps only
    /// entries whose name is still listed. Returns the names that were removed.
    pub fn rebuild_types(&mut self) -> Result<Vec<String>> {
        let mut guard = self.inner.lock()?;
        let mut bytes = guard.bytes.clone();
        let removed = typetable::rebuild(&mut bytes, &guard.index)?;
        let index = index::rebuild(&bytes, &guard.index)?;
        guard.bytes = bytes;
        guard.index = index;
        guard.generation = guard.generation.wrapping_add(1);
        Ok(removed)
    }

    /// The slot whose `ID` is `id`. The first one in depth-first order when
    /// the id is duplicated.
    pub fn slot_by_id(&self, id: &str) -> Result<SlotHandle> {
        let guard = self.lock()?;
        let offset = guard
            .index
            .slots
            .iter()
            .find(|slot| slot.id == id)
            .map(|slot| slot.offset)
            .ok_or(Error::NotFound)?;
        handle_at(&self.inner, &guard, offset)
    }

    /// `VersionNumber` as written. Resonite writes a string such as
    /// `2026.9.18.82`; any other BSON type is an error.
    pub fn version_number(&self) -> Result<String> {
        let guard = self.lock()?;
        let el = datatree::field(&guard.bytes, 0, "VersionNumber")?
            .ok_or_else(|| Error::FieldNotFound("VersionNumber".into()))?;
        if el.ty != crate::bson::STRING {
            return Err(Error::Invalid("VersionNumber is not a string".into()));
        }
        Ok(crate::bson::decode_string(el.value)?.to_string())
    }

    /// Every feature flag in file order. A bool reads as 0 or 1.
    pub fn feature_flags(&self) -> Result<Vec<(String, i64)>> {
        let guard = self.lock()?;
        let Some(doc) = datatree::field(&guard.bytes, 0, "FeatureFlags")? else {
            return Ok(Vec::new());
        };
        if doc.ty != crate::bson::DOCUMENT {
            return Err(Error::Invalid("FeatureFlags is not a document".into()));
        }
        let mut out = Vec::new();
        for el in crate::bson::elements(&guard.bytes, doc.value_at)? {
            let value = match el.ty {
                crate::bson::BOOL => i64::from(crate::bson::decode_bool(el.value)?),
                _ => crate::bson::decode_int(el.value, el.ty)?,
            };
            out.push((el.key.to_string(), value));
        }
        Ok(out)
    }

    pub fn types(&self) -> Result<Vec<String>> {
        Ok(self.lock()?.index.types.clone())
    }

    pub fn slot_count(&self) -> Result<usize> {
        Ok(self.lock()?.index.slots.len())
    }

    pub fn component_count(&self) -> Result<usize> {
        Ok(self.lock()?.index.components.len())
    }

    pub fn type_version(&self, name: &str) -> Result<Option<i64>> {
        let guard = self.lock()?;
        let Some(doc) = datatree::field(&guard.bytes, 0, "TypeVersions")? else {
            return Ok(None);
        };
        if doc.ty != crate::bson::DOCUMENT {
            return Err(Error::Invalid("TypeVersions is not a document".into()));
        }
        datatree::read_number_field(&guard.bytes, doc.value_at, name)
    }

    pub fn feature_flag(&self, name: &str) -> Result<Option<bool>> {
        let guard = self.lock()?;
        let Some(doc) = datatree::field(&guard.bytes, 0, "FeatureFlags")? else {
            return Ok(None);
        };
        if doc.ty != crate::bson::DOCUMENT {
            return Err(Error::Invalid("FeatureFlags is not a document".into()));
        }
        datatree::read_bool_field(&guard.bytes, doc.value_at, name)
    }

    pub fn assets(&self) -> Result<Vec<AssetInfo>> {
        let guard = self.lock()?;
        Ok(datatree::asset_views(&guard.bytes)?
            .into_iter()
            .map(|(id, type_index)| AssetInfo { id, type_index })
            .collect())
    }

    /// Each asset entry's BSON document, for tests.
    pub(crate) fn asset_raw(&self) -> Result<Vec<Vec<u8>>> {
        let guard = self.lock()?;
        let Some(arr) = datatree::asset_array(&guard.bytes)? else {
            return Ok(Vec::new());
        };
        Ok(crate::bson::elements(&guard.bytes, arr.value_at)?
            .into_iter()
            .map(|el| el.value.to_vec())
            .collect())
    }

    /// Decompressed BSON. This is the edit buffer, not a JSON document.
    pub fn bson_bytes(&self) -> Result<Vec<u8>> {
        Ok(self.lock()?.bytes.clone())
    }

    /// Resonite `.brson`: Brotli quality 5 and the 9-byte `FrDT` header.
    pub fn write_brson<W: Write>(&self, out: &mut W) -> Result<()> {
        self.write_brson_with_quality(out, DEFAULT_QUALITY)
    }

    pub fn write_brson_with_quality<W: Write>(&self, out: &mut W, quality: u32) -> Result<()> {
        let guard = self.lock()?;
        container::write_brson(&guard.bytes, out, quality)
    }

    /// Tool file: uncompressed BSON and the index, so the next open skips Brotli.
    pub fn write_work(&self, out: &mut Vec<u8>) -> Result<()> {
        let guard = self.lock()?;
        work::write(&guard.bytes, &guard.index, out)
    }

    fn lock(&self) -> Result<MutexGuard<'_, Inner>> {
        Ok(self.inner.lock()?)
    }
}

impl SlotHandle {
    pub fn name(&self) -> Result<String> {
        let guard = self.lock()?;
        let offset = resolve(&guard, self)?;
        datatree::read_string_field(&guard.bytes, offset, "Name")?
            .ok_or_else(|| Error::Invalid("slot has no Name".into()))
    }

    pub fn id(&self) -> Result<String> {
        let guard = self.lock()?;
        let offset = resolve(&guard, self)?;
        datatree::read_string_field(&guard.bytes, offset, "ID")?
            .ok_or_else(|| Error::Invalid("slot has no ID".into()))
    }

    pub fn parent_reference(&self) -> Result<Option<String>> {
        let guard = self.lock()?;
        let offset = resolve(&guard, self)?;
        datatree::read_string_field(&guard.bytes, offset, "ParentReference")
    }

    pub fn get(&self, field: &str) -> Result<Value> {
        let guard = self.lock()?;
        let offset = resolve(&guard, self)?;
        datatree::read_slot_value(&guard.bytes, offset, field)
    }

    /// Replace a field on this slot and patch ancestor BSON lengths.
    ///
    /// When the field is `{ID, Data}` (as Resonite writes `Name`, `Tag`,
    /// `Position`, ...), only `Data` is replaced and the wrapper keeps its id;
    /// `float3` and `floatQ` are then written as double arrays. An unwrapped
    /// field is replaced as in v1.
    ///
    /// The splice is applied to a copy and installed only after the document
    /// still indexes cleanly.
    pub fn set(&self, field: &str, value: Value) -> Result<()> {
        let mut guard = self.lock()?;
        let offset = resolve(&guard, self)?;
        if field == "ID" {
            reject_duplicate_slot_id(&guard, offset, &value)?;
        }
        let lengths = guard
            .index
            .slot_by_offset(offset)
            .map(|slot| slot.container_lengths.clone())
            .ok_or(Error::NotFound)?;
        let mut bytes = guard.bytes.clone();
        replace_field(&mut bytes, offset, field, &value, &lengths)?;
        let index = index::rebuild(&bytes, &guard.index)?;
        guard.bytes = bytes;
        guard.index = index;
        guard.generation = guard.generation.wrapping_add(1);
        Ok(())
    }

    /// Depth-first search. The predicate sees this slot first.
    ///
    /// The lock is not held while `pred` runs, so the predicate may call
    /// [`SlotHandle::name`].
    pub fn find_slot<F>(&self, mut pred: F) -> Result<SlotHandle>
    where
        F: FnMut(&SlotHandle) -> Result<bool>,
    {
        let (start_gen, start) = {
            let guard = self.lock()?;
            (guard.generation, resolve(&guard, self)?)
        };
        let mut stack = vec![start];
        while let Some(offset) = stack.pop() {
            let handle = {
                let guard = self.lock()?;
                if guard.generation != start_gen {
                    return Err(Error::Invalid("document changed during find_slot".into()));
                }
                handle_at(&self.inner, &guard, offset)?
            };
            if pred(&handle)? {
                return Ok(handle);
            }
            let children = {
                let guard = self.lock()?;
                if guard.generation != start_gen {
                    return Err(Error::Invalid("document changed during find_slot".into()));
                }
                datatree::child_slot_offsets(&guard.bytes, offset)?
            };
            for child in children.into_iter().rev() {
                stack.push(child);
            }
        }
        Err(Error::NotFound)
    }

    /// This slot's BSON document, for tests.
    pub(crate) fn raw(&self) -> Result<Vec<u8>> {
        let guard = self.lock()?;
        let offset = resolve(&guard, self)?;
        let end = crate::bson::doc_end(&guard.bytes, offset)?;
        Ok(guard.bytes[offset..end].to_vec())
    }

    /// Set a field of the `component`-th component (the order of
    /// [`SlotHandle::components`]).
    ///
    /// For a `{ID, Data}` field only `Data` changes, in Resonite's layout
    /// (int64, double arrays); `None` writes null. A reference is the target's
    /// id as [`Value::String`]. The field must already exist.
    pub fn set_component_value(
        &self,
        component: usize,
        field: &str,
        value: Option<Value>,
    ) -> Result<()> {
        let mut guard = self.lock()?;
        let offset = resolve(&guard, self)?;
        let mut bytes = guard.bytes.clone();
        edit::set_component_value(
            &mut bytes,
            &guard.index,
            offset,
            component,
            field,
            value.as_ref(),
        )?;
        let keys = guard.index.keys();
        let index = index::rebuild_keys(&bytes, &guard.index, &keys, 0)?;
        commit(&mut guard, bytes, index);
        Ok(())
    }

    /// Child slots in order.
    pub fn children(&self) -> Result<Vec<SlotHandle>> {
        let guard = self.lock()?;
        let offset = resolve(&guard, self)?;
        datatree::child_slot_offsets(&guard.bytes, offset)?
            .into_iter()
            .map(|child| handle_at(&self.inner, &guard, child))
            .collect()
    }

    /// A field of the `component`-th component (the order of
    /// [`SlotHandle::components`]). A `{ID, Data}` field reads its `Data`.
    /// A null value is `None`. A reference reads as the target id string.
    pub fn component_value(&self, component: usize, field: &str) -> Result<Option<Value>> {
        let guard = self.lock()?;
        let offset = resolve(&guard, self)?;
        let types = datatree::read_types(&guard.bytes)?;
        let comps = datatree::components_of_slot(&guard.bytes, offset, &types)?;
        let comp = comps
            .get(component)
            .ok_or_else(|| Error::Invalid(format!("no component at {component}")))?;
        let data = datatree::field(&guard.bytes, comp.offset, "Data")?
            .ok_or_else(|| Error::FieldNotFound("Data".into()))?;
        if data.ty != crate::bson::DOCUMENT {
            return Err(Error::Invalid("component Data is not a document".into()));
        }
        let el = datatree::field(&guard.bytes, data.value_at, field)?
            .ok_or_else(|| Error::FieldNotFound(field.to_string()))?;
        datatree::decode_optional_value(&guard.bytes, &el)
    }

    pub fn components(&self) -> Result<Vec<ComponentInfo>> {
        let guard = self.lock()?;
        let offset = resolve(&guard, self)?;
        let types = datatree::read_types(&guard.bytes)?;
        Ok(datatree::components_of_slot(&guard.bytes, offset, &types)?
            .into_iter()
            .map(|c| ComponentInfo {
                type_index: c.type_index,
                type_name: c.type_name,
                references: c.references,
            })
            .collect())
    }

    fn lock(&self) -> Result<MutexGuard<'_, Inner>> {
        Ok(self.inner.lock()?)
    }
}

/// Install an edited buffer and its index. Returns the new generation.
fn commit(guard: &mut Inner, bytes: Vec<u8>, index: Index) -> u64 {
    guard.bytes = bytes;
    guard.index = index;
    guard.generation = guard.generation.wrapping_add(1);
    guard.generation
}

fn resolve(guard: &Inner, handle: &SlotHandle) -> Result<usize> {
    if handle.generation == guard.generation {
        if let Some(slot) = guard.index.slot_by_offset(handle.offset) {
            if slot.key == handle.key {
                return Ok(handle.offset);
            }
        }
    }
    guard
        .index
        .slot_by_key(handle.key)
        .map(|slot| slot.offset)
        .ok_or(Error::NotFound)
}

fn handle_at(inner: &Arc<Mutex<Inner>>, guard: &Inner, offset: usize) -> Result<SlotHandle> {
    let key = guard
        .index
        .slot_by_offset(offset)
        .map(|slot| slot.key)
        .ok_or_else(|| Error::Invalid("slot is missing from the index".into()))?;
    Ok(SlotHandle {
        inner: Arc::clone(inner),
        key,
        offset,
        generation: guard.generation,
    })
}

fn reject_duplicate_slot_id(guard: &Inner, offset: usize, value: &Value) -> Result<()> {
    let Value::String(new_id) = value else {
        return Err(Error::Invalid("slot ID must be a string".into()));
    };
    let current = guard
        .index
        .slot_by_offset(offset)
        .map(|slot| slot.id.as_str())
        .ok_or(Error::NotFound)?;
    if new_id == current {
        return Ok(());
    }
    let ids = datatree::document_ids(&guard.bytes)?;
    if ids.iter().any(|id| id == new_id) {
        return Err(Error::Invalid("duplicate PackageNodeIdentifier".into()));
    }
    Ok(())
}

fn replace_field(
    buf: &mut Vec<u8>,
    slot_off: usize,
    name: &str,
    value: &Value,
    lengths: &[usize],
) -> Result<()> {
    let spot = crate::bson::elements(buf, slot_off)?
        .iter()
        .find(|e| e.key == name)
        .map(edit::Spot::from)
        .ok_or_else(|| Error::FieldNotFound(name.to_string()))?;
    edit::replace_value(buf, &spot, Some(value), lengths)
}