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
// Copyright (c) Cole Frederick. All rights reserved.
// The use and distribution terms for this software are covered by the
// Eclipse Public License 1.0 (https://opensource.org/licenses/eclipse-1.0.php)
// which can be found in the file epl-v10.html at the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the terms of this license.
// You must not remove this notice, or any other, from this software.

use super::*;
use std::str::FromStr;
use edn::reader::{EdnReader, ReadResult};
use edn;
use character;
use integral;
use float_point;
use string;

impl From<bool> for Value {
    fn from(x: bool) -> Value { if x { Handle::tru().value() } else { Handle::fals().value() } }
}
impl Into<bool> for Value { fn into(self) -> bool { (&self).into() } }
impl Into<bool> for &Value { fn into(self) -> bool { self.handle().is_so() } }
impl From<char> for Value { fn from(x: char) -> Self { character::new(x).value() } }
impl Into<char> for Value {
    fn into(self) -> char {
        let h = self._consume();
        if let Some(prism) = character::find_prism(h) {
            let c = character::as_char(prism);
            h.retire();
            c
        } else {
            unimplemented!("Converting {} into a char.", h);
        }
    }
}
impl From<i64> for Value { fn from(x: i64) -> Self { integral::new_value(x) } }
impl From<i32> for Value { fn from(x: i32) -> Self { Value::from(x as i64) } }
impl From<i16> for Value { fn from(x: i16) -> Self { Value::from(x as i64) } }
impl From<i8> for Value { fn from(x: i8) -> Self { Value::from(x as i64) } }
impl From<isize> for Value { fn from(x: isize) -> Self { Value::from(x as i64) } }
impl From<u64> for Value { fn from(x: u64) -> Self { Value::from(x as i64) } }
impl From<u32> for Value { fn from(x: u32) -> Self { Value::from(x as i64) } }
impl From<u16> for Value { fn from(x: u16) -> Self { Value::from(x as i64) } }
impl From<u8> for Value { fn from(x: u8) -> Self { Value::from(x as i64) } }
impl From<usize> for Value { fn from(x: usize) -> Self { Value::from(x as i64) } }
impl From<f64> for Value { fn from(x: f64) -> Self { float_point::new(x).handle().value() } }
impl From<f32> for Value { fn from(x: f32) -> Self { Value::from(x as f64) } }
impl From<&str> for Value { fn from(s: &str) -> Self { string::new_value_from_str(s) } }
/// Parse a value from a string of edn data.
///
/// # Examples
///
/// ```
/// # use fress::*;
/// let x: Value = "[1 2 3 4]".parse().unwrap();
/// assert_eq!(x.count(), 4);
/// ```
impl FromStr for Value {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        //group!("Read edn from {:?}", s);
        let b = s.as_bytes();
        let mut reader = EdnReader::new();
        let ret = match edn::read(&mut reader, b) {
            ReadResult::Ok { value, .. } => {
                Ok(value.handle().value())
            },
            ReadResult::NeedMore { bytes_not_used } => {
                let trailing_space = {
                    let mut v = Vec::new();
                    let i = b.len() - bytes_not_used as usize;
                    v.extend_from_slice(&b[i..]);
                    v.push(0x20u8);
                    v
                };
                match edn::read(&mut reader, &trailing_space[..]) {
                    ReadResult::Ok { value, .. } => {
                        Ok(value.handle().value())
                    },
                    ReadResult::NeedMore { .. } => {
                        Err(format!("Incomplete edn element: {:?}", s))
                    },
                    ReadResult::Error { location, message } => {
                        Err(format!("{:?} {}", location, message))
                    },
                }
            },
            ReadResult::Error { location, message } => {
                Err(format!("{:?} {}", location, message))
            },
        };
        //group_end!();
        ret
    }
}

impl<T: Into<Value>> From<Option<T>> for Value {
    fn from(option: Option<T>) -> Value {
        match option {
            Some(t) => t.into(),
            None    => Handle::nil().value(),
        }
    }
}

// vector, array, slice
impl<T: Into<Value>> From<Vec<T>> for Value {
    fn from(val: Vec<T>) -> Value {
        use vector;
        let mut v = vector::new_value();
        for x in val.into_iter() {
            v = v.conj(x.into());
        }
        v
    }
}

// tuples
/*
impl<A, B> From<(A, B)> for Value {
    fn from(x: (A, B)) -> Self {
        unimplemented!()
    }
}
*/

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn bool_roundtrip() {
        let x = true;
        assert_eq!(x, Value::from(x).into());
        let x = false;
        assert_eq!(x, Value::from(x).into());
    }
    #[test]
    fn char_roundtrip() {
        let x = 'λ';
        assert_eq!(x, Value::from(x).into());
    }
    #[test]
    fn option_roundtrip() {
        let x: Option<char> = None;
        assert!(Value::from(x).is_nil());
        let x = Some('λ');
        assert_eq!('λ', Value::from(x).into());
    }
}