gitql_core/values/
float.rs

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
use std::any::Any;
use std::cmp::Ordering;

use gitql_ast::types::base::DataType;
use gitql_ast::types::float::FloatType;

use super::base::Value;

#[derive(Clone)]
pub struct FloatValue {
    pub value: f64,
}

impl Value for FloatValue {
    fn literal(&self) -> String {
        self.value.to_string()
    }

    fn equals(&self, other: &Box<dyn Value>) -> bool {
        if let Some(other_float) = other.as_any().downcast_ref::<FloatValue>() {
            return self.value == other_float.value;
        }
        false
    }

    fn compare(&self, other: &Box<dyn Value>) -> Option<Ordering> {
        if let Some(other_float) = other.as_any().downcast_ref::<FloatValue>() {
            return self.value.partial_cmp(&other_float.value);
        }
        None
    }

    fn data_type(&self) -> Box<dyn DataType> {
        Box::new(FloatType)
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn add_op(&self, other: &Box<dyn Value>) -> Result<Box<dyn Value>, String> {
        if let Some(other_int) = other.as_any().downcast_ref::<FloatValue>() {
            let value = self.value + other_int.value;
            return Ok(Box::new(FloatValue { value }));
        }
        Err("Unexpected value to perform `+` with".to_string())
    }

    fn sub_op(&self, other: &Box<dyn Value>) -> Result<Box<dyn Value>, String> {
        if let Some(other_int) = other.as_any().downcast_ref::<FloatValue>() {
            let value = self.value - other_int.value;
            return Ok(Box::new(FloatValue { value }));
        }
        Err("Unexpected value to perform `-` with".to_string())
    }

    fn mul_op(&self, other: &Box<dyn Value>) -> Result<Box<dyn Value>, String> {
        if let Some(other_int) = other.as_any().downcast_ref::<FloatValue>() {
            let value = self.value * other_int.value;
            return Ok(Box::new(FloatValue { value }));
        }
        Err("Unexpected value to perform `*` with".to_string())
    }

    fn div_op(&self, other: &Box<dyn Value>) -> Result<Box<dyn Value>, String> {
        if let Some(other_int) = other.as_any().downcast_ref::<FloatValue>() {
            let value = self.value / other_int.value;
            return Ok(Box::new(FloatValue { value }));
        }
        Err("Unexpected value to perform `/` with".to_string())
    }

    fn neg_op(&self) -> Result<Box<dyn Value>, String> {
        Ok(Box::new(FloatValue { value: -self.value }))
    }
}