serialize impl

This commit is contained in:
2026-06-08 22:25:15 -07:00
parent 2a844add36
commit ea066706ee
+29 -7
View File
@@ -719,16 +719,38 @@ where
where where
S: serde::Serializer, S: serde::Serializer,
{ {
if let Some(state) = self.history.first() { struct History<'a, G: Game>(&'a [StateSnapshot<G>]);
state.serialize(serializer)?; impl<G: Game> serde::Serialize for History<'_, G>
} else { where
self.state.serialize(serializer)?; G: serde::Serialize,
} G::Instruction: serde::Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let &History(history) = self;
use serde::ser::SerializeSeq; use serde::ser::SerializeSeq;
let mut seq = serializer.serialize_seq(Some(self.history.len()))?; let mut seq = serializer.serialize_seq(Some(history.len()))?;
for snapshot in &self.history { for snapshot in history {
seq.serialize_element(&snapshot.instruction)?; seq.serialize_element(&snapshot.instruction)?;
} }
seq.end() seq.end()
} }
}
use serde::ser::SerializeMap;
let mut map = serializer.serialize_map(Some(2))?;
// serialize the initial state of the game.
// if there is history, it is the first snapshot's state,
// otherwise it is the current game state since there are no moves.
let state = if let Some(snapshot) = self.history.first() {
snapshot.state()
} else {
&self.state
};
map.serialize_entry("state", state)?;
map.serialize_entry("history", &History(&self.history))?;
map.end()
}
} }