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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
use std::cmp::Ordering;
use std::fmt;
use std::ops::{Deref, Drop};
use std::hash::{Hash, Hasher};
use std::str::FromStr;
use std::marker::PhantomData;
use std::borrow::Borrow;
use std::sync::{Arc, RwLock, Weak};
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};

use serde::ser::{Serialize, Serializer};
use serde::de::{self, Deserialize, Deserializer, Visitor};
use rustc_serialize::{Decoder, Decodable, Encoder, Encodable};
use {Validator};

lazy_static! {
    static ref ATOMS: RwLock<HashMap<Buf, Weak<Value>>> =
        RwLock::new(HashMap::new());
}

/// Base symbol type
///
/// To use this type you should define your own type of symbol:
///
/// ```ignore
/// type MySymbol = Symbol<MyValidator>;
/// ```
// TODO(tailhook) optimize Eq to compare pointers
pub struct Symbol<V: Validator + ?Sized>(Arc<Value>, PhantomData<V>);

#[derive(PartialEq, Eq, Hash)]
struct Buf(Arc<String>);

#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
struct Value(Arc<String>);

impl<V: Validator + ?Sized> Clone for Symbol<V> {
    fn clone(&self) -> Symbol<V> {
        Symbol(self.0.clone(), PhantomData)
    }
}

impl<V: Validator + ?Sized> PartialEq for Symbol<V> {
    fn eq(&self, other: &Symbol<V>) -> bool {
        self.0.eq(&other.0)
    }
}
impl<V: Validator + ?Sized> Eq for Symbol<V> {}

impl<V: Validator + ?Sized> Hash for Symbol<V> {
    fn hash<H: Hasher>(&self, hasher: &mut H) {
        self.0.hash(hasher)
    }
}

impl<V: Validator + ?Sized> PartialOrd for Symbol<V> {
    fn partial_cmp(&self, other: &Symbol<V>) -> Option<Ordering> {
        self.0.partial_cmp(&other.0)
    }
}

impl<V: Validator + ?Sized> Ord for Symbol<V> {
    fn cmp(&self, other: &Symbol<V>) -> Ordering {
        self.0.cmp(&other.0)
    }
}


impl<V: Validator + ?Sized> FromStr for Symbol<V> {
    type Err = V::Err;
    fn from_str(s: &str) -> Result<Symbol<V>, Self::Err> {
        V::validate_symbol(s)?;
        if let Some(a) = ATOMS.read().expect("atoms locked").get(s) {
            if let Some(a) = a.upgrade() {
                return Ok(Symbol(a.clone(), PhantomData));
            }
            // We may get a race condition where atom has no strong references
            // any more, but weak reference is still no removed because
            // destructor is waiting for a lock in another thread.
            //
            // That's fine we'll get a write lock and recheck it later.
        }
        let buf = Arc::new(String::from(s));
        let mut atoms = ATOMS.write().expect("atoms locked");
        let val = match atoms.entry(Buf(buf.clone())) {
            Occupied(mut e) => match e.get().upgrade() {
                Some(a) => a,
                None => {
                    let result = Arc::new(Value(buf));
                    e.insert(Arc::downgrade(&result));
                    result
                }
            },
            Vacant(e) => {
                let result = Arc::new(Value(buf));
                e.insert(Arc::downgrade(&result));
                result
            }
        };
        Ok(Symbol(val, PhantomData))
    }
}

impl Drop for Value {
    fn drop(&mut self) {
        let mut atoms = ATOMS.write().expect("atoms locked");
        atoms.remove(&self.0[..]);
    }
}

impl<V: Validator + ?Sized> AsRef<str> for Symbol<V> {
    fn as_ref(&self) -> &str {
        &(self.0).0[..]
    }
}

impl<V: Validator + ?Sized> Borrow<str> for Symbol<V> {
    fn borrow(&self) -> &str {
        &(self.0).0[..]
    }
}

impl<V: Validator + ?Sized> Borrow<String> for Symbol<V> {
    fn borrow(&self) -> &String {
        &(self.0).0
    }
}

impl Borrow<str> for Buf {
    fn borrow(&self) -> &str {
        &self.0
    }
}

impl Borrow<String> for Buf {
    fn borrow(&self) -> &String {
        &self.0
    }
}


impl<V: Validator + ?Sized> fmt::Debug for Symbol<V> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        V::display(self, fmt)
    }
}

impl<V: Validator + ?Sized> fmt::Display for Symbol<V> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        (self.0).0.fmt(fmt)
    }
}

impl<V: Validator> Decodable for Symbol<V> {
    fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
        use std::error::Error;
        d.read_str()?
        .parse::<Symbol<V>>()
        .map_err(|e| d.error(e.description()))
    }
}

impl<V: Validator> Encodable for Symbol<V> {
    fn encode<E: Encoder>(&self, d: &mut E) -> Result<(), E::Error> {
        d.emit_str(&(self.0).0)
    }
}

struct SymbolVisitor<V: Validator>(PhantomData<V>);

impl<'de, V: Validator> Visitor<'de> for SymbolVisitor<V> {
    type Value = Symbol<V>;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("a valid symbol")
    }

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
        where E: de::Error
    {
        v.parse().map_err(de::Error::custom)
    }
}
impl<'de, V: Validator> Deserialize<'de> for Symbol<V> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where D: Deserializer<'de>
    {
        deserializer.deserialize_str(SymbolVisitor(PhantomData))
    }
}

impl<V: Validator> Serialize for Symbol<V> {
    fn serialize<S: Serializer>(&self, serializer: S)
        -> Result<S::Ok, S::Error>
    {
        serializer.serialize_str(&(self.0).0)
    }
}

impl<V: Validator + ?Sized> Deref for Symbol<V> {
    type Target = str;
    fn deref(&self) -> &str {
        &(self.0).0
    }
}

impl<V: Validator + ?Sized> Symbol<V> {
    /// Create a symbol from a static string
    ///
    /// # Panics
    ///
    /// When symbol is of invalid format. We assume that this is used for
    /// constant strings in source code, so we assert that they are valid.
    ///
    /// Use `FromStr::from_str(x)` or `x.parse()` to parse user input
    pub fn from(s: &'static str) -> Symbol<V> {
        FromStr::from_str(s)
        .expect("static string used as atom is invalid")
    }
}

#[cfg(test)]
mod test {
    use std::io;
    use rustc_serialize::json;
    use {Validator, Symbol};
    use serde_json;

    #[allow(dead_code)]
    struct AnyString;
    #[allow(dead_code)]
    struct AlphaNumString;
    type Atom = Symbol<AnyString>;
    type AlphaNum = Symbol<AlphaNumString>;

    impl Validator for AnyString {
        // Use an error from standard library to make example shorter
        type Err = ::std::string::ParseError;
        fn validate_symbol(_: &str) -> Result<(), Self::Err> {
            Ok(())
        }
    }

    impl Validator for AlphaNumString {
        // Use an error from standard library to make example shorter
        type Err = io::Error;
        fn validate_symbol(s: &str) -> Result<(), Self::Err> {
            if s.chars().any(|c| !c.is_alphanumeric()) {
                return Err(io::Error::new(io::ErrorKind::InvalidData,
                    "Character is not alphanumeric"));
            }
            Ok(())
        }
    }

    #[test]
    fn eq() {
        assert_eq!(Atom::from("x"), Atom::from("x"));
    }

    #[test]
    fn ord() {
        assert!(Atom::from("a") < Atom::from("b"));
    }

    #[test]
    fn clone() {
        assert_eq!(Atom::from("x").clone(), Atom::from("x"));
    }

    #[test]
    fn hash() {
        use std::collections::HashMap;
        let mut h = HashMap::new();
        h.insert(Atom::from("x"), 123);
        assert_eq!(h.get("x"), Some(&123));
        assert_eq!(h.get(&Atom::from("x")), Some(&123));
        assert_eq!(h.get("y"), None);
        assert_eq!(h.get(&Atom::from("y")), None);
    }

    #[test]
    fn encode() {
        assert_eq!(json::encode(&Atom::from("xyz")).unwrap(),
                   r#""xyz""#);
    }
    #[test]
    fn decode() {
        assert_eq!(json::decode::<Atom>(r#""xyz""#).unwrap(),
                   Atom::from("xyz"));
    }

    #[test]
    fn encode_serde() {
        assert_eq!(serde_json::to_string(&Atom::from("xyz")).unwrap(),
                   r#""xyz""#);
    }

    #[test]
    fn decode_serde() {
        assert_eq!(serde_json::from_str::<Atom>(r#""xyz""#).unwrap(),
                   Atom::from("xyz"));
    }

    #[test]
    #[should_panic(message="static strings used as atom is invalid")]
    fn distinct_validators() {
        let _xa = Atom::from("x");
        let _xn = AlphaNum::from("x");
        let _ya = Atom::from("a-b");
        // This should fail on invalid value, but didn't fail in <= v0.1.2
        let _yn = AlphaNum::from("a-b");
    }
}