From 8461fb8379abe51233a6351357c088f153b13822 Mon Sep 17 00:00:00 2001 From: tali Date: Wed, 12 Apr 2023 00:38:50 -0400 Subject: [PATCH] derive Serialize for tidepool::Config --- tidepool/src/config.rs | 67 +++++++++++++++++++++++------------------- 1 file changed, 36 insertions(+), 31 deletions(-) diff --git a/tidepool/src/config.rs b/tidepool/src/config.rs index e73dd4f..28e622e 100644 --- a/tidepool/src/config.rs +++ b/tidepool/src/config.rs @@ -1,22 +1,25 @@ //! Config file schema (serde) for tidepool. See `example-configs/` for usage samples. -use serde::Deserialize; +use serde::{Deserialize, Serialize}; -#[derive(Deserialize, PartialEq, Debug)] +#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] pub struct Config { pub game: GameConfig, #[serde(default)] pub bot: BotConfig, } -#[derive(Deserialize, PartialEq, Debug)] +#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] pub struct GameConfig { pub goal: usize, - #[serde(default = "defaults::rules", deserialize_with = "game_rules_config")] + #[serde( + default = "defaults::rules", + deserialize_with = "de::game_rules_config" + )] pub rules: GameRulesConfig, } -#[derive(Deserialize, PartialEq, Debug)] +#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] pub struct GameRulesConfig { #[serde(default = "defaults::min_garbage")] pub min: usize, @@ -34,32 +37,7 @@ impl GameRulesConfig { }; } -fn game_rules_config<'de, D>(deserializer: D) -> Result -where - D: serde::Deserializer<'de>, -{ - // all this nonsense is to support `rules = "jstris"` as an entry - - #[derive(Deserialize)] - #[serde(untagged)] - enum Variant { - Jstris(Jstris), - Custom(GameRulesConfig), - } - - #[derive(Deserialize)] - enum Jstris { - #[serde(rename = "jstris")] - Tag, - } - - Variant::deserialize(deserializer).map(|var| match var { - Variant::Jstris(_) => GameRulesConfig::JSTRIS, - Variant::Custom(c) => c, - }) -} - -#[derive(Deserialize, PartialEq, Debug)] +#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] pub struct BotConfig { // TODO: weights // TODO: algorithm @@ -102,6 +80,33 @@ mod defaults { } } +mod de { + use super::*; + + pub fn game_rules_config<'de, D>(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + #[derive(Deserialize)] + #[serde(untagged)] + enum Variant { + Preset(Preset), + Custom(GameRulesConfig), + } + + #[derive(Deserialize)] + enum Preset { + #[serde(rename = "jstris")] + Jstris, + } + + Variant::deserialize(deserializer).map(|var| match var { + Variant::Preset(Preset::Jstris) => GameRulesConfig::JSTRIS, + Variant::Custom(c) => c, + }) + } +} + #[cfg(test)] mod test { use super::*;