diff options
| author | troido <troido@protonmail.com> | 2020-09-24 17:12:39 +0200 |
|---|---|---|
| committer | troido <troido@protonmail.com> | 2020-09-24 17:12:39 +0200 |
| commit | 5ae2f9040324baaeaed3f91a84662425cb6186dc (patch) | |
| tree | 6b76ecbe4961ef11bb48c56d752f7586a1b74212 /src/item.rs | |
| parent | e6476e7afff0234d67ebce7c74e4c91c31d87755 (diff) | |
more serde (de)serialisation
Diffstat (limited to 'src/item.rs')
| -rw-r--r-- | src/item.rs | 35 |
1 files changed, 9 insertions, 26 deletions
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<Flag>, HashSet<Flag>), @@ -41,26 +41,6 @@ pub enum ItemAction { None } -use ItemAction::{Eat, Build, Equip, None}; - -impl ItemAction { - - pub fn from_json(val: &Value) -> Option<Self> { - 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::<Option<HashSet<Flag>>>()?, - arg.get(2)?.as_array()?.iter().map(|v| Flag::from_str(v.as_str()?).ok()).collect::<Option<HashSet<Flag>>>()? - ), - "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 ); } |
