From ea066706ee9f4d7f333aae6c6f5d0c2d91bf56cf Mon Sep 17 00:00:00 2001 From: Rhys Lloyd Date: Mon, 8 Jun 2026 22:25:15 -0700 Subject: [PATCH] serialize impl --- card_game/src/lib.rs | 42 ++++++++++++++++++++++++++++++++---------- 1 file changed, 32 insertions(+), 10 deletions(-) diff --git a/card_game/src/lib.rs b/card_game/src/lib.rs index 91751d8..f011c16 100644 --- a/card_game/src/lib.rs +++ b/card_game/src/lib.rs @@ -719,16 +719,38 @@ where where S: serde::Serializer, { - if let Some(state) = self.history.first() { - state.serialize(serializer)?; + struct History<'a, G: Game>(&'a [StateSnapshot]); + impl serde::Serialize for History<'_, G> + where + G: serde::Serialize, + G::Instruction: serde::Serialize, + { + fn serialize(&self, serializer: S) -> Result + 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 { - self.state.serialize(serializer)?; - } - use serde::ser::SerializeSeq; - let mut seq = serializer.serialize_seq(Some(self.history.len()))?; - for snapshot in &self.history { - seq.serialize_element(&snapshot.instruction)?; - } - seq.end() + &self.state + }; + map.serialize_entry("state", state)?; + map.serialize_entry("history", &History(&self.history))?; + map.end() } }