Skip to content

Commit

Permalink
Implement Reconcile for MaybeMissing
Browse files Browse the repository at this point in the history
  • Loading branch information
alexjg committed Jun 4, 2024
1 parent 46d0433 commit 123cfec
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 2 deletions.
13 changes: 12 additions & 1 deletion autosurgeon/src/hydrate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ impl<T> HydrateResultExt<Option<T>> for Result<Option<T>, HydrateError> {
/// Note that this can be combined with `Option<T>` to get both behaviours
///
/// ```rust
/// # use autosurgeon::{Hydrate, hydrate::MaybeMissing};
/// # use autosurgeon::{Hydrate, MaybeMissing};
/// # use automerge::transaction::Transactable;
/// let mut doc = automerge::AutoCommit::new();
/// let name = MaybeMissing::<Option<String>>::hydrate(&doc, &automerge::ROOT, "name".into()).unwrap();
Expand Down Expand Up @@ -332,6 +332,17 @@ impl<T: Hydrate> Hydrate for MaybeMissing<T> {
}
}

impl<T: crate::Reconcile> crate::Reconcile for MaybeMissing<T> {
type Key<'a> = T::Key<'a>;

fn reconcile<R: crate::Reconciler>(&self, reconciler: R) -> Result<(), R::Error> {
match self {
Self::Missing => Ok(()),
Self::Present(val) => val.reconcile(reconciler),
}
}
}

impl<T> MaybeMissing<T> {
pub fn unwrap_or_else<F>(self, f: F) -> T
where
Expand Down
2 changes: 1 addition & 1 deletion autosurgeon/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -459,7 +459,7 @@ mod doc;
pub use doc::{Doc, ReadDoc};
pub mod hydrate;
#[doc(inline)]
pub use hydrate::{hydrate, hydrate_path, hydrate_prop, Hydrate, HydrateError};
pub use hydrate::{hydrate, hydrate_path, hydrate_prop, Hydrate, HydrateError, MaybeMissing};
pub mod reconcile;
#[doc(inline)]
pub use reconcile::{
Expand Down
45 changes: 45 additions & 0 deletions autosurgeon/src/reconcile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1093,4 +1093,49 @@ mod tests {
}}
);
}

struct Foo {
bar: crate::hydrate::MaybeMissing<String>,
}

impl crate::Reconcile for Foo {
type Key<'a> = NoKey;

fn reconcile<R: Reconciler>(&self, mut reconciler: R) -> Result<(), R::Error> {
let mut map = reconciler.map()?;
map.put("bar", &self.bar)?;
Ok(())
}
}

#[test]
fn reconcile_maybe_missing_present() {
let mut doc = automerge::AutoCommit::new();
reconcile(
&mut doc,
&Foo {
bar: crate::MaybeMissing::Present("baz".to_string()),
},
)
.unwrap();
let val = doc.get(&automerge::ROOT, "bar").unwrap().unwrap();
assert_eq!(
val.0,
automerge::Value::Scalar(std::borrow::Cow::Owned(ScalarValue::Str("baz".into())))
);
}

#[test]
fn reconcile_maybe_missing_not_present() {
let mut doc = automerge::AutoCommit::new();
reconcile(
&mut doc,
&Foo {
bar: crate::MaybeMissing::Missing,
},
)
.unwrap();
let val = doc.get(&automerge::ROOT, "bar").unwrap();
assert!(val.is_none());
}
}

0 comments on commit 123cfec

Please sign in to comment.