1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
// Copyright (C) 2018  Adam Gausmann
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use std::collections::HashMap;

use serde::{Serialize, Serializer, Deserialize, Deserializer};

/// Dynamic typing which dictates what values can be assigned as properties.
#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)]
pub enum Property {

    /// A Boolean value.
    Boolean(bool),

    /// A signed integer value.
    Integer(i64),

    /// A signed floating-point (decimal) value.
    Number(f64),

    /// A Unicode string.
    Text(String),
}

/// Try to unwrap a referenced `Property` into `Self`.
pub trait FromProperty<'a>: Sized
{
    fn from_property(property: &'a Property) -> Option<Self>;
}

/// A set of properties indexed by their case-sensitive name.
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
/// use tsukurou::properties::Properties;
/// 
/// // Properties can be initialized empty:
/// let mut properties = Properties::new();
/// 
/// // ... Or they can take a pre-created map:
/// let other_properties = Properties::with_map(HashMap::new());
///
/// // Both result in an the same initial map:
/// assert_eq!(properties, other_properties);
///
/// // Properties can be set using most primitive types as well as strings:
/// properties.set("foo", 2.6f64);
/// properties.set("bar", "baz");
/// properties.set("spam", true);
///
/// assert_eq!(properties.get("bar"), Some("baz"));
/// assert_eq!(properties.get::<i64>("bar"), None);
///
/// // Properties may be deleted, and the entire map may also be cleared:
/// properties.delete("bar");
/// assert_eq!(properties.get::<&str>("bar"), None);
///
/// properties.clear();
/// assert_eq!(properties.get::<f64>("foo"), None);
/// assert_eq!(properties.get::<bool>("spam"), None);
/// ```
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Properties {
    map: HashMap<String, Property>,
}

impl Property {

    /// Attempts to convert this `Property` into a value of the given type.
    pub fn parse<'a, P>(&'a self) -> Option<P>
    where
        P: FromProperty<'a>,
    {
        P::from_property(self)
    }
}

impl Properties {
    /// Creates an empty `Properties`.
    pub fn new() -> Properties {
        Properties {
            map: HashMap::new(),
        }
    }

    /// Initializes a new `Properties` with the given mapping.
    pub fn with_map(map: HashMap<String, Property>) -> Properties {
        Properties {
            map,
        }
    }

    /// Gets a property by its name, converting it to the given type `T`.
    ///
    /// `T` may also be `&Property`, in which case the reference to the
    /// property itself will be returned directly.
    pub fn get<'a, T>(&'a self, name: &str) -> Option<T>
    where
        T: FromProperty<'a>,
    {
        self.map.get(name)
            .and_then(T::from_property)
    }

    /// Sets or replaces a property by its name, creating it from the given
    /// type `T`.
    ///
    /// `T` may also be `Property` , in which case the property itself will
    /// be directly inserted.
    pub fn set<T>(&mut self, name: &str, value: T)
    where
        Property: From<T>
    {
        self.map.insert(name.to_string(), Property::from(value));
    }

    /// Selects a property by name and removes it from the set.
    ///
    /// Returns `true` if and only if a property with the given name existed
    /// before removal.
    pub fn delete(&mut self, name: &str) -> bool {
        self.map.remove(name)
            .is_some()
    }

    /// Removes all properties from the set, resetting it to its state as if
    /// it had just been created with `Properties::new()`.
    pub fn clear(&mut self) {
        self.map.clear()
    }
}

impl Serialize for Properties {
    fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.map.serialize(s)
    }
}

impl<'de> Deserialize<'de> for Properties {
    fn deserialize<D>(d: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Ok(Properties {
            map: HashMap::deserialize(d)?,
        })
    }
}

impl<'a> FromProperty<'a> for &'a Property {
    fn from_property(property: &'a Property) -> Option<&'a Property> {
        Some(property)
    }
}

impl<'a> FromProperty<'a> for bool {
    fn from_property(property: &'a Property) -> Option<bool> {
        if let &Property::Boolean(x) = property {
            Some(x)
        } else {
            None
        }
    }
}

impl From<bool> for Property {
    fn from(x: bool) -> Property {
        Property::Boolean(x)
    }
}

impl<'a> FromProperty<'a> for i64 {
    fn from_property(property: &'a Property) -> Option<i64> {
        if let &Property::Integer(x) = property {
            Some(x)
        } else {
            None
        }
    }
}

impl From<i64> for Property {
    fn from(x: i64) -> Property {
        Property::Integer(x)
    }
}

impl<'a> FromProperty<'a> for f64 {
    fn from_property(property: &'a Property) -> Option<f64> {
        if let &Property::Number(x) = property {
            Some(x)
        } else {
            None
        }
    }
}

impl From<f64> for Property {
    fn from(x: f64) -> Property {
        Property::Number(x)
    }
}

impl<'a> FromProperty<'a> for String {
    fn from_property(property: &'a Property) -> Option<String> {
        if let &Property::Text(ref x) = property {
            Some(x.clone())
        } else {
            None
        }
    }
}

impl From<String> for Property {
    fn from(x: String) -> Property {
        Property::Text(x)
    }
}

impl<'a> FromProperty<'a> for &'a str {
    fn from_property(property: &'a Property) -> Option<&'a str> {
        if let &Property::Text(ref x) = property {
            Some(x)
        } else {
            None
        }
    }
}

impl<'a> From<&'a str> for Property {
    fn from(x: &'a str) -> Property {
        Property::from(x.to_string())
    }
}

/// Implement `Property` conversions transitively for a new type that can be
/// converted to a type that already has `Property` conversions.
///
/// Assumes `$x` and `$y` are primitive types that can be converted to and from
/// each other with `x as y` or `y as x` for all types in `$y`.
/// This may be replaced with TryFrom once stabilized to prevent panics in debug
/// mode if integers can not be converted.
macro_rules! transitive_property {
    ($x:ty as $($y:ty),*) => {
        $(
            impl<'a> FromProperty<'a> for $y {
                fn from_property(property: &'a Property) -> Option<$y> {
                    <$x>::from_property(property)
                        .map(|x| x as $y)
                }
            }

            impl From<$y> for Property {
                fn from(y: $y) -> Property {
                    Property::from(y as $x)
                }
            }
        )*
    };
}

transitive_property!(i64 as u64, i32, u32, i16, u16, i8, u8, isize, usize);
transitive_property!(f64 as f32);