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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
use ordered_float::OrderedFloat;
use std::cmp::{Ord, PartialOrd};
use std::collections::{BTreeMap, BTreeSet};
use utils::index::Index;
#[doc(hidden)]
pub mod utils;

/// `EdnType` is an Enum with possible values for an EDN type
/// Symbol and Char are not yet implemented
/// String implementation of Edn can be obtained with `.to_string()`
#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub enum Edn {
    Vector(Vector),
    Set(Set),
    Map(Map),
    List(List),
    Key(String),
    Symbol(String),
    Str(String),
    Int(isize),
    UInt(usize),
    Double(Double),
    Rational(String),
    Char(char),
    Bool(bool),
    Nil,
    Empty,
}

#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Vector(Vec<Edn>);
impl Vector {
    pub fn new(v: Vec<Edn>) -> Vector {
        Vector(v)
    }

    pub fn empty() -> Vector {
        Vector(Vec::new())
    }
}

#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct List(Vec<Edn>);
impl List {
    pub fn new(v: Vec<Edn>) -> List {
        List(v)
    }

    pub fn empty() -> List {
        List(Vec::new())
    }
}

#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Set(BTreeSet<Edn>);
impl Set {
    pub fn new(v: BTreeSet<Edn>) -> Set {
        Set(v)
    }

    pub fn empty() -> Set {
        Set(BTreeSet::new())
    }
}

#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Map(BTreeMap<String, Edn>);
impl Map {
    pub fn new(m: BTreeMap<String, Edn>) -> Map {
        Map(m)
    }

    pub fn empty() -> Map {
        Map(BTreeMap::new())
    }
}

pub type Double = OrderedFloat<f64>;

impl core::fmt::Display for Vector {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "[{}]",
            self.0
                .iter()
                .map(|i| format!("{:?}, ", i))
                .fold(String::new(), |mut acc, i| {
                    acc.push_str(&i);
                    acc
                })
        )
    }
}

impl core::fmt::Display for List {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "({})",
            self.0
                .iter()
                .map(|i| format!("{:?}, ", i))
                .fold(String::new(), |mut acc, i| {
                    acc.push_str(&i);
                    acc
                })
        )
    }
}

impl core::fmt::Display for Set {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "#{{{}}}",
            self.0
                .iter()
                .map(|i| format!("{:?}, ", i))
                .fold(String::new(), |mut acc, i| {
                    acc.push_str(&i);
                    acc
                })
        )
    }
}

impl core::fmt::Display for Map {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "{{{}}}",
            self.0
                .iter()
                .map(|(k, v)| format!("{}: {:?}, ", k, v))
                .fold(String::new(), |mut acc, i| {
                    acc.push_str(&i);
                    acc
                })
        )
    }
}

impl core::fmt::Display for Edn {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let text = match self {
            Edn::Vector(v) => format!("{}", v),
            Edn::Set(s) => format!("{}", s),
            Edn::Map(m) => format!("{}", m),
            Edn::List(l) => format!("{}", l),
            Edn::Symbol(sy) => sy.to_string(),
            Edn::Key(k) => k.to_string(),
            Edn::Str(s) => s.to_string(),
            Edn::Int(i) => format!("{}", i),
            Edn::UInt(u) => format!("{}", u),
            Edn::Double(d) => format!("{}", d),
            Edn::Rational(r) => r.to_string(),
            Edn::Bool(b) => format!("{}", b),
            Edn::Char(c) => format!("{}", c),
            Edn::Nil => String::from("nil"),
            Edn::Empty => String::from(""),
        };
        write!(f, "{}", text)
    }
}

impl Edn {
    /// `to_float` takes an `Edn` and returns an `Option<f64>` with its value. Most types return None
    /// ```rust
    /// use edn_rs::edn::{Edn, Vector};
    ///
    /// let key = Edn::Key(String::from("1234"));
    /// let q = Edn::Rational(String::from("3/4"));
    /// let i = Edn::Int(12isize);
    ///
    /// assert_eq!(Edn::Vector(Vector::empty()).to_float(), None);
    /// assert_eq!(key.to_float().unwrap(),1234f64);
    /// assert_eq!(q.to_float().unwrap(), 0.75f64);
    /// assert_eq!(i.to_float().unwrap(), 12f64);
    /// ```
    pub fn to_float(&self) -> Option<f64> {
        match self {
            Edn::Key(k) => k.parse::<f64>().ok(),
            Edn::Str(s) => s.parse::<f64>().ok(),
            Edn::Int(i) => to_double(i).ok(),
            Edn::UInt(u) => to_double(u).ok(),
            Edn::Double(d) => Some(d.into_inner()),
            Edn::Rational(r) => rational_to_double(&r),
            _ => None,
        }
    }

    /// `to_int` takes an `Edn` and returns an `Option<isize>` with its value. Most types return None
    /// ```rust
    /// use edn_rs::edn::{Edn, Vector};
    ///
    /// let key = Edn::Key(String::from("1234"));
    /// let q = Edn::Rational(String::from("3/4"));
    /// let f = Edn::Double(12.3f64.into());
    ///
    /// assert_eq!(Edn::Vector(Vector::empty()).to_float(), None);
    /// assert_eq!(key.to_int().unwrap(),1234isize);
    /// assert_eq!(q.to_int().unwrap(), 1isize);
    /// assert_eq!(f.to_int().unwrap(), 12isize);
    /// ```
    pub fn to_int(&self) -> Option<isize> {
        match self {
            Edn::Key(k) => k.parse::<isize>().ok(),
            Edn::Str(s) => s.parse::<isize>().ok(),
            Edn::Int(i) => Some(i.to_owned()),
            Edn::Double(d) => Some(d.to_owned().round() as isize),
            Edn::Rational(r) => Some(rational_to_double(&r).unwrap_or(0f64).round() as isize),
            _ => None,
        }
    }

    /// `to_bool` takes an `Edn` and returns an `Option<bool>` with its value. Most types return None
    /// ```rust
    /// use edn_rs::edn::{Edn};
    ///
    /// let b = Edn::Bool(true);
    /// let s = Edn::Str("true".to_string());
    /// let symbol = Edn::Symbol("false".to_string());
    ///
    /// assert_eq!(b.to_bool().unwrap(),true);
    /// assert_eq!(s.to_bool().unwrap(),true);
    /// assert_eq!(symbol.to_bool().unwrap(),false);
    /// ```
    pub fn to_bool(&self) -> Option<bool> {
        match self {
            Edn::Bool(b) => Some(*b),
            Edn::Str(s) => s.parse::<bool>().ok(),
            Edn::Symbol(s) => s.parse::<bool>().ok(),
            _ => None,
        }
    }

    /// Index into a EDN vector, list, set or map. A string index can be used to access a
    /// value in a map, and a usize index can be used to access an element of a
    /// seqs.
    ///
    /// Returns `None` if the type of `self` does not match the type of the
    /// index, for example if the index is a string and `self` is a seq or a
    /// number. Also returns `None` if the given key does not exist in the map
    /// or the given index is not within the bounds of the seq.
    ///
    /// ```rust
    /// #[macro_use]
    /// extern crate edn_rs;
    /// use edn_rs::edn::{Edn, Map, Vector};
    ///
    /// fn main() {
    ///     let edn = edn!([ 1 1.2 3 {false :f nil 3/4}]);
    ///
    ///     assert_eq!(edn[1], edn!(1.2));
    ///     assert_eq!(edn.get(1).unwrap(), &edn!(1.2));
    ///     assert_eq!(edn[3]["false"], edn!(:f));
    ///     assert_eq!(edn[3].get("false").unwrap(), &Edn::Key("f".to_string()));
    /// }
    /// ```
    pub fn get<I: Index>(&self, index: I) -> Option<&Edn> {
        index.index_into(self)
    }

    /// Mutably index into a EDN vector, set, list or map. A string index can be used to
    /// access a value in a map, and a usize index can be used to access an
    /// element of a seq.
    ///
    /// Returns `None` if the type of `self` does not match the type of the
    /// index, for example if the index is a string and `self` is a seq or a
    /// number. Also returns `None` if the given key does not exist in the map
    /// or the given index is not within the bounds of the seq.
    ///
    /// ```rust
    /// #[macro_use]
    /// extern crate edn_rs;
    /// use edn_rs::edn::{Edn, Map, Vector};
    ///
    /// fn main() {
    ///     let mut edn = edn!([ 1 1.2 3 {false :f nil 3/4}]);
    ///
    ///     assert_eq!(edn[1], edn!(1.2));
    ///     assert_eq!(edn.get_mut(1).unwrap(), &edn!(1.2));
    ///     assert_eq!(edn[3]["false"], edn!(:f));
    ///     assert_eq!(edn[3].get_mut("false").unwrap(), &Edn::Key("f".to_string()));
    /// }
    /// ```
    pub fn get_mut<I: Index>(&mut self, index: I) -> Option<&mut Edn> {
        index.index_into_mut(self)
    }

    pub(crate) fn parse_word(word: String) -> Edn {
        match word {
            w if w.starts_with(":") => Edn::Key(w),
            w if w.starts_with("\\") && w.len() == 2 => Edn::Char(w.chars().last().unwrap()),
            w if w.starts_with("\"") && w.ends_with("\"") => Edn::Str(w.replace("\"", "")),
            w if w.parse::<bool>().is_ok() => Edn::Bool(w.parse::<bool>().unwrap()),
            w if w == "nil" || w == "Nil" => Edn::Nil,
            w if w.contains("/") && w.split("/").all(|d| d.parse::<f64>().is_ok()) => {
                Edn::Rational(w)
            }
            w if w.parse::<isize>().is_ok() => Edn::Int(w.parse::<isize>().unwrap()),
            w if w.parse::<usize>().is_ok() => Edn::UInt(w.parse::<usize>().unwrap()),
            w if w.parse::<f64>().is_ok() => Edn::Double(OrderedFloat(w.parse::<f64>().unwrap())),
            w => Edn::Symbol(w),
        }
    }
}

impl std::str::FromStr for Edn {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        crate::deserialize::parse_edn(s)
    }
}

fn to_double<T>(i: T) -> Result<f64, std::num::ParseFloatError>
where
    T: std::fmt::Debug,
{
    format!("{:?}", i).parse::<f64>()
}

fn rational_to_double(r: &str) -> Option<f64> {
    if r.split('/').count() == 2 {
        let vals = r
            .split('/')
            .map(ToString::to_string)
            .map(|v| v.parse::<f64>())
            .map(Result::ok)
            .collect::<Option<Vec<f64>>>()?;
        return Some(vals[0] / vals[1]);
    }
    None
}

#[test]
fn parses_rationals() {
    assert_eq!(rational_to_double("3/4").unwrap(), 0.75f64);
    assert_eq!(rational_to_double("25/5").unwrap(), 5f64);
    assert_eq!(rational_to_double("15/4").unwrap(), 3.75f64);
    assert_eq!(rational_to_double("3 4"), None);
    assert_eq!(rational_to_double("3/4/5"), None);
    assert_eq!(rational_to_double("text/moretext"), None);
}