Last active
July 11, 2019 13:08
-
-
Save mexus/8e3410d0be74b88645597eaa6e66fff4 to your computer and use it in GitHub Desktop.
enum variants as keys in a toml dictionary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// [dependencies] | |
// serde = { version = "1", features = [ "derive" ] } | |
// strum = "0.15.0" | |
// strum_macros = "0.15.0" | |
// toml = "0.5.1" | |
use serde::{ | |
de::{self, Error as _}, | |
Deserialize, Deserializer, | |
}; | |
use std::{collections::HashMap, fmt}; | |
use strum_macros::EnumString; | |
#[derive(Debug, Eq, PartialEq, Hash, EnumString)] | |
#[strum(serialize_all = "snake_case")] | |
pub enum StepType { | |
Jump, | |
DoABarrelRoll, | |
} | |
#[derive(Debug, Eq, PartialEq)] | |
struct Map { | |
inner: HashMap<StepType, bool>, | |
} | |
impl<'de> Deserialize<'de> for Map { | |
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> | |
where | |
D: Deserializer<'de>, | |
{ | |
struct MapVisitor; | |
impl<'de> de::Visitor<'de> for MapVisitor { | |
type Value = Map; | |
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
f.write_str("a map of StepType -> bool") | |
} | |
fn visit_map<A>(self, mut map_access: A) -> Result<Self::Value, A::Error> | |
where | |
A: de::MapAccess<'de>, | |
{ | |
let mut dict = HashMap::new(); | |
while let Some((key, val)) = map_access.next_entry::<String, _>()? { | |
dict.insert(key.parse().map_err(A::Error::custom)?, val); | |
} | |
Ok(Map { inner: dict }) | |
} | |
} | |
deserializer.deserialize_map(MapVisitor) | |
} | |
} | |
fn main() { | |
let toml = r#"do_a_barrel_roll = true"#; | |
let parsed: Map = toml::from_str(toml).unwrap(); | |
println!("{:?}", parsed); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment