stainless_script/stdlib/
bool_type.rs

1use crate::{
2    class::Class,
3    node::Node,
4    object::{Object, ObjectEq, ObjectFromStr, ObjectOrd, ObjectPartialEq, ObjectPartialOrd},
5    socket::{InputSocket, OutputSocket},
6    ExecutionContext,
7};
8
9use super::any_class;
10use std::{borrow::Cow, rc::Rc};
11
12pub fn bool_class() -> Class {
13    Class {
14        name: "bool".into(),
15        nodes: vec![Rc::new(BoolNode) as Rc<dyn Node>],
16        obj_from_str: Some(<bool as ObjectFromStr>::from_str),
17    }
18}
19
20#[derive(Debug, Clone)]
21pub struct BoolNode;
22
23impl Object for bool {
24    fn class(&self) -> Class {
25        bool_class()
26    }
27
28    fn as_number(&self) -> f64 {
29        if *self {
30            1.0
31        } else {
32            0.0
33        }
34    }
35
36    fn as_bool(&self) -> bool {
37        *self
38    }
39}
40
41impl ObjectPartialEq for bool {
42    fn eq(&self, other: Rc<dyn Object>) -> bool {
43        other.class() == self.class() && *self == other.as_bool()
44    }
45}
46
47impl ObjectPartialOrd for bool {
48    fn partial_cmp(&self, other: Rc<dyn Object>) -> Option<std::cmp::Ordering> {
49        if other.class() == self.class() {
50            PartialOrd::partial_cmp(self, &other.as_bool())
51        } else {
52            None
53        }
54    }
55}
56
57impl ObjectEq for bool {}
58
59impl ObjectOrd for bool {
60    fn cmp(&self, other: Rc<dyn Object>) -> std::cmp::Ordering {
61        ObjectPartialOrd::partial_cmp(self, other).unwrap()
62    }
63}
64
65impl Node for BoolNode {
66    fn execute(&self, context: &mut ExecutionContext) -> usize {
67        let cond = context.get_inputs()[0].as_bool();
68        context.set_outputs(vec![Rc::new(cond) as Rc<dyn Object>]);
69        0
70    }
71
72    fn class(&self) -> Class {
73        bool_class()
74    }
75
76    fn variants(&self) -> Vec<Cow<'_, str>> {
77        vec!["from-object".into()]
78    }
79
80    fn current_variant(&self) -> Cow<'_, str> {
81        "from-object".into()
82    }
83
84    fn set_variant(&mut self, _variant: &str) {}
85
86    fn inputs(&self) -> Vec<InputSocket> {
87        vec![InputSocket { class: any_class() }]
88    }
89
90    fn outputs(&self) -> Vec<OutputSocket> {
91        vec![OutputSocket {
92            class: bool_class(),
93        }]
94    }
95
96    fn clone_node(&self) -> Rc<dyn Node> {
97        Rc::new(self.clone()) as Rc<dyn Node>
98    }
99}