datex_core/values/core_values/
boolean.rs

1use crate::stdlib::string::String;
2use crate::stdlib::string::ToString;
3use crate::traits::structural_eq::StructuralEq;
4use crate::values::value_container::{ValueContainer, ValueError};
5use core::prelude::rust_2024::*;
6use core::result::Result;
7use core::{fmt::Display, ops::Not};
8use serde::{Deserialize, Serialize};
9
10#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
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 { "true" } else { "false" }
33    }
34}
35
36impl Display for Boolean {
37    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
38        core::write!(f, "{}", self.0)
39    }
40}
41
42impl StructuralEq for Boolean {
43    fn structural_eq(&self, other: &Self) -> bool {
44        self.0 == other.0
45    }
46}
47
48impl From<bool> for Boolean {
49    fn from(v: bool) -> Self {
50        Boolean(v)
51    }
52}
53
54impl Not for Boolean {
55    type Output = Boolean;
56
57    fn not(self) -> Self::Output {
58        Boolean(!self.0)
59    }
60}
61// new into
62impl<T: Into<ValueContainer>> TryFrom<Option<T>> for Boolean {
63    type Error = ValueError;
64    fn try_from(value: Option<T>) -> Result<Self, Self::Error> {
65        match value {
66            Some(v) => {
67                let boolean: ValueContainer = v.into();
68                boolean
69                    .to_value()
70                    .borrow()
71                    .cast_to_bool()
72                    .ok_or(ValueError::TypeConversionError)
73            }
74            None => Err(ValueError::IsVoid),
75        }
76    }
77}