derive Serialize for tidepool::Config

This commit is contained in:
tali 2023-04-12 00:38:50 -04:00
parent 79695ef1d6
commit 8461fb8379
1 changed files with 36 additions and 31 deletions

View File

@ -1,22 +1,25 @@
//! Config file schema (serde) for tidepool. See `example-configs/` for usage samples. //! 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 struct Config {
pub game: GameConfig, pub game: GameConfig,
#[serde(default)] #[serde(default)]
pub bot: BotConfig, pub bot: BotConfig,
} }
#[derive(Deserialize, PartialEq, Debug)] #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct GameConfig { pub struct GameConfig {
pub goal: usize, 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, pub rules: GameRulesConfig,
} }
#[derive(Deserialize, PartialEq, Debug)] #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct GameRulesConfig { pub struct GameRulesConfig {
#[serde(default = "defaults::min_garbage")] #[serde(default = "defaults::min_garbage")]
pub min: usize, pub min: usize,
@ -34,32 +37,7 @@ impl GameRulesConfig {
}; };
} }
fn game_rules_config<'de, D>(deserializer: D) -> Result<GameRulesConfig, D::Error> #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
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)]
pub struct BotConfig { pub struct BotConfig {
// TODO: weights // TODO: weights
// TODO: algorithm // TODO: algorithm
@ -102,6 +80,33 @@ mod defaults {
} }
} }
mod de {
use super::*;
pub fn game_rules_config<'de, D>(deserializer: D) -> Result<GameRulesConfig, D::Error>
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)] #[cfg(test)]
mod test { mod test {
use super::*; use super::*;