Skip to main content

tilo_resource/
keyed.rs

1//! Items keyed by an id they carry, with no stored order: [`Keyed`].
2//!
3//! A [`Collection`](crate::Collection) keeps an order key per item, which is
4//! right for a list someone arranges. Many items are ordered by their own
5//! content instead — clips by where they sit on a timeline, markers by
6//! their time, tracks by their index — and an order key would be a second
7//! truth that can disagree with it. `Keyed<T>` stores each item under the id
8//! it carries ([`Identified::id`]), merges concurrent edits per field of each
9//! item, and holds them in memory as a plain `Vec<T>` in id order (then
10//! [`Identified::order`]), so code that works with a vector keeps working.
11//!
12//! Clones share the vector until one of them changes it: a copy of a state
13//! holding items (a view keeping the state it was shown while the reader
14//! follows) costs a pointer, and a change copies only the items of the field
15//! it touched.
16//!
17//! A refresh keeps each item's id beside it, so bringing the items up to
18//! date after a change asks only the items the change touched for their
19//! ids: an id may be costly to make (formatted from a UUID), and finding and
20//! sorting by asking every item again cost more than the change itself.
21//!
22//! A copy changed one item at a time ([`Items::find_mut`]) remembers which
23//! items it handed out since it was copied, so the edits between it and the
24//! items it was copied from ([`Model::diff`], what a surface that edited a
25//! local copy submits) compare only those: an edit of one clip of 600 costs
26//! one clip, not 600. Items added at the end ([`Items::push`]) and items
27//! removed ([`Items::retain`], [`Items::take`], [`Items::remove`]) are
28//! remembered the same way, so cutting a clip in two costs the two halves
29//! and deleting one costs that one. Saving a copy over the items it was
30//! copied from writes only the items changed, added and removed, and for a
31//! [`Keyed`] those someone else touched meanwhile.
32
33use std::cmp::Ordering;
34use std::collections::{HashMap, HashSet};
35use std::marker::PhantomData;
36use std::ops::{Deref, DerefMut};
37use std::sync::Arc;
38use std::sync::atomic::{AtomicU64, Ordering as Atomic};
39use tilo_sort::CompactSort as _;
40
41use automerge::transaction::Transactable;
42use automerge::{ObjId, ObjType, ReadDoc, Value};
43
44use crate::action::{ActionCx, Refusal};
45use crate::collection::Id;
46use crate::cow::Shared;
47use crate::delta::{Delta, Touch};
48use crate::model::LocatedAt as _;
49use crate::model::{Doc, Model, ModelError, Slot, edit_whole, read_key, refresh_key};
50use crate::path::{Edit, EditOp, Path, Segment};
51
52/// An item of a [`Keyed`] or an [`Ordered`](crate::Ordered): what it is
53/// stored under, and how items sort in memory beyond that.
54pub trait Identified {
55    /// The item's identity: the key it is stored under.
56    fn id(&self) -> Id;
57
58    /// How two items sort in memory after their ids; the default keeps id
59    /// order. A timeline sorts its markers by time here.
60    fn order(&self, other: &Self) -> Ordering {
61        let _ = other;
62        Ordering::Equal
63    }
64}
65
66/// Items that carry their own ids, held as a plain `Vec<T>` in memory and
67/// stored the way `S` says: [`Keyed`] under their ids alone, in their own
68/// order; [`Ordered`](crate::Ordered) as someone arranged them.
69pub struct Items<T, S> {
70    /// Shared between clones until one of them changes the items.
71    stock: Shared<Stock<T>>,
72    storage: PhantomData<fn() -> S>,
73}
74
75/// The items, the id of each once a refresh has needed them, and what they
76/// were copied from.
77struct Stock<T> {
78    items: Vec<T>,
79    /// `ids[i]` is `items[i].id()`, except at the positions in `stale`. Kept
80    /// by the refreshes that read it, dropped whenever all the items are
81    /// handed out to change: whoever changes an item may change its id.
82    ids: Option<Vec<Arc<str>>>,
83    /// Positions, ascending, whose kept id may be out of date: items handed
84    /// out one at a time to change ([`Items::find_mut`]).
85    stale: Vec<usize>,
86    /// Which state of the items this is, a mark no other has had: made anew
87    /// whenever they are handed out to change, so items copied from these
88    /// can tell whether these are still as they were copied.
89    mark: u64,
90    /// The items these were copied from, and which of them changed since.
91    since: Option<Since>,
92}
93
94/// Items still as the ones they were copied from, except as noted: some
95/// changed in place, some removed, some added at the end. Nothing else
96/// changed: handing out all the items, or any change that moves one,
97/// forgets the copy.
98struct Since {
99    /// The [`Stock::mark`] of the items copied.
100    copied: u64,
101    /// How many of the items copied these still hold: `items[..held]` are
102    /// they, in the order copied. Every item past them was added at the end
103    /// ([`Items::push`]) under an id no item held then.
104    held: usize,
105    /// Positions among the items copied, ascending, of items still held
106    /// that were handed out one at a time to change ([`Items::find_mut`]).
107    changed: Vec<usize>,
108    /// Positions among the items copied, ascending, of items removed.
109    removed: Vec<usize>,
110    /// The id each item past `held` was added under, in order.
111    added: Vec<Arc<str>>,
112}
113
114impl Since {
115    fn new(copied: u64, held: usize) -> Self {
116        Self {
117            copied,
118            held,
119            changed: Vec::new(),
120            removed: Vec::new(),
121            added: Vec::new(),
122        }
123    }
124
125    /// The item at `at` was handed out to change. An item added since is
126    /// written whole whatever it holds, so only one copied is noted.
127    fn handed_out(&mut self, at: usize) {
128        if at < self.held {
129            note(&mut self.changed, copied_at(&self.removed, at));
130        }
131    }
132
133    /// The items at the positions `doomed` (ascending) are being removed.
134    fn removing(&mut self, doomed: &[usize]) {
135        let held = doomed.partition_point(|&at| at < self.held);
136        let (copied, added) = doomed.split_at(held);
137        // Where each was among the items copied, against the removals so far.
138        let mut gone = 0usize;
139        let mut origins = Vec::with_capacity(copied.len());
140        for &at in copied {
141            while self
142                .removed
143                .get(gone)
144                .is_some_and(|&removed| removed <= at.saturating_add(gone))
145            {
146                gone = gone.saturating_add(1);
147            }
148            origins.push(at.saturating_add(gone));
149        }
150        self.changed
151            .retain(|origin| origins.binary_search(origin).is_err());
152        // The added ones were never copied: they are simply no longer added.
153        let first_added = self.held;
154        let added: Vec<usize> = added
155            .iter()
156            .map(|at| at.saturating_sub(first_added))
157            .collect();
158        remove_positions(&mut self.added, &added);
159        self.held = self.held.saturating_sub(origins.len());
160        self.removed.extend_from_slice(&origins);
161        self.removed.sort_unstable();
162    }
163}
164
165/// The position among the items copied of the item now at `at`, one of
166/// those still held, given the positions `removed` (ascending) of the
167/// copied items removed since.
168fn copied_at(removed: &[usize], at: usize) -> usize {
169    let mut origin = at;
170    for &gone in removed {
171        if gone > origin {
172            break;
173        }
174        origin = origin.saturating_add(1);
175    }
176    origin
177}
178
179/// Remove the elements at the positions `doomed` (ascending) of `items`.
180fn remove_positions<X>(items: &mut Vec<X>, doomed: &[usize]) {
181    if doomed.is_empty() {
182        return;
183    }
184    let mut at = 0usize;
185    let mut next = doomed.iter().peekable();
186    items.retain(|_| {
187        let gone = next.next_if_eq(&&at).is_some();
188        at = at.saturating_add(1);
189        !gone
190    });
191}
192
193/// What changed in items since they were copied ([`Stock::changed_since`]).
194#[derive(Clone, Copy)]
195struct Changes<'a> {
196    /// Positions among the items copied, ascending, of items held that may
197    /// have changed in place.
198    changed: &'a [usize],
199    /// Positions among the items copied, ascending, of items removed.
200    removed: &'a [usize],
201    /// How many of the items copied are held: the ones past them were added
202    /// at the end, under the ids `added`.
203    held: usize,
204    added: &'a [Arc<str>],
205}
206
207impl Changes<'_> {
208    /// No change to `count` items.
209    fn none(count: usize) -> Self {
210        Changes {
211            changed: &[],
212            removed: &[],
213            held: count,
214            added: &[],
215        }
216    }
217}
218
219/// A [`Stock::mark`] no other stock has had.
220fn fresh_mark() -> u64 {
221    static NEXT: AtomicU64 = AtomicU64::new(0);
222    NEXT.fetch_add(1, Atomic::Relaxed)
223}
224
225/// Add `at` to the ascending positions `positions`, once.
226fn note(positions: &mut Vec<usize>, at: usize) {
227    if let Err(slot) = positions.binary_search(&at) {
228        positions.insert(slot, at);
229    }
230}
231
232impl<T> Stock<T> {
233    fn new(items: Vec<T>) -> Self {
234        Self {
235            items,
236            ids: None,
237            stale: Vec::new(),
238            mark: fresh_mark(),
239            since: None,
240        }
241    }
242
243    /// All the items, to change: their ids, and what they were copied
244    /// from, are no longer known.
245    fn all_mut(&mut self) -> &mut Vec<T> {
246        self.mark = fresh_mark();
247        self.ids = None;
248        self.stale.clear();
249        self.since = None;
250        &mut self.items
251    }
252
253    /// The item at `at`, to change; the copy remembers it changed.
254    fn one_mut(&mut self, at: usize) -> Option<&mut T> {
255        if at >= self.items.len() {
256            return None;
257        }
258        self.mark = fresh_mark();
259        if self.ids.is_some() {
260            note(&mut self.stale, at);
261        }
262        if let Some(since) = &mut self.since {
263            since.handed_out(at);
264        }
265        self.items.get_mut(at)
266    }
267
268    /// Forget the items at the positions `doomed` (ascending, each held)
269    /// everywhere but in the items themselves; the copy remembers they
270    /// left.
271    fn forget(&mut self, doomed: &[usize]) {
272        self.mark = fresh_mark();
273        if let Some(since) = &mut self.since {
274            since.removing(doomed);
275        }
276        if let Some(ids) = &mut self.ids {
277            remove_positions(ids, doomed);
278        }
279        self.stale = self
280            .stale
281            .iter()
282            .filter_map(|&at| match doomed.binary_search(&at) {
283                Ok(_) => None,
284                Err(before) => Some(at.saturating_sub(before)),
285            })
286            .collect();
287    }
288
289    /// Remove the items at the positions `doomed` (ascending, each held).
290    fn remove_all(&mut self, doomed: &[usize]) {
291        if doomed.is_empty() {
292            return;
293        }
294        self.forget(doomed);
295        remove_positions(&mut self.items, doomed);
296    }
297
298    /// Remove the item at `at`, which is held.
299    fn remove_one(&mut self, at: usize) -> T {
300        self.forget(&[at]);
301        self.items.remove(at)
302    }
303
304    /// What changed since these items were copied from `origin`, when they
305    /// were and `origin` is still as it was then.
306    fn changed_since(&self, origin: &Self) -> Option<Changes<'_>> {
307        let since = self.since.as_ref()?;
308        let still_as_copied = since.copied == origin.mark
309            && origin.items.len() == since.held.saturating_add(since.removed.len())
310            && self.items.len() == since.held.saturating_add(since.added.len());
311        still_as_copied.then_some(Changes {
312            changed: since.changed.as_slice(),
313            removed: since.removed.as_slice(),
314            held: since.held,
315            added: since.added.as_slice(),
316        })
317    }
318}
319
320impl<T: Identified> Stock<T> {
321    /// The kept ids, brought up to date where an item handed out may have
322    /// changed its id; taken, to be put back.
323    fn take_ids(&mut self) -> Option<Vec<Arc<str>>> {
324        let mut ids = self.ids.take()?;
325        for at in self.stale.drain(..) {
326            if let (Some(held), Some(item)) = (ids.get_mut(at), self.items.get(at)) {
327                let id = item.id();
328                if **held != *id.as_str() {
329                    *held = Arc::from(id.as_str());
330                }
331            }
332        }
333        Some(ids)
334    }
335}
336
337impl<T> Default for Stock<T> {
338    fn default() -> Self {
339        Self::new(Vec::new())
340    }
341}
342
343impl<T: Clone> Clone for Stock<T> {
344    /// The copy made to change items another holder still shares: the ids
345    /// come along (a pointer each), and the copy remembers these items as
346    /// what it was copied from.
347    fn clone(&self) -> Self {
348        Self {
349            items: self.items.clone(),
350            ids: self.ids.clone(),
351            stale: self.stale.clone(),
352            mark: fresh_mark(),
353            since: Some(Since::new(self.mark, self.items.len())),
354        }
355    }
356}
357
358/// The id of each of `items`, asked once.
359fn ids_of<T: Identified>(items: &[T]) -> Vec<Arc<str>> {
360    items
361        .iter()
362        .map(|item| Arc::from(item.id().as_str()))
363        .collect()
364}
365
366/// How two items sort in memory, given their ids: by
367/// [`Identified::order`], then by id.
368fn in_order<T: Identified>(a: (&T, &str), b: (&T, &str)) -> Ordering {
369    a.0.order(b.0).then_with(|| a.1.cmp(b.1))
370}
371
372/// Sort `items` and their `ids` alike, as a read from the document does: by
373/// [`Identified::order`], then id. Stable, so this is a sort by id followed
374/// by a stable sort by order; items already in place are not moved.
375/// Whether any moved.
376fn settle_with_ids<T: Identified>(items: &mut [T], ids: &mut [Arc<str>]) -> bool {
377    let held = || items.iter().zip(ids.iter().map(|id| &**id));
378    if held()
379        .zip(held().skip(1))
380        .all(|(a, b)| in_order(a, b).is_le())
381    {
382        return false;
383    }
384    let swaps = {
385        let (held, held_ids): (&[T], &[Arc<str>]) = (items, ids);
386        crate::sort::swaps_to_sort(held.len(), &mut |a, b| match (
387            held.get(a).zip(held_ids.get(a)),
388            held.get(b).zip(held_ids.get(b)),
389        ) {
390            (Some((a, a_id)), Some((b, b_id))) => in_order((a, &**a_id), (b, &**b_id)),
391            _ => Ordering::Equal,
392        })
393    };
394    for (a, b) in swaps {
395        items.swap(a, b);
396        ids.swap(a, b);
397    }
398    true
399}
400
401/// Items stored under the ids they carry. See the module docs.
402pub type Keyed<T> = Items<T, ById>;
403
404/// How [`Items`] are stored: the parts of their [`Model`] that differ.
405pub trait ItemStorage: 'static {
406    /// Whether the items keep an order someone arranged.
407    const ARRANGED: bool;
408    /// What a stored value that is not of this storage is called in errors.
409    const NAME: &'static str;
410
411    fn load<T: Model + Identified>(doc: &Doc, map: &ObjId) -> Result<Vec<T>, ModelError>;
412
413    /// Write `items` into `slot`.
414    fn store<T: Model + Identified>(
415        items: &[T],
416        doc: &mut Doc,
417        slot: Slot<'_>,
418    ) -> Result<(), ModelError>;
419
420    /// Bring `items` up to date after `delta`; the default reads them again.
421    #[inline(never)]
422    fn refresh<T: Model + Identified>(
423        items: &mut Vec<T>,
424        doc: &Doc,
425        map: &ObjId,
426        delta: &Delta,
427    ) -> Result<(), ModelError> {
428        if delta.touches(map) {
429            *items = Self::load(doc, map)?;
430        }
431        Ok(())
432    }
433
434    /// [`refresh`](Self::refresh), given the id of each item when known
435    /// (`ids[i]` is `items[i].id()`) and leaving them known when it can.
436    /// The default forgets them and refreshes.
437    ///
438    /// # Errors
439    /// Returns an item that does not read; `ids` is then unknown.
440    fn refresh_with_ids<T: Model + Identified>(
441        items: &mut Vec<T>,
442        ids: &mut Option<Vec<Arc<str>>>,
443        doc: &Doc,
444        map: &ObjId,
445        delta: &Delta,
446    ) -> Result<(), ModelError> {
447        *ids = None;
448        Self::refresh(items, doc, map, delta)
449    }
450
451    /// [`Self::diff`] over items whose type a table describes, compiled
452    /// once for every item type.
453    #[doc(hidden)]
454    const DIFF: ErasedDiff;
455
456    /// The edits that turn `before` into `after`, below `path`.
457    fn diff<T: Model + Identified, R>(
458        before: &[T],
459        after: &[T],
460        path: &[Segment],
461        out: &mut Vec<Edit<R>>,
462    ) {
463        let mut found = Vec::new();
464        Self::DIFF(T::TABLE, (&Rows(before), &Rows(after)), path, &mut found);
465        out.extend(found.into_iter().map(Edit::retyped));
466    }
467}
468
469/// [`ItemStorage::diff`] with the item type erased: the edits turning the
470/// items `before` into `after`, whose type the table describes, below a
471/// path.
472#[doc(hidden)]
473pub type ErasedDiff = fn(
474    &'static crate::table::ModelTable,
475    (
476        &dyn crate::collection::ItemList,
477        &dyn crate::collection::ItemList,
478    ),
479    &[Segment],
480    &mut Vec<Edit<()>>,
481);
482
483/// [`Keyed`] storage: each item under its id, in memory by id and then
484/// [`Identified::order`].
485#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
486pub struct ById;
487
488impl<T: Clone, S> Clone for Items<T, S> {
489    /// Shares the items, however many: the first of the clones to change
490    /// them copies them.
491    fn clone(&self) -> Self {
492        Self {
493            stock: self.stock.share(),
494            storage: PhantomData,
495        }
496    }
497}
498
499impl<T: std::fmt::Debug, S> std::fmt::Debug for Items<T, S> {
500    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
501        self.items().fmt(f)
502    }
503}
504
505impl<T: PartialEq, S> PartialEq for Items<T, S> {
506    /// Items two clones still share are the same and not compared one by
507    /// one.
508    fn eq(&self, other: &Self) -> bool {
509        self.stock.same(&other.stock) || self.items() == other.items()
510    }
511}
512
513impl<T, S> Default for Items<T, S> {
514    fn default() -> Self {
515        Self::from(Vec::new())
516    }
517}
518
519impl<T, S> Items<T, S> {
520    fn items(&self) -> &Vec<T> {
521        &self.stock.get().items
522    }
523
524    /// The items, to change: copied first when a clone still shares them.
525    /// Their ids are forgotten, as the change may change one.
526    fn items_mut(&mut self) -> &mut Vec<T> {
527        self.stock.make_mut().all_mut()
528    }
529}
530
531impl<T, S> Deref for Items<T, S> {
532    type Target = Vec<T>;
533    fn deref(&self) -> &Vec<T> {
534        self.items()
535    }
536}
537
538impl<T, S> DerefMut for Items<T, S> {
539    /// The items, to change: copied first when a clone still shares them.
540    fn deref_mut(&mut self) -> &mut Vec<T> {
541        self.items_mut()
542    }
543}
544
545impl<T, S> From<Vec<T>> for Items<T, S> {
546    fn from(items: Vec<T>) -> Self {
547        Self {
548            stock: Shared::new(Stock::new(items)),
549            storage: PhantomData,
550        }
551    }
552}
553
554impl<T, S> FromIterator<T> for Items<T, S> {
555    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
556        Self::from(iter.into_iter().collect::<Vec<_>>())
557    }
558}
559
560impl<T, S> IntoIterator for Items<T, S> {
561    type Item = T;
562    type IntoIter = std::vec::IntoIter<T>;
563    fn into_iter(self) -> Self::IntoIter {
564        self.stock.into_inner().items.into_iter()
565    }
566}
567
568impl<'a, T, S> IntoIterator for &'a Items<T, S> {
569    type Item = &'a T;
570    type IntoIter = std::slice::Iter<'a, T>;
571    fn into_iter(self) -> Self::IntoIter {
572        self.items().iter()
573    }
574}
575
576impl<'a, T, S> IntoIterator for &'a mut Items<T, S> {
577    type Item = &'a mut T;
578    type IntoIter = std::slice::IterMut<'a, T>;
579    fn into_iter(self) -> Self::IntoIter {
580        self.items_mut().iter_mut()
581    }
582}
583
584impl<T: serde::Serialize, S> serde::Serialize for Items<T, S> {
585    fn serialize<Ser: serde::Serializer>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error> {
586        self.items().serialize(serializer)
587    }
588}
589
590impl<'de, T: serde::Deserialize<'de>, S> serde::Deserialize<'de> for Items<T, S> {
591    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
592        Vec::<T>::deserialize(deserializer).map(Self::from)
593    }
594}
595
596impl<T: crate::JsonSchema, S> crate::JsonSchema for Items<T, S> {
597    fn json_schema() -> serde_json::Value {
598        crate::schema::array(T::json_schema())
599    }
600    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
601        crate::FieldType::Collection(Box::new(T::field_type(types)))
602    }
603}
604
605impl<T: Identified, S> Items<T, S> {
606    #[must_use]
607    pub fn new() -> Self {
608        Self::default()
609    }
610
611    pub fn position_of(&self, id: &Id) -> Option<usize> {
612        let stock = self.stock.get();
613        match &stock.ids {
614            Some(ids) if stock.stale.is_empty() => {
615                ids.iter().position(|held| **held == *id.as_str())
616            }
617            // An item handed out to change is asked: its id may have changed.
618            Some(ids) => ids.iter().enumerate().position(|(at, held)| {
619                if stock.stale.binary_search(&at).is_ok() {
620                    stock.items.get(at).is_some_and(|item| &item.id() == id)
621                } else {
622                    **held == *id.as_str()
623                }
624            }),
625            None => stock.items.iter().position(|item| &item.id() == id),
626        }
627    }
628
629    pub fn find(&self, id: &Id) -> Option<&T> {
630        self.items().get(self.position_of(id)?)
631    }
632
633    /// The item `id`, to change. The items are copied first when a clone
634    /// still shares them, and only when the item is there; the copy
635    /// remembers which items changed, so comparing it with what it was
636    /// copied from compares only those. The ids asked to find it are kept,
637    /// so finding the next one asks none.
638    pub fn find_mut(&mut self, id: &Id) -> Option<&mut T> {
639        let learned = self.stock.get().ids.is_none().then(|| ids_of(self.items()));
640        let at = match &learned {
641            Some(ids) => ids.iter().position(|held| **held == *id.as_str())?,
642            None => self.position_of(id)?,
643        };
644        let stock = self.stock.make_mut();
645        if learned.is_some() {
646            stock.ids = learned;
647        }
648        stock.one_mut(at)
649    }
650
651    /// The item at position `at`, to change, remembered as
652    /// [`find_mut`](Self::find_mut) remembers it: changing a few items
653    /// picked by position costs those items, where changing them through
654    /// `iter_mut` hands out every item.
655    pub fn at_mut(&mut self, at: usize) -> Option<&mut T> {
656        if at >= self.items().len() {
657            return None;
658        }
659        self.stock.make_mut().one_mut(at)
660    }
661
662    /// Add `item` at the end, as `Vec::push` does. The items are copied
663    /// first when a clone still shares them; the copy remembers the item
664    /// came, so comparing it with what it was copied from, or saving it over
665    /// that, visits the items changed and added rather than every item. An
666    /// id the items already hold is no addition but items leaving and
667    /// coming, which only comparing them all can tell: the copy forgets
668    /// what it was copied from. The ids kept beside the items are kept.
669    pub fn push(&mut self, item: T) {
670        let stock = self.stock.make_mut();
671        if stock.since.is_some() || stock.ids.is_some() {
672            let id = item.id();
673            if stock.since.is_some() {
674                // The ids, learned when unknown, to tell an addition.
675                let ids = stock.take_ids().unwrap_or_else(|| ids_of(&stock.items));
676                if ids.iter().any(|held| **held == *id.as_str()) {
677                    stock.since = None;
678                }
679                stock.ids = Some(ids);
680            }
681            let id: Arc<str> = Arc::from(id.as_str());
682            if let Some(since) = &mut stock.since {
683                since.added.push(Arc::clone(&id));
684            }
685            if let Some(ids) = &mut stock.ids {
686                ids.push(id);
687            }
688        }
689        stock.mark = fresh_mark();
690        stock.items.push(item);
691    }
692
693    /// Remove the item `id`. The items are copied first when a clone still
694    /// shares them, and only when the item is there; the copy remembers the
695    /// item left, so comparing it with what it was copied from, or saving
696    /// it over that, visits the items removed rather than every item.
697    pub fn take(&mut self, id: &Id) -> Option<T> {
698        let at = self.position_of(id)?;
699        Some(self.stock.make_mut().remove_one(at))
700    }
701
702    /// Remove and return the item at `at`, as `Vec::remove` does, and
703    /// remember it left as [`take`](Self::take) does.
704    ///
705    /// # Panics
706    /// When `at` is past the items, as `Vec::remove` does.
707    pub fn remove(&mut self, at: usize) -> T {
708        let stock = self.stock.make_mut();
709        if at >= stock.items.len() {
710            // Out of range: `Vec::remove` says so.
711            return stock.all_mut().remove(at);
712        }
713        stock.remove_one(at)
714    }
715
716    /// Keep only the items `keep` accepts, asking it once for each item in
717    /// order, as `Vec::retain` does. Items it keeps all are not copied or
718    /// changed; otherwise the copy remembers which items left, as
719    /// [`take`](Self::take) does.
720    pub fn retain(&mut self, mut keep: impl FnMut(&T) -> bool) {
721        let doomed: Vec<usize> = self
722            .items()
723            .iter()
724            .enumerate()
725            .filter_map(|(at, item)| (!keep(item)).then_some(at))
726            .collect();
727        if !doomed.is_empty() {
728            self.stock.make_mut().remove_all(&doomed);
729        }
730    }
731}
732
733impl<T: Identified> Keyed<T> {
734    /// Sort as a read from the document does: by id, then [`Identified::order`].
735    pub fn settle(&mut self) {
736        let stock = self.stock.make_mut();
737        let mut ids = stock.take_ids().unwrap_or_else(|| ids_of(&stock.items));
738        if settle_with_ids(&mut stock.items, &mut ids) {
739            // Moved: no longer as they were copied, position by position.
740            stock.mark = fresh_mark();
741            stock.since = None;
742        }
743        stock.ids = Some(ids);
744    }
745}
746
747impl<R, T: Model + Identified, S> Path<R, Items<T, S>> {
748    /// The item `id`, its own paths rooted here.
749    #[must_use]
750    pub fn item(&self, id: &Id) -> T::Paths<R> {
751        T::paths_at(self.child(Segment::Item(id.clone())))
752    }
753
754    #[must_use]
755    pub fn item_path(&self, id: &Id) -> Path<R, T> {
756        self.child(Segment::Item(id.clone()))
757    }
758
759    #[must_use]
760    pub fn remove(&self, id: &Id) -> Edit<R> {
761        self.edit(EditOp::RemoveItem { id: id.clone() })
762    }
763}
764
765impl<R, T: Model + Identified> Path<R, Keyed<T>> {
766    /// The edits that make the item `after` what it is: added when `before`
767    /// is `None`, else changed field by field from `before`.
768    #[must_use]
769    pub fn upsert(&self, before: Option<&T>, after: &T) -> Vec<Edit<R>> {
770        match before {
771            Some(before) => self.item_path(&after.id()).edits(before, after),
772            None => vec![self.insert(after)],
773        }
774    }
775
776    /// Add `item` under its own id.
777    #[must_use]
778    pub fn insert(&self, item: &T) -> Edit<R> {
779        self.edit(EditOp::InsertItem {
780            id: Some(item.id()),
781            at: crate::At::Index(0),
782            value: item.to_json(),
783        })
784    }
785}
786
787impl ItemStorage for ById {
788    const ARRANGED: bool = false;
789    const NAME: &'static str = "keyed items";
790
791    #[inline(never)]
792    fn load<T: Model + Identified>(doc: &Doc, map: &ObjId) -> Result<Vec<T>, ModelError> {
793        let mut items = doc
794            .keys(map)
795            .map(|key| read_key::<T>(doc, map, &key))
796            .collect::<Result<Vec<_>, _>>()?;
797        crate::sort::sort_by(&mut items, T::order);
798        Ok(items)
799    }
800
801    fn store<T: Model + Identified>(
802        items: &[T],
803        doc: &mut Doc,
804        slot: Slot<'_>,
805    ) -> Result<(), ModelError> {
806        store_by_id_in(T::TABLE, &Rows(items), doc, slot)
807    }
808
809    #[inline(never)]
810    fn refresh<T: Model + Identified>(
811        items: &mut Vec<T>,
812        doc: &Doc,
813        map: &ObjId,
814        delta: &Delta,
815    ) -> Result<(), ModelError> {
816        Self::refresh_with_ids(items, &mut None, doc, map, delta)
817    }
818
819    /// Finds each touched item by the id kept beside it and asks only the
820    /// items it read for their ids; sorts only when they are out of place.
821    #[inline(never)]
822    fn refresh_with_ids<T: Model + Identified>(
823        items: &mut Vec<T>,
824        known: &mut Option<Vec<Arc<str>>>,
825        doc: &Doc,
826        map: &ObjId,
827        delta: &Delta,
828    ) -> Result<(), ModelError> {
829        let touched = delta.under(map);
830        if touched.is_all() {
831            *known = None;
832            *items = Self::load(doc, map)?;
833            *known = Some(ids_of(items));
834            return Ok(());
835        }
836        let mut ids = known.take().unwrap_or_else(|| ids_of(items));
837        let mut changed = false;
838        for key in touched.keys() {
839            let at = ids.iter().position(|id| **id == *key);
840            match (doc.get(map, key)?, at) {
841                (None, Some(at)) => {
842                    items.remove(at);
843                    ids.remove(at);
844                    changed = true;
845                }
846                (None, None) => {}
847                (Some(_), Some(at)) => {
848                    if let (Some(item), Some(held)) = (items.get_mut(at), ids.get_mut(at)) {
849                        refresh_key(item, doc, map, key, delta)?;
850                        let id = item.id();
851                        if **held != *id.as_str() {
852                            *held = Arc::from(id.as_str());
853                        }
854                    }
855                    changed = true;
856                }
857                (Some(_), None) => {
858                    let item: T = read_key(doc, map, key)?;
859                    ids.push(Arc::from(item.id().as_str()));
860                    items.push(item);
861                    changed = true;
862                }
863            }
864        }
865        if changed {
866            settle_with_ids(items, &mut ids);
867        }
868        *known = Some(ids);
869        Ok(())
870    }
871
872    const DIFF: ErasedDiff = diff_by_id_in;
873}
874
875/// [`ById::diff`] over items whose type `table` describes, compiled once for
876/// every item type.
877#[inline(never)]
878fn diff_by_id_in(
879    table: &'static crate::table::ModelTable,
880    (before, after): (
881        &dyn crate::collection::ItemList,
882        &dyn crate::collection::ItemList,
883    ),
884    path: &[Segment],
885    out: &mut Vec<Edit<()>>,
886) {
887    let after_ids: Vec<Id> = (0..after.count())
888        .filter_map(|at| Some(after.item(at)?.0))
889        .collect();
890    let before_ids = removed_and_changed_in(table, (before, after), &after_ids, path, out);
891    let held: HashSet<&Id> = before_ids.iter().collect();
892    for (at, id) in after_ids.iter().enumerate() {
893        if held.contains(id) {
894            continue;
895        }
896        let Some((_, item)) = after.item(at) else {
897            continue;
898        };
899        out.push(Edit::new(
900            path.to_vec(),
901            EditOp::InsertItem {
902                id: Some(id.clone()),
903                at: crate::At::Index(0),
904                value: (table.ops.to_json)(table, item),
905            },
906        ));
907    }
908}
909
910/// [`Keyed`] editing: an item lives under its id, in no entry of its own.
911fn edit_by_id(
912    doc: &mut Doc,
913    slot: Slot<'_>,
914    path: &[Segment],
915    op: &EditOp,
916    cx: &mut ActionCx,
917    edits: &crate::collection::EntryEdits<'_>,
918) -> Result<(), ModelError> {
919    match (path.split_first(), op) {
920        (Some((Segment::Item(id), rest)), _) => {
921            let map = slot.object(doc, ObjType::Map)?;
922            if doc.get(&map, id.as_str())?.is_none() {
923                return Err(ModelError::invalid(format!("no item `{id}`")));
924            }
925            (edits.item)(doc, Slot::Key(&map, id.as_str()), rest, op, cx).located(id.as_str())
926        }
927        (None, EditOp::InsertItem { value, .. }) => {
928            let (id, item) = (edits.parse)(value)?;
929            let id = id.unwrap_or_else(|| cx.id());
930            let map = slot.object(doc, ObjType::Map)?;
931            if doc.get(&map, id.as_str())?.is_some() {
932                return Err(ModelError::invalid(format!("an item `{id}` exists")));
933            }
934            item.store_to(doc, Slot::Key(&map, id.as_str()))
935                .located(id.as_str())
936        }
937        (None, EditOp::RemoveItem { id }) => {
938            let map = slot.object(doc, ObjType::Map)?;
939            if doc.get(&map, id.as_str())?.is_none() {
940                return Err(ModelError::invalid(format!("no item `{id}`")));
941            }
942            doc.delete(&map, id.as_str())?;
943            Ok(())
944        }
945        (
946            None,
947            EditOp::UpsertItem {
948                matching,
949                value,
950                id,
951            },
952        ) => {
953            let map = slot.object(doc, ObjType::Map)?;
954            let mut candidates = Vec::new();
955            for key in doc.keys(&map).collect::<Vec<_>>() {
956                if let Some((automerge::Value::Object(ObjType::Map), fields)) =
957                    doc.get(&map, key.as_str())?
958                {
959                    candidates.push(crate::upsert::Candidate {
960                        id: Id::from_raw(key),
961                        fields,
962                    });
963                }
964            }
965            if let Some(item) = crate::upsert::matching_one(doc, &candidates, matching)? {
966                for (key, field) in crate::upsert::changed_fields(doc, &item.fields, value)? {
967                    (edits.item)(
968                        doc,
969                        Slot::Key(&map, item.id.as_str()),
970                        &[Segment::Field(key)],
971                        &EditOp::Set { value: field },
972                        cx,
973                    )
974                    .located(item.id.as_str())?;
975                }
976                return Ok(());
977            }
978            let insert = crate::collection::upserted(doc, &map, matching, value, id.as_ref())?;
979            edit_by_id(doc, slot, path, &insert, cx, edits)
980        }
981        _ => (edits.whole)(doc, slot, path, op),
982    }
983}
984
985/// The edits removing what `after` lacks and changing what both hold, given
986/// the id of each item of `after`, for items whose type `table` describes;
987/// returns the id of each item of `before`. Compiled once for every item
988/// type.
989#[inline(never)]
990pub(crate) fn removed_and_changed_in(
991    table: &'static crate::table::ModelTable,
992    (before, after): (
993        &dyn crate::collection::ItemList,
994        &dyn crate::collection::ItemList,
995    ),
996    after_ids: &[Id],
997    path: &[Segment],
998    out: &mut Vec<Edit<()>>,
999) -> Vec<Id> {
1000    let mut found: HashMap<&str, usize> = HashMap::with_capacity(after_ids.len());
1001    for (at, id) in after_ids.iter().enumerate() {
1002        found.entry(id.as_str()).or_insert(at);
1003    }
1004    let mut before_ids = Vec::with_capacity(before.count());
1005    for at in 0..before.count() {
1006        let Some((id, item)) = before.item(at) else {
1007            continue;
1008        };
1009        match found.get(id.as_str()).and_then(|at| after.item(*at)) {
1010            Some((_, next)) => {
1011                let mut at = path.to_vec();
1012                at.push(Segment::Item(id.clone()));
1013                (table.ops.diff)(table, item, next, &at, out);
1014            }
1015            None => out.push(Edit::new(
1016                path.to_vec(),
1017                EditOp::RemoveItem { id: id.clone() },
1018            )),
1019        }
1020        before_ids.push(id);
1021    }
1022    before_ids
1023}
1024
1025/// Items as the type-erased list the functions compiled once read.
1026struct Rows<'a, T>(&'a [T]);
1027
1028impl<T: Identified + 'static> crate::collection::ItemList for Rows<'_, T> {
1029    fn count(&self) -> usize {
1030        self.0.len()
1031    }
1032
1033    fn item(&self, at: usize) -> Option<(Id, &dyn std::any::Any)> {
1034        let item = self.0.get(at)?;
1035        Some((item.id(), item as &dyn std::any::Any))
1036    }
1037}
1038
1039/// What a copy's [`Changes`] come to, item by item: what comparing every
1040/// item would find, found without visiting the others.
1041struct Plan {
1042    /// The items copied that changed in place or left, in the order copied.
1043    steps: Vec<Step>,
1044    /// The id of each item added at the end, in order.
1045    added: Vec<Id>,
1046}
1047
1048/// An item copied that changed in place, or left.
1049struct Step {
1050    /// Where it was among the items copied.
1051    was: usize,
1052    /// Where it is now; `None` when it left.
1053    now: Option<usize>,
1054    id: Id,
1055}
1056
1057/// The [`Plan`] of the changes `changes` between `before` and `after`;
1058/// `None` when an item changed its id (or one added since did), or one was
1059/// added under the id of one removed: then items left and came, which only
1060/// comparing them all can tell.
1061#[inline(never)]
1062fn plan(
1063    before: &dyn crate::collection::ItemList,
1064    after: &dyn crate::collection::ItemList,
1065    changes: Changes<'_>,
1066) -> Option<Plan> {
1067    let mut steps = Vec::with_capacity(changes.changed.len().saturating_add(changes.removed.len()));
1068    let (mut in_place, mut left) = (changes.changed.iter(), changes.removed.iter());
1069    let (mut next_changed, mut next_removed) = (in_place.next(), left.next());
1070    let mut gone = 0usize;
1071    loop {
1072        match (next_changed, next_removed) {
1073            (None, None) => break,
1074            (Some(&was), next) if next.is_none_or(|&removed| was < removed) => {
1075                let now = was.checked_sub(gone)?;
1076                let (id, _) = before.item(was)?;
1077                if after.item(now)?.0 != id {
1078                    return None;
1079                }
1080                steps.push(Step {
1081                    was,
1082                    now: Some(now),
1083                    id,
1084                });
1085                next_changed = in_place.next();
1086            }
1087            (_, Some(&was)) => {
1088                steps.push(Step {
1089                    was,
1090                    now: None,
1091                    id: before.item(was)?.0,
1092                });
1093                gone = gone.saturating_add(1);
1094                next_removed = left.next();
1095            }
1096            (Some(_), None) => return None,
1097        }
1098    }
1099    if after.count() < changes.held {
1100        return None;
1101    }
1102    let mut added = Vec::with_capacity(changes.added.len());
1103    for (at, came) in (changes.held..after.count()).zip(changes.added) {
1104        let (id, _) = after.item(at)?;
1105        if *id.as_str() != **came {
1106            return None;
1107        }
1108        added.push(id);
1109    }
1110    if !added.is_empty() && !changes.removed.is_empty() {
1111        let left: HashSet<&Id> = steps
1112            .iter()
1113            .filter(|step| step.now.is_none())
1114            .map(|step| &step.id)
1115            .collect();
1116        if added.iter().any(|id| left.contains(id)) {
1117            return None;
1118        }
1119    }
1120    Some(Plan { steps, added })
1121}
1122
1123/// The edits between `before` and `after`, which holds the same items in
1124/// the same order except as `changes` says: each item copied that changed
1125/// in place, field by field, or left, then each added one, in the order
1126/// [`ItemStorage::diff`] would list them (an [`Ordered`](crate::Ordered)
1127/// item inserted at its position, `arranged`). `false`, with nothing
1128/// written, when only comparing every item can tell ([`plan`]). For items
1129/// whose type `table` describes, compiled once for every item type.
1130#[inline(never)]
1131fn diff_changed_in(
1132    table: &'static crate::table::ModelTable,
1133    (before, after): (
1134        &dyn crate::collection::ItemList,
1135        &dyn crate::collection::ItemList,
1136    ),
1137    changes: Changes<'_>,
1138    arranged: bool,
1139    (path, out): (&[Segment], &mut Vec<Edit<()>>),
1140) -> bool {
1141    let Some(plan) = plan(before, after, changes) else {
1142        return false;
1143    };
1144    let mut at = Vec::with_capacity(path.len().saturating_add(1));
1145    at.extend_from_slice(path);
1146    for step in plan.steps {
1147        match step.now {
1148            Some(now) => {
1149                if let (Some((_, was)), Some((_, now))) = (before.item(step.was), after.item(now)) {
1150                    at.push(Segment::Item(step.id));
1151                    (table.ops.diff)(table, was, now, &at, out);
1152                    at.pop();
1153                }
1154            }
1155            None => out.push(Edit::new(path.to_vec(), EditOp::RemoveItem { id: step.id })),
1156        }
1157    }
1158    for (offset, id) in plan.added.into_iter().enumerate() {
1159        let index = changes.held.saturating_add(offset);
1160        let Some((_, item)) = after.item(index) else {
1161            continue;
1162        };
1163        out.push(Edit::new(
1164            path.to_vec(),
1165            EditOp::InsertItem {
1166                id: Some(id),
1167                at: crate::At::Index(if arranged { index } else { 0 }),
1168                value: (table.ops.to_json)(table, item),
1169            },
1170        ));
1171    }
1172    true
1173}
1174
1175/// [`Model::diff`] of [`Items`] whose type `table` describes, stored as
1176/// `diff` and `arranged` say: from `changes` when the copy's changes tell,
1177/// comparing every item otherwise. Compiled once for every item type.
1178#[inline(never)]
1179fn diff_items_in(
1180    (table, diff, arranged): (&'static crate::table::ModelTable, ErasedDiff, bool),
1181    lists: (
1182        &dyn crate::collection::ItemList,
1183        &dyn crate::collection::ItemList,
1184    ),
1185    changes: Option<Changes<'_>>,
1186    path: &[Segment],
1187    out: &mut Vec<Edit<()>>,
1188) {
1189    if let Some(changes) = changes
1190        && diff_changed_in(table, lists, changes, arranged, (path, &mut *out))
1191    {
1192        return;
1193    }
1194    diff(table, lists, path, out);
1195}
1196
1197/// Finds an item by id.
1198type PositionOf<'a> = &'a dyn Fn(&Id) -> Option<usize>;
1199
1200/// Writes items whole into a slot.
1201type StoreWhole<'a> = &'a dyn Fn(&mut Doc, Slot<'_>) -> Result<(), ModelError>;
1202
1203/// [`Model::store_changed`] of [`Items`] `now` over the items `was` they
1204/// were copied from, changed as `changes` says when known, whose type
1205/// `table` describes and stored arranged or not: only what changed when the
1206/// changes tell, the whole items through `store` otherwise. `position_of`
1207/// finds an item of `now` by id. Compiled once for every item type.
1208#[inline(never)]
1209fn store_items_changed_in(
1210    (table, arranged): (&'static crate::table::ModelTable, bool),
1211    lists: (
1212        &dyn crate::collection::ItemList,
1213        &dyn crate::collection::ItemList,
1214    ),
1215    changes: Option<Changes<'_>>,
1216    (position_of, store): (PositionOf<'_>, StoreWhole<'_>),
1217    (doc, slot, dirty): (&mut Doc, Slot<'_>, &Delta),
1218) -> Result<(), ModelError> {
1219    match changes {
1220        Some(changes) if !arranged => {
1221            store_by_id_changed_in(table, position_of, lists, changes, (doc, slot, dirty))
1222        }
1223        Some(changes) => {
1224            if store_arranged_changed_in(table, lists, changes, (doc, slot, dirty))? {
1225                return Ok(());
1226            }
1227            store(doc, slot)
1228        }
1229        None => store(doc, slot),
1230    }
1231}
1232
1233/// Hand each item of the JSON form of [`Items`] to `read`: a list of
1234/// items, or `null` for none.
1235/// Compiled once for every item type.
1236///
1237/// # Errors
1238/// Returns that `value` is no list of items, or the first item that does
1239/// not read.
1240#[inline(never)]
1241fn each_item_json(
1242    value: &serde_json::Value,
1243    read: &mut dyn FnMut(&serde_json::Value) -> Result<(), ModelError>,
1244) -> Result<(), ModelError> {
1245    match value {
1246        serde_json::Value::Array(items) => items.iter().try_for_each(read),
1247        serde_json::Value::Null => Ok(()),
1248        _ => Err(ModelError::shape("a list of items")),
1249    }
1250}
1251
1252/// Write `item`, which `held` was, under `key` of `map`, as
1253/// [`write_key_changed`](crate::model::write_key_changed) writes it, for
1254/// items whose type `table` describes.
1255fn write_item_changed(
1256    table: &'static crate::table::ModelTable,
1257    (doc, map, key): (&mut Doc, &ObjId, &str),
1258    item: &dyn std::any::Any,
1259    held: &dyn std::any::Any,
1260    dirty: &Delta,
1261) -> Result<(), ModelError> {
1262    match dirty.key(map, key) {
1263        Touch::Written => (table.ops.store)(table, item, doc, Slot::Key(map, key)).located(key),
1264        Touch::Untouched if (table.ops.stores_as)(table, item, held) => Ok(()),
1265        Touch::Untouched | Touch::Below => {
1266            (table.ops.store_changed)(table, item, held, doc, Slot::Key(map, key), dirty)
1267                .located(key)
1268        }
1269    }
1270}
1271
1272/// [`Model::store_changed`] of [`Keyed`] items `now` over the items `was`
1273/// they were copied from, changed, removed and added to as `changes` says:
1274/// the operations [`ById::store`] writes, found without visiting the other
1275/// items. The map holds each of `was` under its id as a store left it,
1276/// except where `dirty` says someone else wrote since; an item no change
1277/// touched is the very item `was` holds there, and storing it writes
1278/// nothing. `position_of` finds an item by id.
1279/// For items whose type `table` describes, compiled once for every item
1280/// type.
1281#[inline(never)]
1282fn store_by_id_changed_in(
1283    table: &'static crate::table::ModelTable,
1284    position_of: &dyn Fn(&Id) -> Option<usize>,
1285    (now, was): (
1286        &dyn crate::collection::ItemList,
1287        &dyn crate::collection::ItemList,
1288    ),
1289    changes: Changes<'_>,
1290    (doc, slot, dirty): (&mut Doc, Slot<'_>, &Delta),
1291) -> Result<(), ModelError> {
1292    // A slot holding no map yet is written whole, as is a map someone else
1293    // changed otherwise than item by item, or items that left and came.
1294    let Some((Value::Object(ObjType::Map), map)) = slot.current(doc)? else {
1295        return store_by_id_in(table, now, doc, slot);
1296    };
1297    let touched = dirty.under(&map);
1298    let plan = match plan(was, now, changes) {
1299        Some(plan) if !touched.is_all() => plan,
1300        _ => return store_by_id_in(table, now, doc, slot),
1301    };
1302    // What to write, by position now and then: the items changed and
1303    // added, and those someone else touched; what to delete: the keys of
1304    // the items removed, and a key someone else wrote no item is under.
1305    let mut writes: Vec<(usize, Option<usize>)> = Vec::new();
1306    let mut stale: Vec<&str> = Vec::new();
1307    for step in &plan.steps {
1308        match step.now {
1309            Some(now) => writes.push((now, Some(step.was))),
1310            None => stale.push(step.id.as_str()),
1311        }
1312    }
1313    writes.extend((changes.held..now.count()).map(|at| (at, None)));
1314    for key in touched.keys() {
1315        match position_of(&Id::from_raw(key)) {
1316            Some(at) if at < changes.held => {
1317                writes.push((at, Some(copied_at(changes.removed, at))));
1318            }
1319            Some(at) => writes.push((at, None)),
1320            None => stale.push(key),
1321        }
1322    }
1323    // In the order `store` writes: deletes by key, then items in order. It
1324    // deletes only what the map holds.
1325    stale.compact_sort();
1326    stale.dedup();
1327    for key in stale {
1328        if doc.get(&map, key)?.is_some() {
1329            doc.delete(&map, key)?;
1330        }
1331    }
1332    writes.compact_sort_by_key(|(now, _)| *now);
1333    writes.dedup_by_key(|(now, _)| *now);
1334    for (at, then) in writes {
1335        let Some((id, item)) = now.item(at) else {
1336            continue;
1337        };
1338        let key = id.as_str();
1339        if let Some((_, held)) = then.and_then(|then| was.item(then)) {
1340            write_item_changed(table, (doc, &map, key), item, held, dirty)?;
1341        } else {
1342            made_entry(doc, &map, key)?;
1343            (table.ops.store)(table, item, doc, Slot::Key(&map, key)).located(key)?;
1344        }
1345    }
1346    Ok(())
1347}
1348
1349/// [`ById::store`] over items whose type `table` describes, compiled once
1350/// for every item type.
1351#[inline(never)]
1352fn store_by_id_in(
1353    table: &'static crate::table::ModelTable,
1354    items: &dyn crate::collection::ItemList,
1355    doc: &mut Doc,
1356    slot: Slot<'_>,
1357) -> Result<(), ModelError> {
1358    let map = slot.object(doc, ObjType::Map)?;
1359    let ids: Vec<Id> = (0..items.count())
1360        .filter_map(|at| Some(items.item(at)?.0))
1361        .collect();
1362    let keys: HashSet<&str> = ids.iter().map(Id::as_str).collect();
1363    let stale: Vec<String> = doc
1364        .keys(&map)
1365        .filter(|key| !keys.contains(key.as_str()))
1366        .collect();
1367    for key in stale {
1368        doc.delete(&map, key.as_str())?;
1369    }
1370    for at in 0..items.count() {
1371        let Some((id, item)) = items.item(at) else {
1372            continue;
1373        };
1374        made_entry(doc, &map, id.as_str())?;
1375        (table.ops.store)(table, item, doc, Slot::Key(&map, id.as_str())).located(id.as_str())?;
1376    }
1377    Ok(())
1378}
1379
1380/// Note the item `key` as one the applying action made, when `map` holds no entry for it yet:
1381/// what History names a change that added a keyed item by (the agent, the device it made).
1382fn made_entry(doc: &Doc, map: &ObjId, key: &str) -> Result<(), ModelError> {
1383    if doc.get(map, key)?.is_none() {
1384        crate::action::note_entry(map, key);
1385    }
1386    Ok(())
1387}
1388
1389/// [`Model::store_changed`] of [`Ordered`](crate::Ordered) items `now` over
1390/// the items `was` they were copied from, changed, removed and added to as
1391/// `changes` says: the operations [`Arranged::store`](crate::Arranged)
1392/// writes, found without visiting the other items. `false`, with nothing
1393/// written, when only the whole write can say.
1394///
1395/// The map holds an entry `{ k, v }` for each of `was` as a store left it,
1396/// unless `dirty` says someone else wrote there since; then it is written
1397/// whole. A store leaves order keys rising strictly from item to item, so a
1398/// whole write keeps every order key of the items still held (they rise in
1399/// the order kept), deletes the entries of the items removed, writes the
1400/// items changed field by field and mints keys after the last item held for
1401/// the items added; nothing else.
1402/// For items whose type `table` describes, compiled once for every item
1403/// type.
1404#[inline(never)]
1405fn store_arranged_changed_in(
1406    table: &'static crate::table::ModelTable,
1407    (now, was): (
1408        &dyn crate::collection::ItemList,
1409        &dyn crate::collection::ItemList,
1410    ),
1411    changes: Changes<'_>,
1412    (doc, slot, dirty): (&mut Doc, Slot<'_>, &Delta),
1413) -> Result<bool, ModelError> {
1414    use crate::collection::{ORDER, VALUE, put_entry};
1415    let Some((Value::Object(ObjType::Map), map)) = slot.current(doc)? else {
1416        return Ok(false);
1417    };
1418    if dirty.touches(&map) {
1419        return Ok(false);
1420    }
1421    let Some(plan) = plan(was, now, changes) else {
1422        return Ok(false);
1423    };
1424    // The key the last item held is stored under, read before any write.
1425    let last_key = match changes.held.checked_sub(1).and_then(|at| now.item(at)) {
1426        Some((id, _)) if !plan.added.is_empty() => {
1427            let Some((Value::Object(ObjType::Map), entry)) = doc.get(&map, id.as_str())? else {
1428                return Ok(false);
1429            };
1430            Some(
1431                crate::model::read_key::<crate::Atom>(doc, &entry, ORDER)
1432                    .located(id.as_str())?
1433                    .0,
1434            )
1435        }
1436        _ => None,
1437    };
1438    // Deletes first, in stored order: the order the items were copied in.
1439    for step in &plan.steps {
1440        if step.now.is_none() {
1441            doc.delete(&map, step.id.as_str())?;
1442        }
1443    }
1444    for step in &plan.steps {
1445        if let (Some(at), Some((_, held))) = (step.now, was.item(step.was))
1446            && let Some((_, item)) = now.item(at)
1447        {
1448            let id = step.id.as_str();
1449            let entry = Slot::Key(&map, id).object(doc, ObjType::Map)?;
1450            write_item_changed(table, (doc, &entry, VALUE), item, held, dirty).located(id)?;
1451        }
1452    }
1453    let keys = crate::order::sequence(last_key.as_deref(), None, plan.added.len());
1454    for ((offset, id), key) in plan.added.iter().enumerate().zip(keys) {
1455        let Some((_, item)) = now.item(changes.held.saturating_add(offset)) else {
1456            continue;
1457        };
1458        let made = crate::collection::TableItem { table, value: item };
1459        put_entry(doc, &map, id, key, false, &made)?;
1460    }
1461    Ok(true)
1462}
1463
1464impl<T: Model + Identified, S> crate::items::ItemSource for Items<T, S> {
1465    fn item_collection(&self, field: &'static str) -> crate::items::ItemCollection {
1466        crate::collection::listed_items(T::TABLE, self, field)
1467    }
1468    fn item_presence(&self) -> usize {
1469        usize::from(!self.items().is_empty())
1470    }
1471    fn label_of_item(&self, id: &Id) -> Option<String> {
1472        let item = self.find(id)?;
1473        Some(crate::collection::label_of(T::TABLE, id, item))
1474    }
1475    fn item_texts(&self, field: &'static str, found: &mut Vec<crate::items::ItemText>) {
1476        crate::collection::item_texts(T::TABLE, self, field, found);
1477    }
1478    fn nested_items(&self, field: &'static str, out: &mut Vec<crate::items::ItemCollection>) {
1479        crate::collection::nested_items(T::TABLE, self, field, out);
1480    }
1481}
1482
1483impl<T: Model + Identified, S: 'static> crate::table::PublishedItems for Items<T, S> {
1484    const ITEM_TABLE: &'static crate::table::ModelTable = T::TABLE;
1485}
1486
1487impl<T: Model + Identified, S> crate::collection::ItemList for Items<T, S> {
1488    fn count(&self) -> usize {
1489        self.items().len()
1490    }
1491
1492    fn item(&self, at: usize) -> Option<(Id, &dyn std::any::Any)> {
1493        let item = self.items().get(at)?;
1494        Some((item.id(), item as &dyn std::any::Any))
1495    }
1496}
1497
1498impl<T: Model + Identified, S: ItemStorage> Model for Items<T, S> {
1499    fn value_schema() -> serde_json::Value {
1500        serde_json::json!({"type": "array", "items": T::value_schema()})
1501    }
1502    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
1503        crate::FieldType::Collection(Box::new(T::field_type(types)))
1504    }
1505    const SHAPE: crate::Shape = if S::ARRANGED {
1506        crate::Shape::Collection(&T::SHAPE)
1507    } else {
1508        crate::Shape::Keyed(&T::SHAPE)
1509    };
1510    const CHECKS: bool = T::CHECKS;
1511    const OPS: bool = T::OPS;
1512    crate::model::leaf_paths!();
1513
1514    #[inline(never)]
1515    fn to_json(&self) -> serde_json::Value {
1516        serde_json::Value::Array(self.items().iter().map(Model::to_json).collect())
1517    }
1518
1519    #[inline(never)]
1520    fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
1521        let mut items = Vec::new();
1522        each_item_json(value, &mut |item| {
1523            items.push(T::from_json(item)?);
1524            Ok(())
1525        })?;
1526        Ok(Self::from(items))
1527    }
1528
1529    #[inline(never)]
1530    fn load(doc: &Doc, value: &Value<'_>, id: &ObjId) -> Result<Self, ModelError> {
1531        if !matches!(value, Value::Object(ObjType::Map)) {
1532            return Err(ModelError::shape(S::NAME));
1533        }
1534        S::load(doc, id).map(Self::from)
1535    }
1536
1537    fn missing() -> Result<Self, ModelError> {
1538        Ok(Self::default())
1539    }
1540
1541    #[inline(never)]
1542    fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
1543        S::store(self.items(), doc, slot)
1544    }
1545
1546    /// Items two clones still share are the same items, and store as they
1547    /// are: saving a record whose items no change touched visits none.
1548    fn stores_as(&self, before: &Self) -> bool {
1549        self.stock.same(&before.stock)
1550    }
1551
1552    /// A copy changed one item at a time, removed from and added to writes
1553    /// only those items, and for a [`Keyed`] the ones someone else touched;
1554    /// anything else is written as [`store`](Model::store) writes it.
1555    #[inline(never)]
1556    fn store_changed(
1557        &self,
1558        before: &Self,
1559        doc: &mut Doc,
1560        slot: Slot<'_>,
1561        dirty: &Delta,
1562    ) -> Result<(), ModelError> {
1563        let (now, was) = (self.stock.get(), before.stock.get());
1564        let changes = if self.stock.same(&before.stock) {
1565            Some(Changes::none(was.items.len()))
1566        } else {
1567            now.changed_since(was)
1568        };
1569        store_items_changed_in(
1570            (T::TABLE, S::ARRANGED),
1571            (&Rows(&now.items), &Rows(&was.items)),
1572            changes,
1573            (&|id| self.position_of(id), &|doc, slot| {
1574                self.store(doc, slot)
1575            }),
1576            (doc, slot, dirty),
1577        )
1578    }
1579
1580    #[inline(never)]
1581    fn refresh(
1582        &mut self,
1583        doc: &Doc,
1584        value: &Value<'_>,
1585        id: &ObjId,
1586        delta: &Delta,
1587    ) -> Result<(), ModelError> {
1588        if !matches!(value, Value::Object(ObjType::Map)) {
1589            *self = Self::load(doc, value, id)?;
1590            return Ok(());
1591        }
1592        // Untouched items stay shared with any clone of them.
1593        if !delta.touches(id) {
1594            return Ok(());
1595        }
1596        let stock = self.stock.make_mut();
1597        let mut ids = stock.take_ids();
1598        let refreshed = S::refresh_with_ids(stock.all_mut(), &mut ids, doc, id, delta);
1599        stock.ids = ids;
1600        refreshed
1601    }
1602    #[inline(never)]
1603    fn edit(
1604        doc: &mut Doc,
1605        slot: Slot<'_>,
1606        path: &[Segment],
1607        op: &EditOp,
1608        cx: &mut ActionCx,
1609    ) -> Result<(), ModelError> {
1610        let edits = crate::collection::EntryEdits {
1611            item: &T::edit,
1612            parse: &|value| {
1613                let item = T::from_json(value)?;
1614                item.check().map_err(ModelError::refused)?;
1615                Ok((
1616                    Some(item.id()),
1617                    Box::new(item) as Box<dyn crate::model::Stores + '_>,
1618                ))
1619            },
1620            whole: &edit_whole::<Self>,
1621            order_only: false,
1622        };
1623        if S::ARRANGED {
1624            crate::collection::edit_entries(doc, slot, path, op, cx, &edits)
1625        } else {
1626            edit_by_id(doc, slot, path, op, cx, &edits)
1627        }
1628    }
1629
1630    /// Items two clones still share are not compared; a copy changed one
1631    /// item at a time compares only the items it changed.
1632    #[inline(never)]
1633    fn diff<R>(&self, after: &Self, path: &[Segment], out: &mut Vec<Edit<R>>) {
1634        if self.stock.same(&after.stock) {
1635            return;
1636        }
1637        let mut found = Vec::new();
1638        diff_items_in(
1639            (T::TABLE, S::DIFF, S::ARRANGED),
1640            (&Rows(self.items()), &Rows(after.items())),
1641            after.stock.get().changed_since(self.stock.get()),
1642            path,
1643            &mut found,
1644        );
1645        out.extend(found.into_iter().map(Edit::retyped));
1646    }
1647
1648    fn check(&self) -> Result<(), Refusal> {
1649        if T::CHECKS {
1650            self.items().iter().try_for_each(Model::check)?;
1651        }
1652        Ok(())
1653    }
1654
1655    fn get_at(&self, path: &[Segment]) -> Option<&dyn std::any::Any>
1656    where
1657        Self: 'static,
1658    {
1659        match path.split_first() {
1660            None => Some(self),
1661            Some((Segment::Item(id), rest)) => self.find(id)?.get_at(rest),
1662            Some(_) => None,
1663        }
1664    }
1665
1666    fn op_coalesces(
1667        path: &[Segment],
1668        previous: &serde_json::Value,
1669        next: &serde_json::Value,
1670    ) -> Option<bool> {
1671        match path.split_first() {
1672            Some((Segment::Item(_), rest)) if T::OPS => T::op_coalesces(rest, previous, next),
1673            _ => None,
1674        }
1675    }
1676
1677    fn op_continuable(path: &[Segment], op: &serde_json::Value) -> Option<bool> {
1678        match path.split_first() {
1679            Some((Segment::Item(_), rest)) if T::OPS => T::op_continuable(rest, op),
1680            _ => None,
1681        }
1682    }
1683
1684    fn op_describe(path: &[Segment], op: &serde_json::Value) -> Option<crate::path::OpDescription> {
1685        match path.split_first() {
1686            Some((Segment::Item(_), rest)) if T::OPS => T::op_describe(rest, op),
1687            _ => None,
1688        }
1689    }
1690
1691    fn op_lands(&self, path: &[Segment], op: &serde_json::Value) -> Option<crate::Place> {
1692        match path.split_first() {
1693            Some((Segment::Item(id), rest)) if T::OPS => self.find(id)?.op_lands(rest, op),
1694            _ => None,
1695        }
1696    }
1697
1698    fn op_schemas(prefix: &str, out: &mut Vec<(String, serde_json::Value)>) {
1699        if T::OPS {
1700            T::op_schemas(&format!("{prefix}*."), out);
1701        }
1702    }
1703
1704    fn collect_text(&self, out: &mut Vec<String>) {
1705        for item in self.items() {
1706            item.collect_text(out);
1707        }
1708    }
1709}