Skip to content

Commit

Permalink
Add Serialize impl for LeafAnswer
Browse files Browse the repository at this point in the history
  • Loading branch information
bakaq committed Dec 14, 2024
1 parent b8af470 commit 45de3a1
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/machine/lib_machine/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,28 @@ pub enum LeafAnswer {
},
}

impl Serialize for LeafAnswer {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
LeafAnswer::True => serializer.serialize_bool(true),
LeafAnswer::False => serializer.serialize_bool(false),
LeafAnswer::Exception(e) => {
let mut map = serializer.serialize_map(Some(1))?;
map.serialize_entry("exception", &e)?;
map.end()
}
LeafAnswer::LeafAnswer { bindings } => {
let mut map = serializer.serialize_map(Some(1))?;
map.serialize_entry("bindings", &bindings)?;
map.end()
}
}
}
}

impl LeafAnswer {
/// Creates a leaf answer with no residual goals.
pub fn from_bindings<S: Into<String>>(bindings: impl IntoIterator<Item = (S, Term)>) -> Self {
Expand Down
23 changes: 23 additions & 0 deletions src/machine/lib_machine/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -692,3 +692,26 @@ fn term_json_serialize_disjunctions() {

assert_eq!(json_value, serde_json::to_value(prolog_value).unwrap());
}

#[test]
#[cfg_attr(miri, ignore)]
fn leaf_answer_json_serialize() {
let leaf_answers = [
LeafAnswer::True,
LeafAnswer::False,
LeafAnswer::Exception(Term::atom("a")),
LeafAnswer::from_bindings([("X", Term::atom("a")), ("Y", Term::string("b"))]),
];

let json_value = json!([
true,
false,
{ "exception": { "atom": "a" } },
{ "bindings": {
"X": { "atom": "a" },
"Y": "b",
}},
]);

assert_eq!(json_value, serde_json::to_value(leaf_answers).unwrap());
}

0 comments on commit 45de3a1

Please sign in to comment.