1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
//! Element definitions

use crate::error::{ElementAppendError, ElementBuildError, UnknownElementError};
use crate::ElementConf;
use common::{DcElement, DcMsgReceiver, DcPipeline, MsgReceiver, Pipeline};
pub use common::{ElementResult, ElementValue, MsgType, Port};
use serde::de::DeserializeOwned;
use std::collections::HashMap;

pub(crate) type ElementNextBoxed =
    Box<dyn FnMut(*mut DcPipeline, *mut DcMsgReceiver) -> ElementResult + Send>;
pub type ElementFinalizer = Box<dyn FnOnce() -> Result<(), crate::error::Error> + Send>;

/// Prepared element to execute
pub struct ElementExecutable {
    pub(crate) next_boxed: ElementNextBoxed,
    pub(crate) finalizer: Option<ElementFinalizer>,
}

/// Opaque type to build element
#[derive(Clone)]
pub enum ElementBuilder {
    Native(fn(ElementConf) -> Result<ElementExecutable, crate::error::Error>),
    Plugin(DcElement),
}

impl ElementBuilder {
    pub(crate) fn build(
        &self,
        conf: ElementConf,
    ) -> Result<ElementExecutable, crate::error::Error> {
        match self {
            ElementBuilder::Native(build_executable) => build_executable(conf),
            ElementBuilder::Plugin(element) => crate::plugin::build_plugin_element(*element, &conf),
        }
    }
}

/// Unit of task execution.
pub struct ElementPreBuild {
    conf: ElementConf,
    builder: ElementBuilder,
}

impl ElementPreBuild {
    pub(crate) fn build(&mut self) -> Result<ElementExecutable, crate::error::Error> {
        self.builder.build(self.conf.clone())
    }
}

/// Buildable element from config.
pub trait ElementBuildable: Sized + Send + 'static {
    /// Configuration type for this element
    type Config: DeserializeOwned;

    /// Name of this element. Must be unique in elements
    const NAME: &'static str;

    /// The number of receiving ports
    const RECV_PORTS: Port = 0;

    /// The number of sending ports
    const SEND_PORTS: Port = 0;

    /// Returns acceptable message type of this element
    fn acceptable_msg_types() -> Vec<Vec<MsgType>> {
        Vec::new()
    }

    /// Create element from config
    fn new(conf: Self::Config) -> Result<Self, crate::error::Error>;

    /// Get message from `receiver` and returns the result of this element.
    fn next(&mut self, pipeline: &mut Pipeline, receiver: &mut MsgReceiver) -> ElementResult;

    /// Returns the finalizer of this element
    fn finalizer(&mut self) -> Result<Option<ElementFinalizer>, crate::error::Error> {
        Ok(None)
    }

    #[doc(hidden)]
    fn element_conf_to_executable(
        conf: ElementConf,
    ) -> Result<ElementExecutable, crate::error::Error> {
        let conf: Self::Config = conf.to_conf()?;
        let mut element = Self::new(conf)?;
        let finalizer = element.finalizer()?;
        let next_boxed: ElementNextBoxed = Box::new(move |pipeline, recv| {
            let mut pipeline = unsafe { Pipeline::new(pipeline) };
            let mut recv = unsafe { MsgReceiver::new(recv) };
            element.next(&mut pipeline, &mut recv)
        });
        Ok(ElementExecutable {
            next_boxed,
            finalizer,
        })
    }

    #[doc(hidden)]
    fn builder() -> ElementBuilder {
        ElementBuilder::Native(Self::element_conf_to_executable)
    }
}

type RecvMsgTypeGetter = Box<dyn Fn() -> Vec<Vec<MsgType>>>;

/// Holds buildable element list.
pub struct ElementBank {
    builders: HashMap<String, ElementBuilder>,
    acceptable_msg_types: HashMap<String, RecvMsgTypeGetter>,
    ports: HashMap<String, (Port, Port)>,
}

impl Default for ElementBank {
    fn default() -> Self {
        ElementBank::new()
    }
}

impl ElementBank {
    /// New empty ElementBank.
    pub fn empty() -> Self {
        ElementBank {
            builders: HashMap::default(),
            acceptable_msg_types: HashMap::default(),
            ports: HashMap::default(),
        }
    }

    /// Append element.
    pub(crate) fn append(
        &mut self,
        name: &str,
        builder: ElementBuilder,
        acceptable_msg_types: RecvMsgTypeGetter,
        ports: (Port, Port),
    ) -> Result<(), ElementAppendError> {
        if self.builders.contains_key(name) {
            return Err(ElementAppendError(format!(
                "element name duplication detected for \"{}\"",
                name
            )));
        }

        self.builders.insert(name.to_owned(), builder);
        self.acceptable_msg_types
            .insert(name.to_owned(), acceptable_msg_types);
        self.ports.insert(name.to_owned(), ports);

        log::trace!("append \"{}\" to element bank", name);
        Ok(())
    }

    /// Register buildable element.
    pub fn append_from_buildable<E: ElementBuildable + 'static>(
        &mut self,
    ) -> Result<(), ElementAppendError> {
        self.append(
            E::NAME,
            ElementBuilder::Native(E::element_conf_to_executable),
            Box::new(E::acceptable_msg_types),
            (E::RECV_PORTS, E::SEND_PORTS),
        )
    }

    /// get pre build element by name and config.
    pub fn pre_build(
        &self,
        name: &str,
        conf: ElementConf,
    ) -> Result<ElementPreBuild, ElementBuildError> {
        if let Some(builder) = self.builders.get(name) {
            Ok(ElementPreBuild {
                conf,
                builder: builder.clone(),
            })
        } else {
            Err(ElementBuildError::UnknownElement(UnknownElementError(
                name.into(),
            )))
        }
    }

    /// Get acceptable message types.
    pub fn acceptable_msg_types(
        &self,
        name: &str,
    ) -> Result<Vec<Vec<MsgType>>, UnknownElementError> {
        self.acceptable_msg_types
            .get(name)
            .map(|f| f())
            .ok_or_else(|| UnknownElementError(name.into()))
    }

    /// Get the number of ports of element.
    pub fn ports(&self, name: &str) -> Result<(Port, Port), UnknownElementError> {
        self.ports
            .get(name)
            .copied()
            .ok_or_else(|| UnknownElementError(name.into()))
    }

    /// New ElementBank with core elements.
    pub fn new() -> Self {
        let mut bank = Self::empty();

        crate::base::append_to_bank(&mut bank);

        bank
    }
}