Skip to main content

simple_expressions/types/
primitive.rs

1use crate::types::error::{Error, Result};
2
3#[derive(Debug, Clone, PartialEq)]
4pub enum Primitive {
5    Int(i64),
6    Float(f64),
7    Str(String),
8    Bool(bool),
9}
10
11impl Primitive {
12    /// Rendering for humans. This is formatting, not coercion: it never fails,
13    /// and it is deliberately not something a [`Coercions`](crate::types::coerce::Coercions)
14    /// policy can influence.
15    pub fn as_str_lossy(&self) -> String {
16        match self {
17            Primitive::Str(s) => s.clone(),
18            Primitive::Int(i) => i.to_string(),
19            Primitive::Float(f) => f.to_string(),
20            Primitive::Bool(b) => b.to_string(),
21        }
22    }
23}
24
25impl From<i64> for Primitive {
26    fn from(v: i64) -> Self {
27        Primitive::Int(v)
28    }
29}
30impl From<f64> for Primitive {
31    fn from(v: f64) -> Self {
32        Primitive::Float(v)
33    }
34}
35impl From<bool> for Primitive {
36    fn from(v: bool) -> Self {
37        Primitive::Bool(v)
38    }
39}
40impl From<String> for Primitive {
41    fn from(v: String) -> Self {
42        Primitive::Str(v)
43    }
44}
45impl From<&str> for Primitive {
46    fn from(v: &str) -> Self {
47        Primitive::Str(v.to_string())
48    }
49}
50
51impl TryFrom<Primitive> for i64 {
52    type Error = Error;
53    fn try_from(p: Primitive) -> Result<Self> {
54        if let Primitive::Int(i) = p { Ok(i) } else { Err(Error::TypeMismatch("expected int".into())) }
55    }
56}
57impl TryFrom<Primitive> for f64 {
58    type Error = Error;
59    fn try_from(p: Primitive) -> Result<Self> {
60        if let Primitive::Float(f) = p { Ok(f) } else { Err(Error::TypeMismatch("expected float".into())) }
61    }
62}
63impl TryFrom<Primitive> for bool {
64    type Error = Error;
65    fn try_from(p: Primitive) -> Result<Self> {
66        if let Primitive::Bool(b) = p { Ok(b) } else { Err(Error::TypeMismatch("expected bool".into())) }
67    }
68}
69impl TryFrom<Primitive> for String {
70    type Error = Error;
71    fn try_from(p: Primitive) -> Result<Self> {
72        if let Primitive::Str(s) = p { Ok(s) } else { Err(Error::TypeMismatch("expected string".into())) }
73    }
74}