Skip to main content

mirascript_vm/value/types/
boolean.rs

1use crate::{MiraError, Result, value::arena::MiraManageable};
2
3use super::MiraValue;
4
5impl MiraValue {
6    /// Create a `MiraValue` representing a boolean value.
7    #[inline]
8    pub const fn boolean(value: bool) -> Self {
9        Self::Boolean(value)
10    }
11
12    /// Check whether this value is a boolean value.
13    #[inline]
14    pub const fn is_boolean(self) -> bool {
15        matches!(self, Self::Boolean(_))
16    }
17
18    /// Return the inline boolean payload, or `None` for another value type.
19    #[inline]
20    pub fn as_boolean(&self) -> Option<bool> {
21        match self {
22            Self::Boolean(value) => Some(*value),
23            _ => None,
24        }
25    }
26}
27
28impl From<bool> for MiraValue {
29    #[inline]
30    fn from(value: bool) -> Self {
31        Self::Boolean(value)
32    }
33}
34
35impl From<bool> for MiraManageable {
36    #[inline]
37    fn from(value: bool) -> Self {
38        std::convert::Into::<MiraValue>::into(value).into()
39    }
40}
41
42impl TryFrom<MiraValue> for bool {
43    type Error = Box<MiraError>;
44
45    #[inline]
46    fn try_from(value: MiraValue) -> Result<Self> {
47        value
48            .as_boolean()
49            .ok_or_else(|| MiraError::conversion_type("bool", value.value_type()))
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56
57    #[test]
58    fn test_boolean() {
59        let value = MiraValue::boolean(true);
60        assert!(value.is_boolean());
61        assert_eq!(value.as_boolean(), Some(true));
62
63        let value = MiraValue::boolean(false);
64        assert!(value.is_boolean());
65        assert_eq!(value.as_boolean(), Some(false));
66
67        let value = MiraValue::Nil;
68        assert!(!value.is_boolean());
69        assert_eq!(value.as_boolean(), None);
70    }
71
72    #[test]
73    fn test_try_from() {
74        let value = MiraValue::boolean(true);
75        let boolean: bool = value.try_into().unwrap();
76        assert!(boolean);
77
78        let value = MiraValue::Nil;
79        assert!(bool::try_from(value).is_err());
80    }
81}