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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */


use std::any::Any;
use std::any::TypeId;
use std::sync::Arc;
use std::sync::Mutex;
use crate::DErr;
use crate::executor::Executor;
use crate::node::AbstAggregator;


///An edge which transports data. The type id can be retrieved at runtime via the type id
#[derive(Clone)]
pub struct Edge{
    pub type_id: TypeId,
    pub start_node: Arc<Mutex<dyn AbstAggregator + Send>>,
    pub start_idx: usize,
    pub end_node: Arc<Mutex<dyn AbstAggregator + Send>>,
    pub end_idx: usize
}

impl Edge{
    ///Connects some start node (`start`) from the output at index `start_idx`. To the node `end`s input pin at `end_idx`.
    pub fn connect(
	start: Arc<Mutex<dyn AbstAggregator + Send>>,
	start_idx: usize,
	end: Arc<Mutex<dyn AbstAggregator + Send>>,
	end_idx: usize
    ) -> Result<(), DErr>{
	if start.lock().unwrap().out_type_id(start_idx) != end.lock().unwrap().in_type_id(end_idx){
	    return Err(DErr::TypeMissmatch);
	}
	let edge = Edge{
	    type_id: start.lock().unwrap().out_type_id(start_idx).unwrap(),
	    start_node: start.clone(),
	    start_idx,
	    end_node: end.clone(),
	    end_idx
	};
	start.lock().unwrap().set_out_edge(edge.clone())?;
	end.lock().unwrap().set_in_edge(edge)?;
	Ok(())
    }
    
    pub fn send<T>(&self, executor: Arc<Executor>, data: Box<T>) -> Result<(), DErr> where T: Any{
	if TypeId::of::<T>() == self.type_id{
	    self.end_node.lock().unwrap().set_in_from_edge(executor, self.end_idx, data)?;
	    Ok(())
	}else{
	    Err(DErr::TypeMissmatch)
	}
    }
}