serialize impl

This commit is contained in:
2026-06-08 22:25:15 -07:00
parent 2a844add36
commit ea066706ee
+32 -10
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>
where
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;
let mut seq = serializer.serialize_seq(Some(history.len()))?;
for snapshot in history {
seq.serialize_element(&snapshot.instruction)?;
}
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 { } else {
self.state.serialize(serializer)?; &self.state
} };
use serde::ser::SerializeSeq; map.serialize_entry("state", state)?;
let mut seq = serializer.serialize_seq(Some(self.history.len()))?; map.serialize_entry("history", &History(&self.history))?;
for snapshot in &self.history { map.end()
seq.serialize_element(&snapshot.instruction)?;
}
seq.end()
} }
} }