diff --git a/tiled/src/lib.rs b/tiled/src/lib.rs index 9ee98eb9..1c39c524 100644 --- a/tiled/src/lib.rs +++ b/tiled/src/lib.rs @@ -8,7 +8,7 @@ mod error; mod tiled; pub use error::Error; -pub use tiled::layer::Property; +pub use tiled::{Property, PropertyVal}; #[derive(Debug, Clone)] pub struct Object { diff --git a/tiled/src/tiled.rs b/tiled/src/tiled.rs index 2cf6db7d..b97a319a 100644 --- a/tiled/src/tiled.rs +++ b/tiled/src/tiled.rs @@ -1,8 +1,60 @@ +use layer::Layer; use nanoserde::DeJson; pub mod layer; -use layer::Layer; +#[derive(Debug, Clone)] +pub enum PropertyVal { + String(String), + UInt(u64), + Integer(i64), + Float(f64), + Boolean(bool), +} + +impl Default for PropertyVal { + fn default() -> Self { + PropertyVal::Boolean(false) + } +} + +impl std::fmt::Display for PropertyVal { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + PropertyVal::String(x) => write!(f, "{}", x), + PropertyVal::UInt(x) => write!(f, "{}", x), + PropertyVal::Integer(x) => write!(f, "{}", x), + PropertyVal::Float(x) => write!(f, "{}", x), + PropertyVal::Boolean(x) => write!(f, "{}", x), + } + } +} + +impl DeJson for PropertyVal { + fn de_json( + s: &mut nanoserde::DeJsonState, + i: &mut std::str::Chars, + ) -> Result { + use nanoserde::DeJsonTok; + + let v = match s.tok { + DeJsonTok::Bool(b) => PropertyVal::Boolean(b), + DeJsonTok::U64(x) => PropertyVal::UInt(x), + DeJsonTok::I64(x) => PropertyVal::Integer(x), + DeJsonTok::F64(x) => PropertyVal::Float(x), + DeJsonTok::Str => PropertyVal::String(core::mem::replace(&mut s.strbuf, String::new())), + _ => { + return Err(s.err_token( + "Incorrect property value. Must be either string, number or boolean", + )) + } + }; + + s.next_tok(i)?; + + Ok(v) + } +} /// https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#tmx-grid #[derive(Clone, Debug, Default, DeJson)] @@ -14,7 +66,7 @@ pub struct Grid { #[derive(Clone, Debug, Default, DeJson)] pub struct Property { pub name: String, - pub value: String, + pub value: PropertyVal, #[nserde(rename = "type")] pub ty: String, } diff --git a/tiled/src/tiled/layer.rs b/tiled/src/tiled/layer.rs index 36ec7998..7b4ce7b1 100644 --- a/tiled/src/tiled/layer.rs +++ b/tiled/src/tiled/layer.rs @@ -1,3 +1,4 @@ +use super::Property; use nanoserde::DeJson; /// https://doc.mapeditor.org/en/stable/reference/json-map-format/#json-chunk @@ -51,15 +52,6 @@ pub struct Layer { pub image: Option, } -#[derive(Clone, Debug, Default, DeJson)] -#[nserde(default)] -pub struct Property { - pub name: String, - #[nserde(rename = "type")] - pub ty: String, - pub value: String, -} - #[derive(Clone, Debug, Default, DeJson)] #[nserde(default)] pub struct Object {