datex_core/values/core_values/
boolean.rs

1use std::{fmt::Display, ops::Not};
2
3use crate::values::{
4    traits::structural_eq::StructuralEq,
5    value_container::{ValueContainer, ValueError},
6};
7
8use super::super::core_value_trait::CoreValueTrait;
9
10#[derive(Debug, Clone, PartialEq, Eq, Hash)]
11pub struct Boolean(pub bool);
12
13impl Boolean {
14    pub fn as_bool(&self) -> bool {
15        self.0
16    }
17}
18impl Boolean {
19    pub fn toggle(&mut self) {
20        self.0 = !self.0;
21    }
22    pub fn is_true(&self) -> bool {
23        self.0
24    }
25    pub fn is_false(&self) -> bool {
26        !self.0
27    }
28    pub fn as_string(&self) -> String {
29        self.0.to_string()
30    }
31    pub fn as_str(&self) -> &str {
32        if self.0 {
33            "true"
34        } else {
35            "false"
36        }
37    }
38}
39
40impl Display for Boolean {
41    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
42        write!(f, "{}", self.0)
43    }
44}
45
46impl CoreValueTrait for Boolean {}
47
48impl StructuralEq for Boolean {
49    fn structural_eq(&self, other: &Self) -> bool {
50        self.0 == other.0
51    }
52}
53
54impl From<bool> for Boolean {
55    fn from(v: bool) -> Self {
56        Boolean(v)
57    }
58}
59
60impl Not for Boolean {
61    type Output = Boolean;
62
63    fn not(self) -> Self::Output {
64        Boolean(!self.0)
65    }
66}
67// new into
68impl<T: Into<ValueContainer>> TryFrom<Option<T>> for Boolean {
69    type Error = ValueError;
70    fn try_from(value: Option<T>) -> Result<Self, Self::Error> {
71        match value {
72            Some(v) => {
73                let boolean: ValueContainer = v.into();
74                boolean
75                    .to_value()
76                    .borrow()
77                    .cast_to_bool()
78                    .ok_or(ValueError::TypeConversionError)
79            }
80            None => Err(ValueError::IsVoid),
81        }
82    }
83}