reproto_core/
rp_value.rs

1//! Value of models
2
3use errors::Result;
4use std::fmt;
5use {Loc, RpNumber};
6
7#[derive(Debug, Clone, Serialize)]
8#[serde(tag = "type", content = "value", rename_all = "snake_case")]
9pub enum RpValue {
10    String(String),
11    Number(RpNumber),
12    Identifier(String),
13    Array(Vec<Loc<RpValue>>),
14}
15
16impl RpValue {
17    /// Treat as a string.
18    pub fn as_str(&self) -> Result<&str> {
19        use self::RpValue::*;
20
21        match *self {
22            String(ref string) => Ok(string),
23            _ => Err("not a string".into()),
24        }
25    }
26
27    /// Treat as a string.
28    pub fn as_number(&self) -> Result<&RpNumber> {
29        use self::RpValue::*;
30
31        match *self {
32            Number(ref number) => Ok(number),
33            _ => Err("not a number".into()),
34        }
35    }
36
37    /// Treat as a string.
38    pub fn as_identifier(&self) -> Result<&str> {
39        use self::RpValue::*;
40
41        match *self {
42            Identifier(ref identifier) => Ok(identifier),
43            _ => Err("expected identifier".into()),
44        }
45    }
46
47    pub fn as_string(&self) -> Result<&str> {
48        use self::RpValue::*;
49
50        match *self {
51            String(ref string) => Ok(string),
52            _ => Err("expected string".into()),
53        }
54    }
55
56    /// Treat into a string.
57    pub fn into_number(self) -> Result<RpNumber> {
58        use self::RpValue::*;
59
60        match self {
61            Number(number) => Ok(number),
62            _ => Err("not a number".into()),
63        }
64    }
65
66    pub fn into_string(self) -> Result<String> {
67        use self::RpValue::*;
68
69        match self {
70            String(string) => Ok(string),
71            _ => Err("expected string".into()),
72        }
73    }
74
75    /// Is this value a string.
76    pub fn is_string(&self) -> bool {
77        use self::RpValue::*;
78
79        match *self {
80            String(_) => true,
81            _ => false,
82        }
83    }
84}
85
86impl fmt::Display for RpValue {
87    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
88        match *self {
89            RpValue::String(ref string) => write!(f, "\"{}\"", string),
90            RpValue::Number(ref number) => number.fmt(f),
91            RpValue::Identifier(ref identifier) => identifier.fmt(f),
92            RpValue::Array(ref values) => {
93                write!(f, "[")?;
94
95                let mut it = values.iter().peekable();
96
97                while let Some(v) = it.next() {
98                    v.fmt(f)?;
99
100                    if it.peek().is_some() {
101                        write!(f, ", ")?;
102                    }
103                }
104
105                write!(f, "]")?;
106                Ok(())
107            }
108        }
109    }
110}