From 5ae2f9040324baaeaed3f91a84662425cb6186dc Mon Sep 17 00:00:00 2001 From: troido Date: Thu, 24 Sep 2020 17:12:39 +0200 Subject: more serde (de)serialisation --- src/item.rs | 35 +++++++++-------------------------- 1 file changed, 9 insertions(+), 26 deletions(-) (limited to 'src/item.rs') diff --git a/src/item.rs b/src/item.rs index a663634..4fdb4b8 100644 --- a/src/item.rs +++ b/src/item.rs @@ -3,8 +3,7 @@ use std::collections::HashSet; use std::str::FromStr; use serde; -use serde::Deserialize; -use serde_json::{Value}; +use serde::{Deserialize, Serialize}; use crate::{ Template, components::{ @@ -33,7 +32,8 @@ pub struct Item { pub action: ItemAction } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] pub enum ItemAction { Eat(i64), Build(Template, HashSet, HashSet), @@ -41,26 +41,6 @@ pub enum ItemAction { None } -use ItemAction::{Eat, Build, Equip, None}; - -impl ItemAction { - - pub fn from_json(val: &Value) -> Option { - let typ = val.get(0)?; - let arg = val.get(1)?; - Some(match typ.as_str()? { - "eat" => Eat(arg.as_i64()?), - "build" => Build( - Template::deserialize(arg.get(0)?).ok()?, - arg.get(1)?.as_array()?.iter().map(|v| Flag::from_str(v.as_str()?).ok()).collect::>>()?, - arg.get(2)?.as_array()?.iter().map(|v| Flag::from_str(v.as_str()?).ok()).collect::>>()? - ), - "none" => None, - "equip" => Equip(Equippable::from_json(arg)?), - _ => {return Option::None} - }) - } -} #[cfg(test)] mod tests { @@ -72,11 +52,14 @@ mod tests { #[test] fn equip_from_json() { assert_eq!( - ItemAction::from_json(&json!(["equip", {"slot": "hand", "stats": {"strength": 10}}])), - Some(ItemAction::Equip(Equippable {slot: Slot::Hand, stats: hashmap!(Stat::Strength => 10), sprite: Option::None})) + ItemAction::deserialize(&json!({"equip": {"slot": "hand", "stats": {"strength": 10}}})).unwrap(), + ItemAction::Equip(Equippable {slot: Slot::Hand, stats: hashmap!(Stat::Strength => 10), sprite: Option::None}) ); + } + #[test] + fn invalid_stat() { assert_eq!( - ItemAction::from_json(&json!(["equip", {"slot": "hand", "stats": {"attack": 50}}])), + ItemAction::deserialize(&json!({"equip": {"slot": "hand", "stats": {"attack": 50}}})).ok(), Option::None ); } -- cgit