logic_mesh/base/input/
base.rs

1// Copyright (c) 2022-2023, Radu Racariu.
2
3//!
4//! Defines the base input type
5//!
6
7use libhaystack::val::{kind::HaystackKind, Value};
8use uuid::Uuid;
9
10use crate::base::link::{BaseLink, Link};
11
12use super::{props::InputDefault, InputProps};
13
14/// The base input type
15#[derive(Debug, Default)]
16pub struct BaseInput<Reader, Writer> {
17    /// The block unique input's name
18    pub name: String,
19    /// The kind of data this input can receive
20    pub kind: HaystackKind,
21    /// The block id of the block this input belongs to
22    pub block_id: Uuid,
23    /// The number of connections this input has
24    pub connection_count: usize,
25    /// The input reader
26    pub reader: Reader,
27    /// The input writer
28    pub writer: Writer,
29    /// The input value
30    pub val: Option<Value>,
31    /// The input default values
32    pub default: InputDefault,
33    /// The links to other inputs
34    pub links: Vec<BaseLink<Writer>>,
35}
36
37/// Implements the `InputProps` trait for `BaseInput`
38impl<Reader, Writer: Clone> InputProps for BaseInput<Reader, Writer> {
39    type Reader = Reader;
40    type Writer = Writer;
41
42    fn name(&self) -> &str {
43        &self.name
44    }
45
46    fn kind(&self) -> &HaystackKind {
47        &self.kind
48    }
49
50    fn block_id(&self) -> &Uuid {
51        &self.block_id
52    }
53
54    fn is_connected(&self) -> bool {
55        self.connection_count > 0
56    }
57
58    fn links(&self) -> Vec<&dyn Link> {
59        self.links.iter().map(|l| l as &dyn Link).collect()
60    }
61
62    fn add_link(&mut self, link: BaseLink<Self::Writer>) {
63        self.links.push(link)
64    }
65
66    fn remove_link_by_id(&mut self, link_id: &Uuid) {
67        self.links.retain(|l| l.id() != link_id)
68    }
69
70    fn remove_target_block_links(&mut self, block_id: &Uuid) {
71        self.links.retain(|l| l.target_block_id() != block_id)
72    }
73
74    fn remove_all_links(&mut self) {
75        self.links.clear()
76    }
77
78    fn default(&self) -> &InputDefault {
79        &self.default
80    }
81
82    fn reader(&mut self) -> &mut Self::Reader {
83        &mut self.reader
84    }
85
86    fn writer(&mut self) -> &mut Self::Writer {
87        &mut self.writer
88    }
89
90    fn get_value(&self) -> Option<&Value> {
91        self.val.as_ref()
92    }
93
94    fn increment_conn(&mut self) -> usize {
95        self.connection_count += 1;
96        self.connection_count
97    }
98
99    fn decrement_conn(&mut self) -> usize {
100        if self.connection_count > 0 {
101            self.connection_count -= 1;
102
103            if self.connection_count == 0 {
104                self.val = None;
105            }
106        }
107
108        self.connection_count
109    }
110}