Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Term and LeafAnswer serde serialization #2707

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Add Serialize impl for LeafAnswer
bakaq committed Dec 14, 2024
commit 45de3a14a4c48f28104715fca0a872fc609515a3
22 changes: 22 additions & 0 deletions src/machine/lib_machine/mod.rs
Original file line number Diff line number Diff line change
@@ -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 {
23 changes: 23 additions & 0 deletions src/machine/lib_machine/tests.rs
Original file line number Diff line number Diff line change
@@ -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());
}