1use std::collections::BTreeMap;
16
17use automerge::transaction::Transactable;
18use automerge::{AutoCommit, ObjId, ObjType, ReadDoc, ScalarValue, Value};
19
20use crate::action::{ActionCx, Refusal};
21use crate::delta::{Delta, Touch};
22use crate::path::{EditOp, Path, Segment, Settable};
23
24pub type Doc = AutoCommit;
26
27#[derive(Debug, thiserror::Error)]
29pub enum ModelError {
30 #[error("{}expected {expected}", located(.path))]
31 Shape {
32 path: String,
33 expected: &'static str,
34 },
35 #[error("{}required value is missing", located(.path))]
36 Missing { path: String },
37 #[error("{}{message}", located(.path))]
38 Invalid { path: String, message: String },
39 #[error("document error: {0}")]
40 Automerge(#[from] automerge::AutomergeError),
41 #[error("{0}")]
43 Refused(String),
44 #[error("{0}")]
47 Declined(tilo_actions::Declined),
48}
49
50fn located(path: &str) -> String {
53 if path.is_empty() {
54 String::new()
55 } else {
56 format!("{path}: ")
57 }
58}
59
60impl ModelError {
61 #[must_use]
62 pub fn shape(expected: &'static str) -> Self {
63 Self::Shape {
64 path: String::new(),
65 expected,
66 }
67 }
68
69 #[must_use]
70 pub fn invalid(message: impl Into<String>) -> Self {
71 Self::Invalid {
72 path: String::new(),
73 message: message.into(),
74 }
75 }
76
77 #[must_use]
79 #[inline(never)]
80 pub fn at(mut self, segment: &str) -> Self {
81 match &mut self {
82 Self::Shape { path, .. } | Self::Missing { path } | Self::Invalid { path, .. } => {
83 *path = if path.is_empty() {
84 segment.to_owned()
85 } else {
86 format!("{segment}.{path}")
87 };
88 }
89 Self::Automerge(_) | Self::Refused(_) | Self::Declined(_) => {}
90 }
91 self
92 }
93
94 #[must_use]
96 pub fn refused(refusal: Refusal) -> Self {
97 Self::Refused(refusal.into_reason())
98 }
99
100 #[must_use]
102 pub fn unsupported(op: &EditOp) -> Self {
103 Self::invalid(format!("this value has no `{}` edit", op.name()))
104 }
105}
106
107pub enum Fresh {
111 Nothing,
113 Value(automerge::hydrate::Value),
116 Made(automerge::hydrate::Value),
121 Store,
123}
124
125thread_local! {
126 static STORING_MADE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
129}
130
131#[must_use]
135pub fn storing_made() -> bool {
136 STORING_MADE.with(std::cell::Cell::get)
137}
138
139pub(crate) fn storing_made_around<T>(store: impl FnOnce() -> T) -> T {
141 struct Restore(bool);
142 impl Drop for Restore {
143 fn drop(&mut self) {
144 STORING_MADE.with(|made| made.set(self.0));
145 }
146 }
147 let was = STORING_MADE.with(|made| made.replace(true));
148 let _restore = Restore(was);
149 store()
150}
151
152impl Fresh {
153 #[must_use]
155 pub fn scalar(value: impl Into<ScalarValue>) -> Self {
156 Self::Value(automerge::hydrate::Value::Scalar(value.into()))
157 }
158}
159
160#[derive(Clone, Copy, Debug)]
163pub enum Slot<'a> {
164 Key(&'a ObjId, &'a str),
165 Index(&'a ObjId, usize),
166 Insert(&'a ObjId, usize),
167}
168
169impl Slot<'_> {
170 pub fn current(self, doc: &Doc) -> Result<Option<(Value<'static>, ObjId)>, ModelError> {
172 let found = match self {
173 Slot::Key(obj, key) => doc.get(obj, key)?,
174 Slot::Index(obj, index) => doc.get(obj, index)?,
175 Slot::Insert(..) => None,
176 };
177 Ok(found.map(|(value, id)| (value.to_owned(), id)))
178 }
179
180 pub fn put_scalar(self, doc: &mut Doc, value: ScalarValue) -> Result<(), ModelError> {
182 match self {
183 Slot::Key(obj, key) => {
184 if !matches!(doc.get(obj, key)?, Some((Value::Scalar(current), _)) if same_scalar(¤t, &value))
185 {
186 doc.put(obj, key, value)?;
187 }
188 }
189 Slot::Index(obj, index) => {
190 if !matches!(doc.get(obj, index)?, Some((Value::Scalar(current), _)) if same_scalar(¤t, &value))
191 {
192 doc.put(obj, index, value)?;
193 }
194 }
195 Slot::Insert(obj, index) => doc.insert(obj, index, value)?,
196 }
197 Ok(())
198 }
199
200 pub fn make(
203 self,
204 doc: &mut Doc,
205 value: &automerge::hydrate::Value,
206 ) -> Result<ObjId, ModelError> {
207 Ok(match self {
208 Self::Key(obj, key) => doc.batch_create_object(obj, key, value, false)?,
209 Self::Index(obj, index) => doc.batch_create_object(obj, index, value, false)?,
210 Self::Insert(obj, index) => doc.batch_create_object(obj, index, value, true)?,
211 })
212 }
213
214 pub fn object(self, doc: &mut Doc, kind: ObjType) -> Result<ObjId, ModelError> {
217 if let Some((Value::Object(existing), id)) = self.current(doc)?
218 && existing == kind
219 {
220 return Ok(id);
221 }
222 Ok(match self {
223 Slot::Key(obj, key) => doc.put_object(obj, key, kind)?,
224 Slot::Index(obj, index) => doc.put_object(obj, index, kind)?,
225 Slot::Insert(obj, index) => doc.insert_object(obj, index, kind)?,
226 })
227 }
228
229 pub fn increment(self, doc: &mut Doc, by: i64) -> Result<(), ModelError> {
231 let counter = matches!(
232 self.current(doc)?,
233 Some((Value::Scalar(scalar), _)) if matches!(scalar.as_ref(), ScalarValue::Counter(_))
234 );
235 if by == 0 && counter {
236 return Ok(());
237 }
238 match (self, counter) {
239 (Slot::Key(obj, key), true) => doc.increment(obj, key, by)?,
240 (Slot::Index(obj, index), true) => doc.increment(obj, index, by)?,
241 (slot, _) => {
242 let start = match slot.current(doc)? {
243 Some((value, _)) => match scalar(&value) {
244 Some(ScalarValue::Int(value)) => *value,
245 _ => 0,
246 },
247 None => 0,
248 };
249 let value = ScalarValue::counter(start.saturating_add(by));
250 match slot {
251 Slot::Key(obj, key) => doc.put(obj, key, value)?,
252 Slot::Index(obj, index) => doc.put(obj, index, value)?,
253 Slot::Insert(obj, index) => doc.insert(obj, index, value)?,
254 }
255 }
256 }
257 Ok(())
258 }
259
260 pub fn remove(self, doc: &mut Doc) -> Result<(), ModelError> {
262 match self {
263 Slot::Key(obj, key) => {
264 if doc.get(obj, key)?.is_some() {
265 doc.delete(obj, key)?;
266 }
267 }
268 Slot::Index(obj, index) => doc.put(obj, index, ScalarValue::Null)?,
269 Slot::Insert(obj, index) => doc.insert(obj, index, ScalarValue::Null)?,
270 }
271 Ok(())
272 }
273}
274
275fn same_scalar(current: &ScalarValue, next: &ScalarValue) -> bool {
276 match (current, next) {
277 (ScalarValue::F64(a), ScalarValue::F64(b)) => a.to_bits() == b.to_bits(),
278 (a, b) => a == b,
279 }
280}
281
282pub trait Model: Sized + 'static {
284 const SHAPE: crate::Shape = crate::Shape::Value;
287
288 const CHECKS: bool = false;
291
292 const OPS: bool = false;
297
298 const NULLABLE: bool = false;
301
302 const SCALAR: bool = false;
308
309 const TABLE: &'static crate::table::ModelTable = &crate::table::TableOf::<Self>::TABLE;
312
313 type Paths<R>: Clone;
317
318 fn paths_at<R>(path: Path<R, Self>) -> Self::Paths<R>;
320
321 fn to_json(&self) -> serde_json::Value;
323
324 fn from_json(value: &serde_json::Value) -> Result<Self, ModelError>;
329
330 #[inline(never)]
334 fn edit(
335 doc: &mut Doc,
336 slot: Slot<'_>,
337 path: &[Segment],
338 op: &EditOp,
339 cx: &mut ActionCx,
340 ) -> Result<(), ModelError> {
341 let _ = cx;
342 edit_whole::<Self>(doc, slot, path, op)
343 }
344
345 #[inline(never)]
352 fn diff<R>(&self, after: &Self, path: &[Segment], out: &mut Vec<crate::Edit<R>>) {
353 if after.stores_as(self) {
354 return;
355 }
356 let value = after.to_json();
357 if self.to_json() != value {
358 out.push(crate::Edit::new(path.to_vec(), EditOp::Set { value }));
359 }
360 }
361
362 fn nested_collections(&self) -> Vec<crate::items::ItemCollection> {
366 Vec::new()
367 }
368
369 fn value_schema() -> serde_json::Value {
373 serde_json::json!({})
374 }
375
376 fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
381 let _ = types;
382 crate::FieldType::Any
383 }
384
385 fn read_whole(&mut self, doc: &Doc) -> Result<(), ModelError> {
394 let _ = doc;
395 Ok(())
396 }
397
398 fn check(&self) -> Result<(), Refusal> {
401 Ok(())
402 }
403
404 fn label(&self) -> Option<String> {
407 None
408 }
409
410 fn op_coalesces(
414 path: &[Segment],
415 previous: &serde_json::Value,
416 next: &serde_json::Value,
417 ) -> Option<bool> {
418 let _ = (path, previous, next);
419 None
420 }
421
422 fn op_continuable(path: &[Segment], op: &serde_json::Value) -> Option<bool> {
424 let _ = (path, op);
425 None
426 }
427 fn op_describe(path: &[Segment], op: &serde_json::Value) -> Option<crate::path::OpDescription> {
430 let _ = (path, op);
431 None
432 }
433
434 fn op_lands(&self, path: &[Segment], op: &serde_json::Value) -> Option<crate::Place> {
437 let _ = (path, op);
438 None
439 }
440
441 fn op_schemas(prefix: &str, out: &mut Vec<(String, serde_json::Value)>) {
444 let _ = (prefix, out);
445 }
446
447 fn get_at(&self, path: &[Segment]) -> Option<&dyn std::any::Any>
450 where
451 Self: 'static,
452 {
453 path.is_empty().then_some(self as &dyn std::any::Any)
454 }
455
456 fn load(doc: &Doc, value: &Value<'_>, id: &ObjId) -> Result<Self, ModelError>;
461
462 fn missing() -> Result<Self, ModelError> {
468 Err(ModelError::Missing {
469 path: String::new(),
470 })
471 }
472
473 fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError>;
476
477 fn fresh(&self, encoding: automerge::TextEncoding) -> Fresh {
481 let _ = encoding;
482 Fresh::Store
483 }
484
485 #[inline(never)]
491 fn stores_as(&self, before: &Self) -> bool {
492 let _ = before;
493 false
494 }
495
496 #[inline(never)]
507 fn store_changed(
508 &self,
509 before: &Self,
510 doc: &mut Doc,
511 slot: Slot<'_>,
512 dirty: &Delta,
513 ) -> Result<(), ModelError> {
514 let _ = (before, dirty);
515 self.store(doc, slot)
516 }
517
518 #[inline(never)]
527 fn refresh(
528 &mut self,
529 doc: &Doc,
530 value: &Value<'_>,
531 id: &ObjId,
532 delta: &Delta,
533 ) -> Result<(), ModelError> {
534 let _ = delta;
535 *self = Self::load(doc, value, id)?;
536 Ok(())
537 }
538
539 fn collect_text(&self, _out: &mut Vec<String>) {}
541}
542
543pub trait Fields: Model {
547 const ITEM_FIELDS: &'static [&'static str] = &[];
550
551 fn read_fields(doc: &Doc, obj: &ObjId) -> Result<Self, ModelError>;
554 fn write_fields(&self, doc: &mut Doc, obj: &ObjId) -> Result<(), ModelError>;
555
556 fn item_collections(&self) -> Vec<crate::items::ItemCollection> {
561 Vec::new()
562 }
563
564 fn item_label(&self, field: &str, id: &crate::Id) -> Option<String> {
567 let _ = (field, id);
568 None
569 }
570
571 fn item_named(&self, field: &str, reference: &str) -> Result<crate::Id, crate::Refusal> {
579 let _ = (field, reference);
580 Err(crate::Refusal::new("this record keeps no such items"))
581 }
582
583 fn item_named_as(
590 &self,
591 field: &str,
592 _what: (&str, &str),
593 reference: &str,
594 ) -> Result<crate::Id, crate::Refusal> {
595 self.item_named(field, reference)
596 }
597
598 fn item_holds(&self, field: &str, id: &str) -> bool {
601 let _ = (field, id);
602 false
603 }
604
605 fn item_id_any(&self, reference: &str) -> bool {
608 let _ = reference;
609 false
610 }
611 fn item_search(&self) -> Vec<crate::items::ItemText> {
614 Vec::new()
615 }
616
617 fn edit_fields(
621 doc: &mut Doc,
622 obj: &ObjId,
623 path: &[Segment],
624 op: &EditOp,
625 cx: &mut ActionCx,
626 ) -> Result<(), ModelError> {
627 let _ = (doc, obj, path, cx);
628 Err(ModelError::unsupported(op))
629 }
630
631 fn item_collection_sizes(&self) -> Vec<(&'static str, usize)> {
636 self.item_collections()
637 .iter()
638 .map(|collection| (collection.field, collection.items.len()))
639 .collect()
640 }
641
642 fn write_changed_fields(
648 &self,
649 before: &Self,
650 doc: &mut Doc,
651 obj: &ObjId,
652 dirty: &Delta,
653 ) -> Result<(), ModelError> {
654 let _ = (before, dirty);
655 self.write_fields(doc, obj)
656 }
657
658 fn refresh_fields(&mut self, doc: &Doc, obj: &ObjId, delta: &Delta) -> Result<(), ModelError> {
664 if delta.touches(obj) {
665 *self = Self::read_fields(doc, obj)?;
666 }
667 Ok(())
668 }
669}
670
671#[inline(never)]
676pub fn read_key<T: Model>(doc: &Doc, obj: &ObjId, key: &str) -> Result<T, ModelError> {
677 let slot = get_slot(doc, obj, key)?;
678 load_at(doc, slot.as_ref().map(|(value, id)| (value, id)), key)
679}
680
681#[inline(never)]
689pub(crate) fn get_slot<'doc>(
690 doc: &'doc Doc,
691 obj: &ObjId,
692 key: &str,
693) -> Result<Option<(Value<'doc>, ObjId)>, ModelError> {
694 Ok(doc.get(obj, key)?)
695}
696
697#[inline(never)]
699pub(crate) fn get_item<'doc>(
700 doc: &'doc Doc,
701 obj: &ObjId,
702 index: usize,
703) -> Result<Option<(Value<'doc>, ObjId)>, ModelError> {
704 Ok(doc.get(obj, index)?)
705}
706
707fn load_at<T: Model>(
710 doc: &Doc,
711 slot: Option<(&Value<'_>, &ObjId)>,
712 key: &str,
713) -> Result<T, ModelError> {
714 match slot {
715 Some((value, id)) => T::load(doc, value, id),
716 None => T::missing(),
717 }
718 .located(key)
719}
720
721pub type MapSlot = Option<(Value<'static>, ObjId)>;
724
725pub fn read_slots<const N: usize>(doc: &Doc, obj: &ObjId, keys: [&str; N]) -> [MapSlot; N] {
732 let mut slots = [const { None }; N];
733 fill_slots(doc, obj, &keys, &mut slots);
734 slots
735}
736
737#[inline(never)]
741pub(crate) fn fill_slots(doc: &Doc, obj: &ObjId, keys: &[&str], slots: &mut [MapSlot]) {
742 let mut missing = keys.len();
743 if missing == 0 {
744 return;
745 }
746 for item in doc.map_range(obj, ..) {
747 let mut matched = false;
748 for (key, slot) in keys.iter().zip(slots.iter_mut()) {
749 if *key == item.key {
750 *slot = Some((item.value.clone().into_value(), item.id()));
751 missing = missing.saturating_sub(1);
752 matched = true;
753 }
754 }
755 if matched && missing == 0 {
756 break;
757 }
758 }
759}
760
761#[inline(never)]
764pub(crate) fn map_slots(doc: &Doc, obj: &ObjId) -> Vec<(String, MapSlot)> {
765 doc.map_range(obj, ..)
766 .map(|item| {
767 let slot = Some((item.value.clone().into_value(), item.id()));
768 (item.key.into_owned(), slot)
769 })
770 .collect()
771}
772
773#[must_use]
777#[inline(never)]
778pub fn take_slot(slots: &mut [MapSlot], index: usize) -> MapSlot {
779 slots.get_mut(index).and_then(Option::take)
780}
781
782pub fn load_slot<T: Model>(doc: &Doc, slot: MapSlot, key: &str) -> Result<T, ModelError> {
788 match slot {
789 Some((value, id)) => load_at(doc, Some((&value, &id)), key),
790 None => load_at(doc, None, key),
791 }
792}
793
794#[inline(never)]
801pub fn refresh_key<T: Model>(
802 target: &mut T,
803 doc: &Doc,
804 obj: &ObjId,
805 key: &str,
806 delta: &Delta,
807) -> Result<(), ModelError> {
808 match delta.key(obj, key) {
809 Touch::Untouched => Ok(()),
810 Touch::Written => {
811 *target = read_key(doc, obj, key)?;
812 Ok(())
813 }
814 Touch::Below => match get_slot(doc, obj, key)? {
815 Some((value, id)) => target.refresh(doc, &value, &id, delta),
816 None => match T::missing() {
817 Ok(missing) => {
818 *target = missing;
819 Ok(())
820 }
821 Err(error) => Err(error),
822 },
823 }
824 .located(key),
825 }
826}
827
828pub trait LocatedAt<T> {
831 fn located(self, key: &str) -> Result<T, ModelError>;
833}
834
835impl<T> LocatedAt<T> for Result<T, ModelError> {
836 fn located(self, key: &str) -> Result<T, ModelError> {
837 match self {
838 Ok(value) => Ok(value),
839 Err(error) => Err(error.at(key)),
840 }
841 }
842}
843
844pub(crate) trait Stores {
847 fn store_to(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError>;
848
849 fn made_to(&self, _: automerge::TextEncoding) -> Option<crate::table::Fields> {
856 None
857 }
858
859 fn write_later_to(
865 &self,
866 _: &mut Doc,
867 _: &ObjId,
868 _: &[(usize, bool)],
869 ) -> Result<(), ModelError> {
870 Ok(())
871 }
872}
873
874impl<T: Model> Stores for T {
875 fn store_to(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
876 self.store(doc, slot)
877 }
878
879 fn made_to(&self, encoding: automerge::TextEncoding) -> Option<crate::table::Fields> {
880 let desc = crate::table::described(T::TABLE).ok()?;
881 crate::table::fresh::fields_made_of(desc, self, encoding)
882 }
883
884 fn write_later_to(
885 &self,
886 doc: &mut Doc,
887 value: &ObjId,
888 later: &[(usize, bool)],
889 ) -> Result<(), ModelError> {
890 let desc = crate::table::described(T::TABLE)?;
891 crate::table::fresh::write_later(desc, self, doc, value, later)
892 }
893}
894
895#[inline(never)]
900pub fn write_key<T: Model>(
901 doc: &mut Doc,
902 obj: &ObjId,
903 key: &str,
904 value: &T,
905) -> Result<(), ModelError> {
906 value.store(doc, Slot::Key(obj, key)).located(key)
907}
908
909#[inline(never)]
912pub fn edit_whole<T: Model>(
913 doc: &mut Doc,
914 slot: Slot<'_>,
915 path: &[Segment],
916 op: &EditOp,
917) -> Result<(), ModelError> {
918 if let Some(segment) = path.first() {
919 return Err(ModelError::invalid(format!(
920 "nothing inside this value is called `{segment}`"
921 )));
922 }
923 match op {
924 EditOp::Set { value } if value.is_null() && !T::NULLABLE => Err(ModelError::invalid(
925 "`null` is no value of this field: set a value of its type",
926 )),
927 EditOp::Set { value } => {
928 let value = T::from_json(value)?;
929 value.check().map_err(ModelError::refused)?;
930 value.store(doc, slot)
931 }
932 other => Err(ModelError::unsupported(other)),
933 }
934}
935
936pub(crate) fn json_shape(expected: &'static str) -> ModelError {
938 ModelError::shape(expected)
939}
940
941#[macro_export]
944macro_rules! leaf_paths {
945 () => {
946 type Paths<R> = $crate::Path<R, Self>;
947 fn paths_at<R>(path: $crate::Path<R, Self>) -> $crate::Path<R, Self> {
948 path
949 }
950 };
951}
952pub(crate) use crate::leaf_paths;
953
954#[doc(hidden)]
959#[macro_export]
960macro_rules! __table_functions {
961 () => {
962 #[inline]
963 fn op_coalesces(
964 path: &[$crate::path::Segment],
965 previous: &$crate::__private::serde_json::Value,
966 next: &$crate::__private::serde_json::Value,
967 ) -> ::core::option::Option<bool> {
968 $crate::table::Run(Self::TABLE).op_coalesces(path, previous, next)
969 }
970 #[inline]
971 fn op_continuable(
972 path: &[$crate::path::Segment],
973 op: &$crate::__private::serde_json::Value,
974 ) -> ::core::option::Option<bool> {
975 $crate::table::Run(Self::TABLE).op_continuable(path, op)
976 }
977 #[inline]
978 fn op_describe(
979 path: &[$crate::path::Segment],
980 op: &$crate::__private::serde_json::Value,
981 ) -> ::core::option::Option<$crate::path::OpDescription> {
982 $crate::table::Run(Self::TABLE).op_describe(path, op)
983 }
984 #[inline]
985 fn op_lands(
986 &self,
987 path: &[$crate::path::Segment],
988 op: &$crate::__private::serde_json::Value,
989 ) -> ::core::option::Option<$crate::Place> {
990 $crate::table::Run(Self::TABLE).op_lands(self, path, op)
991 }
992 #[inline]
993 fn op_schemas(
994 prefix: &str,
995 out: &mut ::std::vec::Vec<(
996 ::std::string::String,
997 $crate::__private::serde_json::Value,
998 )>,
999 ) {
1000 $crate::table::Run(Self::TABLE).op_schemas(prefix, out);
1001 }
1002 #[inline]
1003 fn to_json(&self) -> $crate::__private::serde_json::Value {
1004 $crate::table::Run(Self::TABLE).to_json(self)
1005 }
1006 #[inline]
1007 fn from_json(
1008 value: &$crate::__private::serde_json::Value,
1009 ) -> ::core::result::Result<Self, $crate::model::ModelError> {
1010 $crate::table::Run(Self::TABLE).from_json(value)
1011 }
1012 #[inline]
1013 fn edit(
1014 doc: &mut $crate::model::Doc,
1015 slot: $crate::model::Slot<'_>,
1016 path: &[$crate::path::Segment],
1017 op: &$crate::path::EditOp,
1018 cx: &mut $crate::action::ActionCx,
1019 ) -> ::core::result::Result<(), $crate::model::ModelError> {
1020 $crate::table::Run(Self::TABLE).edit(doc, slot, path, op, cx)
1021 }
1022 #[inline]
1023 fn check(&self) -> ::core::result::Result<(), $crate::action::Refusal> {
1024 $crate::table::Run(Self::TABLE).check(self)
1025 }
1026 #[inline]
1027 fn get_at(
1028 &self,
1029 path: &[$crate::path::Segment],
1030 ) -> ::core::option::Option<&dyn ::core::any::Any> {
1031 $crate::table::Run(Self::TABLE).get_at(self, path)
1032 }
1033 #[inline]
1034 fn diff<R>(
1035 &self,
1036 after: &Self,
1037 path: &[$crate::path::Segment],
1038 out: &mut ::std::vec::Vec<$crate::Edit<R>>,
1039 ) {
1040 $crate::table::Run(Self::TABLE).diff(self, after, path, out);
1041 }
1042 #[inline]
1043 fn load(
1044 doc: &$crate::model::Doc,
1045 value: &$crate::__private::Value<'_>,
1046 id: &$crate::__private::ObjId,
1047 ) -> ::core::result::Result<Self, $crate::model::ModelError> {
1048 $crate::table::Run(Self::TABLE).load(doc, value, id)
1049 }
1050 #[inline]
1051 fn store(
1052 &self,
1053 doc: &mut $crate::model::Doc,
1054 slot: $crate::model::Slot<'_>,
1055 ) -> ::core::result::Result<(), $crate::model::ModelError> {
1056 $crate::table::Run(Self::TABLE).store(self, doc, slot)
1057 }
1058 #[inline]
1059 fn stores_as(&self, before: &Self) -> bool {
1060 $crate::table::Run(Self::TABLE).stores_as(self, before)
1061 }
1062 #[inline]
1063 fn store_changed(
1064 &self,
1065 before: &Self,
1066 doc: &mut $crate::model::Doc,
1067 slot: $crate::model::Slot<'_>,
1068 dirty: &$crate::delta::Delta,
1069 ) -> ::core::result::Result<(), $crate::model::ModelError> {
1070 $crate::table::Run(Self::TABLE).store_changed(self, before, doc, slot, dirty)
1071 }
1072 #[inline]
1073 fn refresh(
1074 &mut self,
1075 doc: &$crate::model::Doc,
1076 value: &$crate::__private::Value<'_>,
1077 id: &$crate::__private::ObjId,
1078 delta: &$crate::delta::Delta,
1079 ) -> ::core::result::Result<(), $crate::model::ModelError> {
1080 $crate::table::Run(Self::TABLE).refresh(self, doc, value, id, delta)
1081 }
1082 #[inline]
1083 fn collect_text(&self, out: &mut ::std::vec::Vec<::std::string::String>) {
1084 $crate::table::Run(Self::TABLE).collect_text(self, out);
1085 }
1086 };
1087}
1088
1089#[macro_export]
1105macro_rules! json_model {
1106 ($ty:ty => named) => {
1107 impl $crate::Settable for $ty {}
1108 impl $crate::Model for $ty {
1109 $crate::leaf_paths!();
1110 const NULLABLE: bool = true;
1111 const TABLE: &'static $crate::table::ModelTable =
1112 &$crate::table::ModelTable::of_json(&$crate::table::JsonOf::<$ty>::COMPARED);
1113 $crate::__table_functions!();
1114 fn missing() -> ::core::result::Result<Self, $crate::ModelError> {
1115 ::core::result::Result::Ok(<Self as ::core::default::Default>::default())
1116 }
1117 fn field_type(types: &mut $crate::TypeSet) -> $crate::FieldType {
1118 <$ty as $crate::JsonSchema>::field_type(types)
1119 }
1120 }
1121 };
1122 ($ty:ty => $schema:tt, $field_type:ident) => {
1123 impl $crate::Settable for $ty {}
1124 impl $crate::Model for $ty {
1125 $crate::leaf_paths!();
1126 const NULLABLE: bool = true;
1127 const TABLE: &'static $crate::table::ModelTable =
1128 &$crate::table::ModelTable::of_json(&$crate::table::JsonOf::<$ty>::COMPARED);
1129 $crate::__table_functions!();
1130 fn missing() -> ::core::result::Result<Self, $crate::ModelError> {
1131 ::core::result::Result::Ok(<Self as ::core::default::Default>::default())
1132 }
1133 fn value_schema() -> $crate::__private::serde_json::Value {
1134 $crate::__private::serde_json::json!($schema)
1135 }
1136 fn field_type(types: &mut $crate::TypeSet) -> $crate::FieldType {
1137 let _ = types;
1138 $crate::FieldType::$field_type
1139 }
1140 }
1141 };
1142 ($($ty:ty),* $(,)?) => {$(
1143 impl $crate::Settable for $ty {}
1144 impl $crate::Model for $ty {
1145 $crate::leaf_paths!();
1146 const NULLABLE: bool = true;
1148 const TABLE: &'static $crate::table::ModelTable =
1150 &$crate::table::ModelTable::of_json(&$crate::table::JsonOf::<$ty>::COMPARED);
1151 $crate::__table_functions!();
1152 fn missing() -> ::core::result::Result<Self, $crate::ModelError> {
1153 ::core::result::Result::Ok(<Self as ::core::default::Default>::default())
1154 }
1155 }
1156 )*};
1157}
1158
1159#[inline(never)]
1166pub fn write_key_changed<T: Model>(
1167 doc: &mut Doc,
1168 obj: &ObjId,
1169 key: &str,
1170 value: &T,
1171 before: &T,
1172 dirty: &Delta,
1173) -> Result<(), ModelError> {
1174 match dirty.key(obj, key) {
1175 Touch::Written => write_key(doc, obj, key, value),
1176 Touch::Untouched if value.stores_as(before) => Ok(()),
1177 Touch::Untouched | Touch::Below => value
1178 .store_changed(before, doc, Slot::Key(obj, key), dirty)
1179 .located(key),
1180 }
1181}
1182
1183pub const VARIANT_KEY: &str = "$variant";
1187
1188#[doc(hidden)]
1196#[inline(never)]
1197pub fn variant_map(
1198 doc: &mut Doc,
1199 slot: Slot<'_>,
1200 variant: &str,
1201 fields: &[&str],
1202) -> Result<ObjId, ModelError> {
1203 let obj = slot.object(doc, ObjType::Map)?;
1204 Slot::Key(&obj, VARIANT_KEY).put_scalar(doc, ScalarValue::Str(variant.into()))?;
1205 let stale: Vec<String> = doc
1206 .keys(&obj)
1207 .filter(|key| key.as_str() != VARIANT_KEY && !fields.contains(&key.as_str()))
1208 .collect();
1209 for key in stale {
1210 doc.delete(&obj, key.as_str())?;
1211 }
1212 Ok(obj)
1213}
1214
1215#[doc(hidden)]
1226pub fn read_variant_field<T: Model>(
1227 doc: &Doc,
1228 obj: &ObjId,
1229 storage: &str,
1230 key: &str,
1231) -> Result<T, ModelError> {
1232 let slot = match get_slot(doc, obj, storage)? {
1233 Some(slot) => Some(slot),
1234 None => get_slot(doc, obj, key)?,
1235 };
1236 load_at(doc, slot.as_ref().map(|(value, id)| (value, id)), key)
1237}
1238
1239#[doc(hidden)]
1245pub fn write_variant_field<T: Model>(
1246 doc: &mut Doc,
1247 obj: &ObjId,
1248 storage: &str,
1249 key: &str,
1250 value: &T,
1251) -> Result<(), ModelError> {
1252 value.store(doc, Slot::Key(obj, storage)).located(key)
1253}
1254
1255#[doc(hidden)]
1260pub fn read_variant_atom<T: crate::table::Atomic>(
1261 doc: &Doc,
1262 obj: &ObjId,
1263 storage: &str,
1264 key: &str,
1265) -> Result<T, ModelError> {
1266 let slot = match get_slot(doc, obj, storage)? {
1267 Some(slot) => Some(slot),
1268 None => get_slot(doc, obj, key)?,
1269 };
1270 let atom = crate::table::Run(T::ATOM);
1271 match slot {
1272 Some((value, id)) => atom.load(doc, &value, &id),
1273 None => atom.missing(),
1274 }
1275 .located(key)
1276}
1277
1278#[doc(hidden)]
1283pub fn write_variant_atom<T: crate::table::Atomic>(
1284 doc: &mut Doc,
1285 obj: &ObjId,
1286 storage: &str,
1287 key: &str,
1288 value: &T,
1289) -> Result<(), ModelError> {
1290 crate::table::Run(T::ATOM)
1291 .store(value, doc, Slot::Key(obj, storage))
1292 .located(key)
1293}
1294
1295#[doc(hidden)]
1297#[inline(never)]
1298pub fn stored_variant(doc: &Doc, value: &Value<'_>, id: &ObjId) -> Result<String, ModelError> {
1299 if !matches!(value, Value::Object(ObjType::Map)) {
1300 return Err(ModelError::shape("a map naming its variant"));
1301 }
1302 match doc.get(id, VARIANT_KEY)? {
1303 Some((Value::Scalar(name), _)) => match name.as_ref() {
1304 ScalarValue::Str(name) => Ok(name.to_string()),
1305 _ => Err(ModelError::shape("a variant name").at(VARIANT_KEY)),
1306 },
1307 _ => Err(ModelError::shape("a variant name").at(VARIANT_KEY)),
1308 }
1309}
1310
1311#[doc(hidden)]
1314#[inline(never)]
1315pub fn json_variant(
1316 value: &serde_json::Value,
1317) -> Result<(&str, &serde_json::Map<String, serde_json::Value>), ModelError> {
1318 let serde_json::Value::Object(fields) = value else {
1319 return Err(json_shape("an object naming its variant"));
1320 };
1321 match fields.get(VARIANT_KEY) {
1322 Some(serde_json::Value::String(name)) => Ok((name.as_str(), fields)),
1323 _ => Err(json_shape("a variant name").at(VARIANT_KEY)),
1324 }
1325}
1326
1327#[doc(hidden)]
1332pub fn json_field<T: Model>(
1333 fields: &serde_json::Map<String, serde_json::Value>,
1334 key: &str,
1335) -> Result<T, ModelError> {
1336 match fields.get(key) {
1337 Some(value) => T::from_json(value),
1338 None => T::missing(),
1339 }
1340 .located(key)
1341}
1342
1343#[doc(hidden)]
1345#[must_use]
1346#[inline(never)]
1347pub fn json_of_variant(variant: &str, fields: Vec<(&str, serde_json::Value)>) -> serde_json::Value {
1348 let mut map = serde_json::Map::new();
1349 map.insert(VARIANT_KEY.to_owned(), serde_json::Value::from(variant));
1350 for (key, value) in fields {
1351 map.insert(key.to_owned(), value);
1352 }
1353 serde_json::Value::Object(map)
1354}
1355
1356#[doc(hidden)]
1358#[must_use]
1359#[inline(never)]
1360pub fn unknown_variant(variant: &str) -> ModelError {
1361 ModelError::invalid(format!("no variant `{variant}`")).at(VARIANT_KEY)
1362}
1363
1364#[doc(hidden)]
1367#[must_use]
1368#[inline(never)]
1369pub fn variant_schema(variant: &str, fields: Vec<(&str, serde_json::Value)>) -> serde_json::Value {
1370 let mut properties = vec![(VARIANT_KEY, crate::schema::constant(variant), true)];
1371 properties.extend(fields.into_iter().map(|(key, schema)| (key, schema, false)));
1372 crate::schema::object(properties)
1373}
1374
1375fn scalar<'v>(value: &'v Value<'_>) -> Option<&'v ScalarValue> {
1376 match value {
1377 Value::Scalar(scalar) => Some(scalar.as_ref()),
1378 Value::Object(_) => None,
1379 }
1380}
1381
1382impl Settable for bool {}
1383impl Model for bool {
1384 const SCALAR: bool = true;
1385 crate::__own_table!(bool);
1386 fn value_schema() -> serde_json::Value {
1387 serde_json::json!({"type": "boolean"})
1388 }
1389 fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
1390 let _ = types;
1391 crate::FieldType::Bool
1392 }
1393 leaf_paths!();
1394 #[inline(never)]
1395 fn to_json(&self) -> serde_json::Value {
1396 serde_json::Value::Bool(*self)
1397 }
1398 #[inline(never)]
1399 fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
1400 match value {
1401 serde_json::Value::Bool(value) => Ok(*value),
1402 serde_json::Value::Null => Ok(false),
1403 _ => Err(json_shape("a boolean")),
1404 }
1405 }
1406 #[inline(never)]
1407 fn load(_: &Doc, value: &Value<'_>, _: &ObjId) -> Result<Self, ModelError> {
1408 match scalar(value) {
1409 Some(ScalarValue::Boolean(value)) => Ok(*value),
1410 Some(ScalarValue::Null) => Ok(false),
1411 _ => Err(ModelError::shape("a boolean")),
1412 }
1413 }
1414 fn missing() -> Result<Self, ModelError> {
1415 Ok(false)
1416 }
1417 #[inline(never)]
1418 fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
1419 slot.put_scalar(doc, ScalarValue::Boolean(*self))
1420 }
1421 fn fresh(&self, _: automerge::TextEncoding) -> Fresh {
1422 Fresh::scalar(ScalarValue::Boolean(*self))
1423 }
1424 #[inline(never)]
1425 fn stores_as(&self, before: &Self) -> bool {
1426 self == before
1427 }
1428}
1429
1430macro_rules! integer_model {
1431 ($($ty:ty),*) => {$(
1432 impl Settable for $ty {}
1433 impl Model for $ty {
1434 const SCALAR: bool = true;
1435 crate::__own_table!($ty);
1436 fn value_schema() -> serde_json::Value {
1437 serde_json::json!({"type": "integer"})
1438 }
1439 fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
1440 let _ = types;
1441 crate::FieldType::Int
1442 }
1443 leaf_paths!();
1444 fn to_json(&self) -> serde_json::Value {
1445 serde_json::Value::from(*self)
1446 }
1447 fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
1448 let wide: i128 = match value {
1449 serde_json::Value::Number(number) => number
1450 .as_i64()
1451 .map(i128::from)
1452 .or_else(|| number.as_u64().map(i128::from))
1453 .ok_or_else(|| json_shape("an integer"))?,
1454 serde_json::Value::Null => 0,
1455 _ => return Err(json_shape("an integer")),
1456 };
1457 <$ty>::try_from(wide).map_err(|_| ModelError::invalid("integer out of range"))
1458 }
1459 fn load(_: &Doc, value: &Value<'_>, _: &ObjId) -> Result<Self, ModelError> {
1460 let wide: i128 = match scalar(value) {
1461 Some(ScalarValue::Int(value)) => i128::from(*value),
1462 Some(ScalarValue::Uint(value)) => i128::from(*value),
1463 Some(ScalarValue::Counter(counter)) => i128::from(i64::from(counter)),
1464 Some(ScalarValue::Timestamp(value)) => i128::from(*value),
1465 Some(ScalarValue::Null) => 0,
1466 _ => return Err(ModelError::shape("an integer")),
1467 };
1468 <$ty>::try_from(wide).map_err(|_| ModelError::invalid("integer out of range"))
1469 }
1470 fn missing() -> Result<Self, ModelError> {
1471 Ok(0)
1472 }
1473 fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
1474 let value = i64::try_from(*self)
1475 .map(ScalarValue::Int)
1476 .or_else(|_| u64::try_from(*self).map(ScalarValue::Uint))
1477 .map_err(|_| ModelError::invalid("integer out of range"))?;
1478 slot.put_scalar(doc, value)
1479 }
1480 fn fresh(&self, _: automerge::TextEncoding) -> Fresh {
1481 match i64::try_from(*self) {
1482 Ok(value) => Fresh::scalar(ScalarValue::Int(value)),
1483 Err(_) => u64::try_from(*self)
1484 .map_or(Fresh::Store, |value| Fresh::scalar(ScalarValue::Uint(value))),
1485 }
1486 }
1487 fn stores_as(&self, before: &Self) -> bool {
1488 self == before
1489 }
1490 }
1491 )*};
1492}
1493integer_model!(i8, i16, i32, i64, u8, u16, u32, u64, usize, isize);
1494
1495impl Settable for f64 {}
1496impl Model for f64 {
1497 const SCALAR: bool = true;
1498 crate::__own_table!(f64);
1499 fn value_schema() -> serde_json::Value {
1500 serde_json::json!({"type": "number"})
1501 }
1502 fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
1503 let _ = types;
1504 crate::FieldType::Float
1505 }
1506 leaf_paths!();
1507 #[inline(never)]
1508 fn to_json(&self) -> serde_json::Value {
1509 serde_json::Number::from_f64(*self)
1510 .map_or(serde_json::Value::Null, serde_json::Value::Number)
1511 }
1512 #[inline(never)]
1513 fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
1514 match value {
1515 serde_json::Value::Number(number) => {
1516 number.as_f64().ok_or_else(|| json_shape("a number"))
1517 }
1518 serde_json::Value::Null => Ok(0.0),
1519 _ => Err(json_shape("a number")),
1520 }
1521 }
1522 #[allow(
1523 clippy::cast_precision_loss,
1524 reason = "integers written by older schemas widen to the stored float"
1525 )]
1526 #[inline(never)]
1527 fn load(_: &Doc, value: &Value<'_>, _: &ObjId) -> Result<Self, ModelError> {
1528 match scalar(value) {
1529 Some(ScalarValue::F64(value)) => Ok(*value),
1530 Some(ScalarValue::Int(value)) => Ok(*value as f64),
1531 Some(ScalarValue::Uint(value)) => Ok(*value as f64),
1532 Some(ScalarValue::Null) => Ok(0.0),
1533 _ => Err(ModelError::shape("a number")),
1534 }
1535 }
1536 fn missing() -> Result<Self, ModelError> {
1537 Ok(0.0)
1538 }
1539 #[inline(never)]
1540 fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
1541 slot.put_scalar(doc, ScalarValue::F64(*self))
1542 }
1543 fn fresh(&self, _: automerge::TextEncoding) -> Fresh {
1544 Fresh::scalar(ScalarValue::F64(*self))
1545 }
1546 #[inline(never)]
1547 fn stores_as(&self, before: &Self) -> bool {
1548 self.to_bits() == before.to_bits()
1549 }
1550}
1551
1552impl Settable for f32 {}
1553impl Model for f32 {
1554 const SCALAR: bool = true;
1555 crate::__own_table!(f32);
1556 fn value_schema() -> serde_json::Value {
1557 serde_json::json!({"type": "number"})
1558 }
1559 fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
1560 let _ = types;
1561 crate::FieldType::Float
1562 }
1563 leaf_paths!();
1564 #[inline(never)]
1565 fn to_json(&self) -> serde_json::Value {
1566 f64::from(*self).to_json()
1567 }
1568 #[allow(
1569 clippy::cast_possible_truncation,
1570 reason = "an f32 field stores what it wrote, widened"
1571 )]
1572 #[inline(never)]
1573 fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
1574 f64::from_json(value).map(|value| value as f32)
1575 }
1576 #[allow(
1577 clippy::cast_possible_truncation,
1578 reason = "an f32 field stores what it wrote, widened"
1579 )]
1580 #[inline(never)]
1581 fn load(doc: &Doc, value: &Value<'_>, id: &ObjId) -> Result<Self, ModelError> {
1582 f64::load(doc, value, id).map(|value| value as f32)
1583 }
1584 fn missing() -> Result<Self, ModelError> {
1585 Ok(0.0)
1586 }
1587 #[inline(never)]
1588 fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
1589 f64::from(*self).store(doc, slot)
1590 }
1591 fn fresh(&self, encoding: automerge::TextEncoding) -> Fresh {
1592 f64::from(*self).fresh(encoding)
1593 }
1594 #[inline(never)]
1595 fn stores_as(&self, before: &Self) -> bool {
1596 self.to_bits() == before.to_bits()
1597 }
1598}
1599
1600impl Settable for String {}
1605impl Model for String {
1606 crate::__own_table!(String);
1607 fn value_schema() -> serde_json::Value {
1608 serde_json::json!({"type": "string"})
1609 }
1610 fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
1611 let _ = types;
1612 crate::FieldType::Text
1613 }
1614 leaf_paths!();
1615 #[inline(never)]
1616 fn to_json(&self) -> serde_json::Value {
1617 serde_json::Value::String(self.clone())
1618 }
1619 #[inline(never)]
1620 fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
1621 match value {
1622 serde_json::Value::String(text) => Ok(text.clone()),
1623 serde_json::Value::Null => Ok(Self::new()),
1624 _ => Err(json_shape("text")),
1625 }
1626 }
1627 #[inline(never)]
1628 fn edit(
1629 doc: &mut Doc,
1630 slot: Slot<'_>,
1631 path: &[Segment],
1632 op: &EditOp,
1633 _cx: &mut ActionCx,
1634 ) -> Result<(), ModelError> {
1635 let edit = match op {
1636 EditOp::Splice { at, delete, insert } if path.is_empty() => crate::TextEdit::Splice {
1637 at: *at,
1638 delete: *delete,
1639 insert: insert.clone(),
1640 },
1641 EditOp::Replace { text } if path.is_empty() => {
1642 crate::TextEdit::ReplaceText { text: text.clone() }
1643 }
1644 _ => return edit_whole::<Self>(doc, slot, path, op),
1645 };
1646 let text = slot.object(doc, ObjType::Text)?;
1647 edit.apply_under(doc, &text).map_err(|error| match error {
1648 tilo_actions::ActionError::Refused(reason) => ModelError::Refused(reason),
1649 tilo_actions::ActionError::Declined(reason) => ModelError::Declined(reason),
1650 other => ModelError::invalid(other.to_string()),
1651 })
1652 }
1653 #[inline(never)]
1654 fn load(doc: &Doc, value: &Value<'_>, id: &ObjId) -> Result<Self, ModelError> {
1655 match value {
1656 Value::Object(ObjType::Text) => Ok(doc.text(id)?),
1657 Value::Scalar(scalar) => match scalar.as_ref() {
1658 ScalarValue::Str(text) => Ok(text.to_string()),
1659 ScalarValue::Null => Ok(Self::new()),
1660 _ => Err(ModelError::shape("text")),
1661 },
1662 Value::Object(_) => Err(ModelError::shape("text")),
1663 }
1664 }
1665 fn missing() -> Result<Self, ModelError> {
1666 Ok(Self::new())
1667 }
1668 #[inline(never)]
1669 fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
1670 let text = slot.object(doc, ObjType::Text)?;
1671 let current = doc.text(&text)?;
1672 if current != *self {
1673 splice_changed_span(doc, &text, ¤t, self)?;
1674 }
1675 Ok(())
1676 }
1677 fn fresh(&self, encoding: automerge::TextEncoding) -> Fresh {
1679 Fresh::Value(automerge::hydrate::Value::Text(crate::text::authored(
1680 encoding, self,
1681 )))
1682 }
1683 #[inline(never)]
1684 fn stores_as(&self, before: &Self) -> bool {
1685 self == before
1686 }
1687 #[inline(never)]
1690 fn store_changed(
1691 &self,
1692 before: &Self,
1693 doc: &mut Doc,
1694 slot: Slot<'_>,
1695 _dirty: &Delta,
1696 ) -> Result<(), ModelError> {
1697 let text = slot.object(doc, ObjType::Text)?;
1698 if before != self {
1699 splice_changed_span(doc, &text, before, self)?;
1700 }
1701 Ok(())
1702 }
1703 fn collect_text(&self, out: &mut Vec<String>) {
1704 if !self.is_empty() {
1705 out.push(self.clone());
1706 }
1707 }
1708}
1709
1710fn splice_changed_span(
1726 doc: &mut Doc,
1727 text: &ObjId,
1728 old: &str,
1729 new: &str,
1730) -> Result<(), ModelError> {
1731 let width = |part: &str| match doc.text_encoding() {
1732 automerge::TextEncoding::UnicodeCodePoint => Some(part.chars().count()),
1733 automerge::TextEncoding::Utf8CodeUnit => Some(part.len()),
1734 automerge::TextEncoding::Utf16CodeUnit => Some(part.encode_utf16().count()),
1735 automerge::TextEncoding::GraphemeCluster => None,
1736 };
1737 let prefix = old
1738 .char_indices()
1739 .zip(new.chars())
1740 .find(|((_, a), b)| a != b)
1741 .map_or_else(|| old.len().min(new.len()), |((index, _), _)| index);
1742 let prefix = (0..=prefix)
1743 .rev()
1744 .find(|&index| old.is_char_boundary(index) && new.is_char_boundary(index))
1745 .unwrap_or(0);
1746 let (old_rest, new_rest) = (
1747 old.get(prefix..).unwrap_or(""),
1748 new.get(prefix..).unwrap_or(""),
1749 );
1750 let suffix = old_rest
1751 .chars()
1752 .rev()
1753 .zip(new_rest.chars().rev())
1754 .take_while(|(a, b)| a == b)
1755 .map(|(a, _)| a.len_utf8())
1756 .sum::<usize>();
1757 let removed = old_rest
1758 .get(..old_rest.len().saturating_sub(suffix))
1759 .unwrap_or("");
1760 let inserted = new_rest
1761 .get(..new_rest.len().saturating_sub(suffix))
1762 .unwrap_or("");
1763 match (width(old.get(..prefix).unwrap_or("")), width(removed)) {
1764 (Some(position), Some(deleted)) => {
1765 let deleted =
1766 isize::try_from(deleted).map_err(|_| ModelError::invalid("text too long"))?;
1767 doc.splice_text(text, position, deleted, inserted)?;
1768 crate::text::mark_authored(doc, text, position, inserted)
1772 .map_err(|error| ModelError::invalid(error.to_string()))?;
1773 }
1774 _ => doc.update_text(text, new)?,
1775 }
1776 Ok(())
1777}
1778
1779#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
1782pub struct Atom(pub String);
1783
1784impl Settable for Atom {}
1785impl Model for Atom {
1786 const SCALAR: bool = true;
1787 crate::__own_table!(Atom);
1788 fn value_schema() -> serde_json::Value {
1789 serde_json::json!({"type": "string"})
1790 }
1791 fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
1792 let _ = types;
1793 crate::FieldType::Text
1794 }
1795 leaf_paths!();
1796 #[inline(never)]
1797 fn to_json(&self) -> serde_json::Value {
1798 serde_json::Value::String(self.0.clone())
1799 }
1800 #[inline(never)]
1801 fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
1802 String::from_json(value).map(Self)
1803 }
1804 #[inline(never)]
1805 fn load(doc: &Doc, value: &Value<'_>, id: &ObjId) -> Result<Self, ModelError> {
1806 String::load(doc, value, id).map(Self)
1807 }
1808 fn missing() -> Result<Self, ModelError> {
1809 Ok(Self::default())
1810 }
1811 #[inline(never)]
1812 fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
1813 slot.put_scalar(doc, ScalarValue::Str(self.0.as_str().into()))
1814 }
1815 fn fresh(&self, _: automerge::TextEncoding) -> Fresh {
1816 Fresh::scalar(ScalarValue::Str(self.0.as_str().into()))
1817 }
1818 fn collect_text(&self, out: &mut Vec<String>) {
1819 if !self.0.is_empty() {
1820 out.push(self.0.clone());
1821 }
1822 }
1823 #[inline(never)]
1824 fn stores_as(&self, before: &Self) -> bool {
1825 self == before
1826 }
1827}
1828
1829impl Settable for uuid::Uuid {}
1830impl Model for uuid::Uuid {
1831 crate::__own_table!(uuid::Uuid);
1832 fn value_schema() -> serde_json::Value {
1833 serde_json::json!({"type": "string", "format": "uuid"})
1834 }
1835 fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
1836 let _ = types;
1837 crate::FieldType::Text
1838 }
1839 leaf_paths!();
1840 #[inline(never)]
1841 fn to_json(&self) -> serde_json::Value {
1842 serde_json::Value::String(self.to_string())
1843 }
1844 #[inline(never)]
1845 fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
1846 match value {
1847 serde_json::Value::String(text) => {
1848 Self::parse_str(text).map_err(|error| ModelError::invalid(error.to_string()))
1849 }
1850 _ => Err(json_shape("a uuid")),
1851 }
1852 }
1853 #[inline(never)]
1854 fn load(_: &Doc, value: &Value<'_>, _: &ObjId) -> Result<Self, ModelError> {
1855 match scalar(value) {
1856 Some(ScalarValue::Str(text)) => {
1857 Self::parse_str(text).map_err(|error| ModelError::invalid(error.to_string()))
1858 }
1859 _ => Err(ModelError::shape("a uuid")),
1860 }
1861 }
1862 #[inline(never)]
1863 fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
1864 slot.put_scalar(doc, ScalarValue::Str(self.to_string().into()))
1865 }
1866 #[inline(never)]
1867 fn stores_as(&self, before: &Self) -> bool {
1868 self == before
1869 }
1870}
1871
1872impl<T: Settable> Settable for Option<T> {}
1874impl<T: Model> Model for Option<T> {
1875 fn value_schema() -> serde_json::Value {
1876 crate::schema::nullable(T::value_schema())
1877 }
1878 fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
1879 crate::FieldType::Option(Box::new(T::field_type(types)))
1880 }
1881 const SHAPE: crate::Shape = T::SHAPE;
1882 const CHECKS: bool = T::CHECKS;
1883 const OPS: bool = T::OPS;
1884 const NULLABLE: bool = true;
1885 const TABLE: &'static crate::table::ModelTable = &crate::table::OptionOf::<T>::TABLE;
1886 leaf_paths!();
1887 crate::__table_functions!();
1888 fn label(&self) -> Option<String> {
1889 self.as_ref().and_then(Model::label)
1890 }
1891 fn missing() -> Result<Self, ModelError> {
1892 Ok(None)
1893 }
1894}
1895
1896impl<T: Settable> Settable for Box<T> {}
1897impl<T: Model> Model for Box<T> {
1898 const SCALAR: bool = T::SCALAR;
1899 fn value_schema() -> serde_json::Value {
1900 T::value_schema()
1901 }
1902 fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
1903 T::field_type(types)
1904 }
1905 const SHAPE: crate::Shape = T::SHAPE;
1906 const CHECKS: bool = T::CHECKS;
1907 const OPS: bool = T::OPS;
1908 const NULLABLE: bool = T::NULLABLE;
1909 fn op_coalesces(
1910 path: &[Segment],
1911 previous: &serde_json::Value,
1912 next: &serde_json::Value,
1913 ) -> Option<bool> {
1914 if T::OPS {
1915 T::op_coalesces(path, previous, next)
1916 } else {
1917 None
1918 }
1919 }
1920 fn op_continuable(path: &[Segment], op: &serde_json::Value) -> Option<bool> {
1921 if T::OPS {
1922 T::op_continuable(path, op)
1923 } else {
1924 None
1925 }
1926 }
1927 fn op_describe(path: &[Segment], op: &serde_json::Value) -> Option<crate::path::OpDescription> {
1928 if T::OPS {
1929 T::op_describe(path, op)
1930 } else {
1931 None
1932 }
1933 }
1934 fn op_lands(&self, path: &[Segment], op: &serde_json::Value) -> Option<crate::Place> {
1935 if T::OPS {
1936 (**self).op_lands(path, op)
1937 } else {
1938 None
1939 }
1940 }
1941 fn op_schemas(prefix: &str, out: &mut Vec<(String, serde_json::Value)>) {
1942 if T::OPS {
1943 T::op_schemas(prefix, out);
1944 }
1945 }
1946 type Paths<R> = T::Paths<R>;
1947 fn paths_at<R>(path: Path<R, Self>) -> T::Paths<R> {
1948 T::paths_at(path.cast())
1949 }
1950 #[inline(never)]
1951 fn to_json(&self) -> serde_json::Value {
1952 (**self).to_json()
1953 }
1954 #[inline(never)]
1955 fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
1956 T::from_json(value).map(Box::new)
1957 }
1958 #[inline(never)]
1959 fn edit(
1960 doc: &mut Doc,
1961 slot: Slot<'_>,
1962 path: &[Segment],
1963 op: &EditOp,
1964 cx: &mut ActionCx,
1965 ) -> Result<(), ModelError> {
1966 T::edit(doc, slot, path, op, cx)
1967 }
1968 fn check(&self) -> Result<(), Refusal> {
1969 (**self).check()
1970 }
1971 #[inline(never)]
1972 fn diff<R>(&self, after: &Self, path: &[Segment], out: &mut Vec<crate::Edit<R>>) {
1973 (**self).diff(after, path, out);
1974 }
1975 fn label(&self) -> Option<String> {
1976 (**self).label()
1977 }
1978 fn get_at(&self, path: &[Segment]) -> Option<&dyn std::any::Any>
1979 where
1980 Self: 'static,
1981 {
1982 (**self).get_at(path)
1983 }
1984
1985 #[inline(never)]
1986 fn load(doc: &Doc, value: &Value<'_>, id: &ObjId) -> Result<Self, ModelError> {
1987 T::load(doc, value, id).map(Box::new)
1988 }
1989 fn missing() -> Result<Self, ModelError> {
1990 T::missing().map(Box::new)
1991 }
1992 #[inline(never)]
1993 fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
1994 (**self).store(doc, slot)
1995 }
1996 #[inline(never)]
1997 fn stores_as(&self, before: &Self) -> bool {
1998 (**self).stores_as(before)
1999 }
2000 #[inline(never)]
2001 fn store_changed(
2002 &self,
2003 before: &Self,
2004 doc: &mut Doc,
2005 slot: Slot<'_>,
2006 dirty: &Delta,
2007 ) -> Result<(), ModelError> {
2008 (**self).store_changed(before, doc, slot, dirty)
2009 }
2010 #[inline(never)]
2011 fn refresh(
2012 &mut self,
2013 doc: &Doc,
2014 value: &Value<'_>,
2015 id: &ObjId,
2016 delta: &Delta,
2017 ) -> Result<(), ModelError> {
2018 (**self).refresh(doc, value, id, delta)
2019 }
2020 fn collect_text(&self, out: &mut Vec<String>) {
2021 (**self).collect_text(out);
2022 }
2023}
2024
2025impl<T: Model> Settable for Vec<T> {}
2030impl<T: Model> Model for Vec<T> {
2031 fn value_schema() -> serde_json::Value {
2032 serde_json::json!({"type": "array", "items": T::value_schema()})
2033 }
2034 fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
2035 crate::FieldType::List(Box::new(T::field_type(types)))
2036 }
2037 const CHECKS: bool = T::CHECKS;
2038 const OPS: bool = T::OPS;
2039 const TABLE: &'static crate::table::ModelTable = &crate::table::VecOf::<T>::TABLE;
2040 leaf_paths!();
2041 crate::__table_functions!();
2042 fn missing() -> Result<Self, ModelError> {
2043 Ok(Self::new())
2044 }
2045}
2046
2047impl<T: Model, const N: usize> Settable for [T; N] {}
2049impl<T: Model, const N: usize> Model for [T; N] {
2050 fn value_schema() -> serde_json::Value {
2051 serde_json::json!({"type": "array", "items": T::value_schema(), "minItems": N, "maxItems": N})
2052 }
2053 fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
2054 crate::FieldType::List(Box::new(T::field_type(types)))
2055 }
2056 const CHECKS: bool = T::CHECKS;
2057 const OPS: bool = T::OPS;
2058 leaf_paths!();
2059 #[inline(never)]
2060 fn to_json(&self) -> serde_json::Value {
2061 serde_json::Value::Array(self.iter().map(Model::to_json).collect())
2062 }
2063 #[inline(never)]
2064 fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
2065 let items = Vec::<T>::from_json(value)?;
2066 let count = items.len();
2067 items
2068 .try_into()
2069 .map_err(|_| ModelError::invalid(format!("expected {N} values, not {count}")))
2070 }
2071 #[inline(never)]
2072 fn load(doc: &Doc, value: &Value<'_>, id: &ObjId) -> Result<Self, ModelError> {
2073 let items = Vec::<T>::load(doc, value, id)?;
2074 let count = items.len();
2075 items
2076 .try_into()
2077 .map_err(|_| ModelError::invalid(format!("expected {N} values, not {count}")))
2078 }
2079 fn missing() -> Result<Self, ModelError> {
2080 let items = (0..N)
2081 .map(|_| T::missing())
2082 .collect::<Result<Vec<_>, _>>()?;
2083 items
2084 .try_into()
2085 .map_err(|_| ModelError::invalid("an empty array"))
2086 }
2087 #[inline(never)]
2088 fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
2089 let list = slot.object(doc, ObjType::List)?;
2090 let existing = doc.length(&list);
2091 for (index, item) in self.iter().enumerate() {
2092 let slot = if index < existing {
2093 Slot::Index(&list, index)
2094 } else {
2095 Slot::Insert(&list, index)
2096 };
2097 item.store(doc, slot).located(&index.to_string())?;
2098 }
2099 for index in (N..existing).rev() {
2100 doc.delete(&list, index)?;
2101 }
2102 Ok(())
2103 }
2104}
2105
2106impl<T: Model> Settable for BTreeMap<String, T> {}
2108impl<T: Model> Model for BTreeMap<String, T> {
2109 const SHAPE: crate::Shape = crate::Shape::Map(&T::SHAPE);
2110 fn value_schema() -> serde_json::Value {
2111 serde_json::json!({"type": "object"})
2112 }
2113 fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
2114 crate::FieldType::Map(Box::new(T::field_type(types)))
2115 }
2116 const CHECKS: bool = T::CHECKS;
2117 const OPS: bool = T::OPS;
2118 const TABLE: &'static crate::table::ModelTable = &crate::table::MapOf::<T>::TABLE;
2119 leaf_paths!();
2120 crate::__table_functions!();
2121 fn missing() -> Result<Self, ModelError> {
2122 Ok(Self::new())
2123 }
2124}
2125
2126macro_rules! json_scalar {
2130 ($ty:path, $field_type:ident) => {
2131 impl Settable for $ty {}
2132 impl Model for $ty {
2133 const SCALAR: bool = true;
2134 crate::__own_table!($ty);
2135 fn value_schema() -> serde_json::Value {
2136 serde_json::json!({})
2137 }
2138 fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
2139 let _ = types;
2140 crate::FieldType::$field_type
2141 }
2142 type Paths<R> = crate::Path<R, Self>;
2143
2144 fn paths_at<R>(path: crate::Path<R, Self>) -> crate::Path<R, Self> {
2145 path
2146 }
2147
2148 #[inline(never)]
2149 fn to_json(&self) -> serde_json::Value {
2150 serde_json::to_value(self).unwrap_or(serde_json::Value::Null)
2151 }
2152
2153 #[inline(never)]
2154 fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
2155 serde_json::from_value(value.clone())
2156 .map_err(|error| ModelError::invalid(error.to_string()))
2157 }
2158
2159 #[inline(never)]
2160 fn load(_: &Doc, value: &Value<'_>, _: &ObjId) -> Result<Self, ModelError> {
2161 match scalar(value) {
2162 Some(ScalarValue::Str(text)) => serde_json::from_str(text)
2163 .map_err(|error| ModelError::invalid(error.to_string())),
2164 _ => Err(ModelError::shape("a stored member")),
2165 }
2166 }
2167
2168 #[inline(never)]
2169 fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
2170 let text = serde_json::to_string(self)
2171 .map_err(|error| ModelError::invalid(error.to_string()))?;
2172 slot.put_scalar(doc, ScalarValue::Str(text.into()))
2173 }
2174
2175 fn fresh(&self, _: automerge::TextEncoding) -> Fresh {
2176 serde_json::to_string(self).map_or(Fresh::Store, |text| {
2177 Fresh::scalar(ScalarValue::Str(text.into()))
2178 })
2179 }
2180
2181 #[inline(never)]
2182 fn stores_as(&self, before: &Self) -> bool {
2183 self == before
2184 }
2185 }
2186 };
2187}
2188
2189json_scalar!(tilo_action_policy::MemberId, Actor);
2192json_scalar!(tilo_action_policy::Actor, Actor);
2193json_scalar!(tilo_action_policy::Grantee, Text);
2194json_scalar!(tilo_action_policy::Lifetime, Text);
2195
2196impl Settable for tilo_app_id::AppId {}
2198impl Model for tilo_app_id::AppId {
2199 const SCALAR: bool = true;
2200 crate::__own_table!(tilo_app_id::AppId);
2201 fn value_schema() -> serde_json::Value {
2202 serde_json::json!({"type": "string"})
2203 }
2204 fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
2205 let _ = types;
2206 crate::FieldType::Text
2207 }
2208 type Paths<R> = crate::Path<R, Self>;
2209
2210 fn paths_at<R>(path: crate::Path<R, Self>) -> crate::Path<R, Self> {
2211 path
2212 }
2213
2214 #[inline(never)]
2215 fn to_json(&self) -> serde_json::Value {
2216 serde_json::Value::String(self.as_str().to_owned())
2217 }
2218
2219 #[inline(never)]
2220 fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
2221 match value {
2222 serde_json::Value::String(text) => Ok(Self::new(text.clone())),
2223 _ => Err(ModelError::shape("an app id")),
2224 }
2225 }
2226
2227 #[inline(never)]
2228 fn load(_: &Doc, value: &Value<'_>, _: &ObjId) -> Result<Self, ModelError> {
2229 match scalar(value) {
2230 Some(ScalarValue::Str(text)) => Ok(Self::new(text.to_string())),
2231 _ => Err(ModelError::shape("an app id")),
2232 }
2233 }
2234
2235 #[inline(never)]
2236 fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
2237 slot.put_scalar(doc, ScalarValue::Str(self.as_str().to_owned().into()))
2238 }
2239
2240 fn fresh(&self, _: automerge::TextEncoding) -> Fresh {
2241 Fresh::scalar(ScalarValue::Str(self.as_str().to_owned().into()))
2242 }
2243
2244 #[inline(never)]
2245 fn stores_as(&self, before: &Self) -> bool {
2246 self == before
2247 }
2248}
2249
2250#[cfg(test)]
2251mod tests {
2252 use super::*;
2253 use automerge::ROOT;
2254 use tilo_automerge::ApplyIncoming;
2255
2256 tilo_test_env::scenario! {
2257 fn writes_become_minimal_mergeable_operations;
2258
2259 phase unchanged_writes_produce_no_operations;
2260 {
2261 let mut doc = Doc::new();
2262 write_key(&mut doc, &ROOT, "title", &"hello".to_owned()).unwrap();
2263 write_key(&mut doc, &ROOT, "count", &3_u32).unwrap();
2264 write_key(&mut doc, &ROOT, "tags", &vec![1_i64, 2]).unwrap();
2265 doc.commit();
2266 write_key(&mut doc, &ROOT, "title", &"hello".to_owned()).unwrap();
2267 write_key(&mut doc, &ROOT, "count", &3_u32).unwrap();
2268 write_key(&mut doc, &ROOT, "tags", &vec![1_i64, 2]).unwrap();
2269 assert_eq!(doc.pending_ops(), 0);
2270 assert_eq!(read_key::<String>(&doc, &ROOT, "title").unwrap(), "hello");
2271 assert_eq!(read_key::<Vec<i64>>(&doc, &ROOT, "tags").unwrap(), [1, 2]);
2272 assert_eq!(read_key::<Option<u8>>(&doc, &ROOT, "absent").unwrap(), None);
2273 }
2274
2275 phase text_splices_merge_concurrent_edits;
2276 {
2277 let mut base = Doc::new();
2278 write_key(&mut base, &ROOT, "body", &"hello world".to_owned()).unwrap();
2279 base.commit();
2280 let mut left = base.fork();
2281 let mut right = base.fork();
2282 write_key(&mut left, &ROOT, "body", &"hello brave world".to_owned()).unwrap();
2283 write_key(&mut right, &ROOT, "body", &"hello world!".to_owned()).unwrap();
2284 left.merge_incoming(&mut right).unwrap();
2285 assert_eq!(
2286 read_key::<String>(&left, &ROOT, "body").unwrap(),
2287 "hello brave world!"
2288 );
2289 }
2290
2291 phase a_text_edit_is_one_splice_of_the_changed_span;
2292 {
2293 for (old, new) in [
2294 ("first thought", "second thought"),
2295 ("café 日本語", "café 日本 語!"),
2296 ("abc", ""),
2297 ("", "abc"),
2298 ("aaa", "aa"),
2299 ("ab", "ba"),
2300 ] {
2301 let mut doc = Doc::new();
2302 write_key(&mut doc, &ROOT, "t", &old.to_owned()).unwrap();
2303 doc.commit();
2304 write_key(&mut doc, &ROOT, "t", &new.to_owned()).unwrap();
2305 doc.commit();
2306 assert_eq!(read_key::<String>(&doc, &ROOT, "t").unwrap(), new);
2307 }
2308 }
2309 }
2310}