meshed/graph/
edge.rs

1/*
2 * Copyright [2022] [Kevin Velasco]
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use crate::graph::node::Node;
18use crate::graph::GraphDefinition;
19use crate::identify::{Identifiable, Identity};
20use std::cmp::Ordering;
21use std::fmt::{Display, Formatter};
22use std::marker::PhantomData;
23use std::rc::Rc;
24
25pub struct Edge<T: GraphDefinition> {
26    pub origin: Node<T>,
27    pub target: Node<T>,
28    pub meta: Rc<T::EdgeMeta>,
29    pub graph_type: PhantomData<T>,
30}
31
32impl<T: GraphDefinition> Edge<T> {
33    pub fn new(from: Node<T>, to: Node<T>, meta: Rc<T::EdgeMeta>) -> Self {
34        Self {
35            origin: from,
36            target: to,
37            meta,
38            graph_type: Default::default(),
39        }
40    }
41}
42
43impl<T: GraphDefinition> Clone for Edge<T> {
44    fn clone(&self) -> Self {
45        Self {
46            origin: self.origin.clone(),
47            target: self.target.clone(),
48            meta: Rc::clone(&self.meta),
49            graph_type: Default::default(),
50        }
51    }
52}
53
54impl<T: GraphDefinition> PartialEq for Edge<T> {
55    fn eq(&self, other: &Self) -> bool {
56        self.get_id() == other.get_id()
57    }
58}
59
60impl<T: GraphDefinition> PartialOrd for Edge<T> {
61    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
62        self.get_id().partial_cmp(&other.get_id())
63    }
64}
65
66impl<T: GraphDefinition> Eq for Edge<T> {}
67
68impl<T: GraphDefinition> Ord for Edge<T> {
69    fn cmp(&self, other: &Self) -> Ordering {
70        self.get_id().cmp(&other.get_id())
71    }
72}
73
74#[derive(Clone, PartialOrd, PartialEq, Eq, Ord, Hash, Debug)]
75pub struct EdgeIdentity<I: Identity>(I, I);
76
77impl<I: Identity> Display for EdgeIdentity<I> {
78    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
79        write!(f, "[{} -> {} ]", &self.0, &self.1)
80    }
81}
82
83impl<I: Identity> Identity for EdgeIdentity<I> {}
84
85// Edges who's metadata is identifiable (unique) are identifiable.
86impl<T> Identifiable<EdgeIdentity<T::Id>> for Edge<T>
87where
88    T: GraphDefinition,
89{
90    fn get_id(&self) -> EdgeIdentity<T::Id> {
91        EdgeIdentity(self.origin.get_id(), self.target.get_id())
92    }
93}