use crate::ids::{NodeId, PortId};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Side {
Left,
#[default]
Right,
Top,
Bottom,
}
impl Side {
pub fn is_horizontal(self) -> bool {
matches!(self, Side::Left | Side::Right)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum PortDirection {
Input,
Output,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum PortScope {
#[default]
Local,
Boundary,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum PortType {
#[default]
Any,
Bool,
Int,
Float,
String,
List(Box<PortType>),
Map(Box<PortType>, Box<PortType>),
Custom(Arc<str>),
Union(Vec<PortType>),
}
impl PortType {
pub fn flows_into(&self, input: &PortType) -> bool {
use PortType::*;
match (self, input) {
(Any, _) | (_, Any) => true,
(Union(outs), _) => outs.iter().all(|o| o.flows_into(input)),
(_, Union(ins)) => ins.iter().any(|i| self.flows_into(i)),
(Int, Float) => true,
(List(a), List(b)) => a.flows_into(b),
(Map(ka, va), Map(kb, vb)) => ka.flows_into(kb) && va.flows_into(vb),
(a, b) => a == b,
}
}
pub fn label(&self) -> String {
use PortType::*;
match self {
Any => "any".into(),
Bool => "bool".into(),
Int => "int".into(),
Float => "float".into(),
String => "string".into(),
List(t) => format!("list<{}>", t.label()),
Map(k, v) => format!("map<{}, {}>", k.label(), v.label()),
Custom(n) => n.to_string(),
Union(ts) => ts.iter().map(|t| t.label()).collect::<Vec<_>>().join(" | "),
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Port {
pub id: PortId,
pub node: NodeId,
pub direction: PortDirection,
pub side: Side,
pub ty: PortType,
#[serde(default)]
pub scope: PortScope,
pub max_connections: Option<usize>,
pub label: Option<Arc<str>>,
#[serde(default = "default_true")]
pub connectable: bool,
}
fn default_true() -> bool {
true
}
impl Port {
pub fn new(id: PortId, node: NodeId, direction: PortDirection) -> Self {
let (side, max_connections) = match direction {
PortDirection::Input => (Side::Left, Some(1)),
PortDirection::Output => (Side::Right, None),
};
Self {
id,
node,
direction,
side,
ty: PortType::Any,
scope: PortScope::Local,
max_connections,
label: None,
connectable: true,
}
}
}
#[cfg(test)]
mod tests {
use super::PortType::*;
#[test]
fn type_compatibility() {
assert!(Int.flows_into(&Float));
assert!(!Float.flows_into(&Int));
assert!(Any.flows_into(&String));
assert!(String.flows_into(&Union(vec![Int, String])));
assert!(!Union(vec![Int, String]).flows_into(&Int));
assert!(List(Box::new(Int)).flows_into(&List(Box::new(Float))));
assert!(!List(Box::new(String)).flows_into(&List(Box::new(Int))));
assert_eq!(
Map(Box::new(String), Box::new(Int)).label(),
"map<string, int>"
);
}
}