Skip to main content

aorist_extendr_api/
logical.rs

1/// Bool is a wrapper for i32 in the context of an R's tristate boolean.
2/// It can be TRUE, FALSE or NA_LOGICAL.
3#[derive(PartialEq, Eq)]
4pub struct Bool(pub i32);
5
6impl Bool {
7    /// Convert this Bool to a bool. Note NA will be true.
8    pub fn to_bool(&self) -> bool {
9        self.0 != 0
10    }
11
12    /// Convert this construct a Bool from a rust boolean.
13    pub fn from_bool(val: bool) -> Self {
14        Bool(val as i32)
15    }
16
17    /// Test if TRUE
18    pub fn is_true(&self) -> bool {
19        self.0 == 1
20    }
21
22    /// Test if FALSE
23    pub fn is_false(&self) -> bool {
24        self.0 == 0
25    }
26}
27
28impl Clone for Bool {
29    fn clone(&self) -> Self {
30        Self(self.0)
31    }
32}
33
34impl Copy for Bool {}
35
36impl From<i32> for Bool {
37    fn from(v: i32) -> Self {
38        Self(v)
39    }
40}
41
42impl From<bool> for Bool {
43    fn from(v: bool) -> Self {
44        Self(v as i32)
45    }
46}
47
48impl From<Bool> for bool {
49    fn from(v: Bool) -> Self {
50        v.0 != 0
51    }
52}
53
54impl From<&Bool> for bool {
55    fn from(v: &Bool) -> Self {
56        v.0 != 0
57    }
58}
59
60impl std::fmt::Debug for Bool {
61    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62        match self {
63            Bool(0) => write!(f, "FALSE"),
64            Bool(1) => write!(f, "TRUE"),
65            Bool(std::i32::MIN) => write!(f, "NA_LOGICAL"),
66            _ => write!(f, "Bool({})", self.0),
67        }
68    }
69}