pi_graph/
lib.rs

1//! 有向无环图
2
3use log::{debug, error};
4use std::{fmt::Debug, mem::replace, option::Iter, collections::VecDeque};
5use pi_slotmap::{Key, SecondaryMap};
6use pi_map::vecmap::VecMap;
7
8/// 有向无环图
9/// K 节点的键
10/// T 节点的值
11// #[delegate]
12pub trait DirectedGraph<K: Key, T> {
13    /// 节点
14    type Node: DirectedGraphNode<K, T>;
15
16    // /// 迭代器的关联类型,指定了迭代器`Item`为`K`
17    // type NodeIter: Iterator<Item = &'a K>;
18
19    /// 根据 key 取 节点
20    fn get(&self, key: K) -> Option<&Self::Node>;
21
22    /// 根据 key 取 节点
23    fn get_mut(&mut self, key: K) -> Option<&mut Self::Node>;
24
25    /// 取节点的数量
26    fn node_count(&self) -> usize;
27
28    /// 取 有输入节点 的 数量
29    fn from_len(&self) -> usize;
30
31    /// 取 有输出节点 的 数量
32    fn to_len(&self) -> usize;
33
34    /// 取 输入节点 切片
35    fn from(&self) -> &[K];
36
37    /// 取 输出节点 切片
38    fn to(&self) -> &[K];
39
40    /// 拓扑排序
41    fn topological_sort(&self) -> &[K];
42
43    // /// 全部节点的迭代器
44    // fn nodes('a self) -> Self::NodeIter;
45
46    // /// 获取图的froms节点的迭代器
47    // fn from(&'a self) -> Self::NodeIter;
48
49    // /// 获取图的froms节点的迭代器
50    // fn to(&'a self) -> Self::NodeIter;
51
52    // /// 从from节点开始的深度遍历迭代器
53    // fn from_dfs('a self) -> Self::NodeIter;
54
55    // /// 从from节点开始的深度遍历迭代器
56    // fn to_dfs('a self) -> Self::NodeIter;
57}
58
59/// 有向无环图 节点
60pub trait DirectedGraphNode<K: Key, T> {
61    // /// 迭代器的关联类型,指定了迭代器`Item`为`K`
62    // type NodeIter: Iterator<Item = &'a K>;
63
64    /// 取 from节点 的 数量
65    fn from_len(&self) -> usize;
66
67    /// 取 to节点 的 数量
68    fn to_len(&self) -> usize;
69
70    /// 取 入点 的 切片
71    fn from(&self) -> &[K];
72
73    /// 取 出点 的 切片
74    fn to(&self) -> &[K];
75
76    /// 取键的引用
77    fn key(&self) -> &K;
78
79    /// 取值的引用
80    fn value(&self) -> &T;
81
82    /// 取值的可变引用
83    fn value_mut(&mut self) -> &mut T;
84
85    // /// 读取计数器
86    // fn load_count(&self) -> usize;
87
88    // /// 增加计数器的值
89    // fn add_count(&mut self, add: usize) -> usize;
90
91    // /// 设置计数器的值
92    // fn set_count(&mut self, count: usize);
93
94    // /// 获取from节点的迭代器
95    // fn from(&self) -> Self::NodeIter;
96
97    // /// 获取to节点的迭代器
98    // fn to(&self) -> Self::NodeIter;
99}
100
101// 遍历邻居的迭代器 TODO 不好实现
102/// 节点 迭代器
103pub struct NodeIterator<'a, K>(Iter<'a, K>);
104
105impl<'a, K> Iterator for NodeIterator<'a, K> {
106    type Item = &'a K;
107
108    fn next(&mut self) -> Option<Self::Item> {
109        self.0.next()
110    }
111}
112
113/// 图
114#[derive(Default, Debug)]
115pub struct NGraph<K: Key, T> {
116    // 所有节点
117    map: SecondaryMap<K, NGraphNode<K, T>>,
118
119    // 入度为0 的 节点
120    from: Vec<K>,
121
122    // 出度为0 的 节点
123    to: Vec<K>,
124
125    // 拓扑排序后的结果
126    topological: Vec<K>,
127}
128
129/// 图节点
130#[derive(Debug)]
131pub struct NGraphNode<K: Key, T> {
132    // 该节点的 入度节点
133    from: Vec<K>,
134
135    // 该节点的 出度节点
136    to: Vec<K>,
137    // 键
138    key: K,
139    // 值
140    value: T,
141}
142
143impl<K: Key, T> NGraphNode<K, T>{
144	#[inline]
145	pub fn from(&mut self) -> &[K] {
146        &self.from
147    }
148	#[inline]
149	pub fn to(&mut self) -> &[K] {
150        &self.to
151    }
152
153	// 到 from 节点删掉 to
154	#[inline]
155	fn remove_edge_from(&mut self, from: K) -> bool {
156        if let Some(index) = self.from.iter().position(|v| *v == from) {
157            self.from.swap_remove(index);
158			true
159        } else {
160			false
161		}
162    }
163
164	// 到 to 节点删掉 from
165	#[inline]
166	fn remove_edge_to(&mut self, to: K) -> bool {
167        if let Some(index) = self.to.iter().position(|v| *v == to) {
168            self.to.swap_remove(index);
169			true
170        } else {
171			false
172		}
173    }
174
175	// 添加to
176	#[inline]
177    fn add_edge_to(&mut self, to: K) -> bool {
178        match self.to.iter().position(|s| *s == to) {
179            Some(_) => false,
180            None => {
181                self.to.push(to);
182                true
183            }
184        }
185    }
186
187    // // 添加from
188    // #[inline]
189    // fn add_edge_from(&mut self, from: K) -> bool {
190    //     match self.from.iter().position(|s| *s == from) {
191    //         Some(_) => false,
192    //         None => {
193    //             self.from.push(from);
194	// 			true
195    //         }
196    //     }
197    // }
198}
199
200impl<K: Key, T: Clone> Clone for NGraphNode<K, T> {
201    fn clone(&self) -> Self {
202        Self {
203            from: self.from.clone(),
204            to: self.to.clone(),
205            key: self.key.clone(),
206            value: self.value.clone(),
207        }
208    }
209}
210
211impl<K: Key, T> DirectedGraphNode<K, T> for NGraphNode<K, T> {
212    #[inline]
213	fn from_len(&self) -> usize {
214        self.from.len()
215    }
216
217	#[inline]
218    fn to_len(&self) -> usize {
219        self.to.len()
220    }
221
222	#[inline]
223    fn from(&self) -> &[K] {
224        &self.from[..]
225    }
226
227    fn to(&self) -> &[K] {
228        &self.to[..]
229    }
230
231	#[inline]
232    fn key(&self) -> &K {
233        &self.key
234    }
235
236	#[inline]
237    fn value(&self) -> &T {
238        &self.value
239    }
240
241	#[inline]
242    fn value_mut(&mut self) -> &mut T {
243        &mut self.value
244    }
245
246	// #[inline]
247    // fn load_count(&self) -> usize {
248	// 	self.count
249    //     // self.count.load(Ordering::Relaxed)
250    // }
251
252	// #[inline]
253    // fn add_count(&mut self, add: usize) -> usize {
254	// 	self.count += add;
255	// 	self.count
256    //     // self.count.fetch_add(add, Ordering::SeqCst)
257    // }
258
259	// #[inline]
260    // fn set_count(&mut self, count: usize) {
261	// 	self.count = count;
262    //     // self.count.store(count, Ordering::SeqCst)
263    // }
264}
265
266impl<K: Key, T> NGraph<K, T> {
267    pub(crate) fn new() -> Self {
268        Self {
269            map: Default::default(),
270            from: Default::default(),
271            to: Default::default(),
272            topological: Default::default(),
273        }
274    }
275
276    // /// 重置 图
277    // pub fn reset(&self) {
278    //     for n in self.map.values() {
279    //         n.set_count(0)
280    //     }
281    // }
282}
283
284impl<K: Key, T> NGraph<K, T> {
285    pub fn iter(&self) -> impl Iterator<Item = &T> {
286        self.map.values().into_iter().map(|v| v.value())
287    }
288}
289
290impl<K: Key, T> DirectedGraph<K, T> for NGraph<K, T> {
291    // /// 迭代器的关联类型,指定了迭代器`Item`为`K`
292    // type NodeIter = NodeIterator<'a, K>;
293
294    type Node = NGraphNode<K, T>;
295
296    fn get(&self, key: K) -> Option<&Self::Node> {
297        self.map.get(key)
298    }
299
300    fn get_mut(&mut self, key: K) -> Option<&mut Self::Node> {
301        self.map.get_mut(key)
302    }
303
304    fn node_count(&self) -> usize {
305        self.map.len()
306    }
307    fn from_len(&self) -> usize {
308        self.from.len()
309    }
310
311    fn to_len(&self) -> usize {
312        self.to.len()
313    }
314    fn from(&self) -> &[K] {
315        &self.from[..]
316    }
317
318    fn to(&self) -> &[K] {
319        &self.to[..]
320    }
321    fn topological_sort(&self) -> &[K] {
322        &self.topological[..]
323    }
324    // fn check_loop(&self) -> Option<&K> {
325    //     let mut stack = Vec::new();
326    //     let mut arr = (0, self.from());
327    //     loop {
328    //         while arr.0 < arr.1.len() {
329    //             let k = &arr.1[arr.0];
330    //             arr.0 += 1;
331    //             let n = self.get(k).unwrap();
332    //             if n.to_len() > 0 {
333    //                 if n.from_len() < n.load_count() {
334    //                     self.reset();
335    //                     return Some(k);
336    //                 }
337    //                 // 进入次数加1
338    //                 n.add_count(1);
339    //                 // 将当前的节点切片放入栈
340    //                 stack.push(arr);
341    //                 // 切换成检查下一层的节点切片
342    //                 arr = (0, n.to());
343    //             }
344    //         }
345    //         match stack.pop() {
346    //             Some(r) => arr = r,
347    //             _ => {
348    //                 self.reset();
349    //                 return None;
350    //             }
351    //         }
352    //     }
353    // }
354}
355
356impl<K: Key, T: Clone> NGraph<K, T> {
357    /// 遍历 局部图
358    pub fn gen_graph_from_keys(&self, finish: &[K]) -> Self {
359        let mut builder = NGraphBuilder::new();
360
361        debug!("gen_graph_from_keys, param keys = {:?}", finish);
362
363        let mut current_keys = vec![];
364        for k in finish {
365            current_keys.push(k.clone());
366
367            let n = self.map.get(k.clone()).unwrap();
368
369            // 防止 keys的 重复 元素
370            if !builder.has_node(*k) {
371                debug!("gen_graph_from_keys, add node k = {:?}", k);
372                builder.node(*k, n.value.clone());
373            }
374        }
375
376        while !current_keys.is_empty() {
377            debug!("gen_graph_from_keys, current_keys = {:?}", current_keys);
378
379            let mut from_keys = vec![];
380
381            for curr in current_keys.iter() {
382                let curr_node = self.map.get(curr.clone()).unwrap();
383
384                // 下一轮 出点
385                for from in curr_node.from() {
386                    let from_node = self.map.get(from.clone()).unwrap();
387
388                    if !builder.has_node(*from) {
389                        debug!("gen_graph_from_keys, add node next = {:?}", from);
390                        builder.node(from.clone(), from_node.value.clone());
391                    }
392
393                    debug!("gen_graph_from_keys, add edge = ({:?}, {:?})", from, curr);
394                    builder.edge(from.clone(), curr.clone());
395                    from_keys.push(from.clone());
396                }
397            }
398
399            debug!("gen_graph_from_keys, from_keys = {:?}", from_keys);
400
401            let _ = replace(&mut current_keys, from_keys);
402        }
403
404        builder.build().unwrap()
405    }
406}
407
408/// 图 构建器
409pub struct NGraphBuilder<K: Key, T> {
410    graph: NGraph<K, T>,
411}
412
413impl<K: Key, T> NGraphBuilder<K, T> {
414    /// 创建 默认
415    pub fn new() -> Self {
416        NGraphBuilder {
417            graph: NGraph::new(),
418        }
419    }
420
421    /// 用已有的图 重新 构建
422    pub fn new_with_graph(graph: NGraph<K, T>) -> Self {
423        // graph.from.clear();
424        // graph.to.clear();
425        // graph.topological.clear();
426
427        NGraphBuilder { graph }
428    }
429
430	pub fn graph(&self) -> &NGraph<K, T> {
431        &self.graph
432    }
433
434    /// 对应节点是否存在
435    pub fn has_node(&self, key: K) -> bool {
436        self.graph.map.contains_key(key)
437    }
438
439    /// 添加 节点
440    pub fn node(&mut self, key: K, value: T) -> &mut Self {
441		log::debug!("add node={:?}", key);
442        self.graph.map.insert(
443            key.clone(),
444            NGraphNode {
445                from: Default::default(),
446                to: Default::default(),
447                key,
448                value,
449            },
450        );
451
452        self
453    }
454
455    /// 添加 边
456    pub fn edge(&mut self, from: K, to: K) -> &mut Self {
457		if let Some([from_node, to_node]) = self.graph.map.get_disjoint_mut([from, to]) {
458			log::debug!("add edge=({:?}, {:?})", from, to);
459			if from_node.add_edge_to(to) {
460				to_node.from.push(from);
461			}
462		}
463        self
464    }
465
466    /// 移除 节点
467    pub fn remove_node(&mut self, key: K) -> &mut Self {
468		if let Some(node) = self.graph.map.remove(key) {
469			log::debug!("remove node={:?}, from={:?}, to={:?}", key, &node.from, &node.to);
470			for f in node.from.iter() {
471				self.graph.map.get_mut(*f).unwrap().remove_edge_to(key);
472			}
473	
474			for t in node.to.iter() {
475				self.graph.map.get_mut(*t).unwrap().remove_edge_from(key);
476			}
477		}
478        self
479    }
480
481    /// 移除 边
482    pub fn remove_edge(&mut self, from: K, to: K) -> &mut Self {
483		if let Some(from_node) = self.graph.map.get_mut(from) {
484			if from_node.remove_edge_to(to) {
485				self.graph.map.get_mut(to).unwrap().remove_edge_from(from);
486				log::debug!("remove edge=({:?}, {:?})", from, to);
487			}
488		}
489        self
490    }
491
492    /// 构建图
493    /// 返回Graph,或者 回环的节点
494    pub fn build(mut self) -> Result<NGraph<K, T>, Vec<K>> {
495		self.graph.from.clear();
496		self.graph.to.clear();
497		self.graph.topological.clear();
498		let mut counts = VecMap::with_capacity(self.graph.map.len());
499		let mut graph = &mut self.graph;
500		// 已经处理过的节点Key
501        let NGraph{topological, from, to, map, ..} = &mut graph;
502
503        // 计算开头 和 结尾的 节点
504        for (k, v) in map.iter() {
505            // 开头:没有入边的点
506            if v.from.is_empty() {
507                from.push(k);
508            }
509
510            // 结尾:没有出边的点
511            if v.to.is_empty() {
512                to.push(k);
513            }
514
515			counts.insert(key_index(k), v.from.len());
516        }
517
518        debug!("graph's from = {:?}", from);
519		let mut queue = from.iter().copied().collect::<VecDeque<K>>();
520        while let Some(k) = queue.pop_front() {
521            topological.push(k);
522			
523            // 处理 from 的 下一层
524            let node = map.get(k).unwrap();
525			debug!("from = {:?}, to: {:?}", k, node.to());
526            // 遍历节点的后续节点
527            for to in node.to()  {
528				debug!("graph's each = {:?}, count = {:?}", to, counts[key_index(*to)]);
529				counts[key_index(*to)] -= 1;
530                // handle_set.insert(*to, ());
531				if counts[key_index(*to)] == 0 {
532					queue.push_back(*to);
533				}
534                // // 即将处理:将节点的计数加1
535                // let n = map.get_mut(*to).unwrap();
536                // n.add_count(1);
537
538                // debug!(
539                //     "add n: k: {:?}, from:{} count:{}",
540                //     to,
541                //     n.from_len(),
542                //     n.load_count()
543                // );
544            }
545        }
546
547		// 如果拓扑排序列表的节点数等于图中的总节点数,则返回拓扑排序列表,否则返回空列表(说明图中存在环路)
548		if topological.len() == map.len() {
549			// topological = topos;
550			return Ok(self.graph);
551		} else {
552			topological.clear();
553		}
554
555		let keys = map.keys().map(|k|{k.clone()}).filter(|r| {!topological.contains(r)}).collect::<Vec<K>>();
556		let mut iter = keys.into_iter();
557		while let Some(n) = iter.next() {
558			let mut cycle_keys = Vec::new();
559			Self::find_cycle(map, n, &mut cycle_keys, Vec::new());
560
561			if cycle_keys.len() > 0 {
562				let cycle: Vec<(K, T)> = cycle_keys.iter().map(|k| {(k.clone(), map.remove(*k).unwrap().value)}).collect();
563				pi_print_any::out_any!(error, "graph build error, no from node, they make cycle: {:?}", cycle);
564				return Result::Err(cycle_keys);
565			}
566		}
567		return Result::Err(Vec::new());
568    }
569    /// 寻找循环依赖
570    fn find_cycle(map: &SecondaryMap<K, NGraphNode<K, T>>, node: K, nodes: &mut Vec<K>, mut indexs: Vec<usize>) {
571		nodes.push(node.clone());
572        indexs.push(0);
573        while nodes.len() > 0 {
574            let index = nodes.len() - 1;
575            let k = &nodes[index];
576            let n = map.get(*k).unwrap();
577            let to = n.to();
578            let child_index = indexs[index];
579            if child_index >= to.len() {
580                nodes.pop();
581                indexs.pop();
582                continue
583            }
584            let child = to[child_index].clone();
585            if child == node {
586                break;
587            }
588            indexs[index] += 1;
589            nodes.push(child);
590            indexs.push(0);
591        }
592    }
593}
594
595#[inline]
596pub fn key_index<K: Key>(k: K) -> usize{
597	k.data().as_ffi() as u32 as usize
598}
599
600#[cfg(test)]
601mod tests {
602    use pi_slotmap::{DefaultKey, SlotMap};
603
604    use crate::*;
605
606    use std::sync::Once;
607
608    static INIT: Once = Once::new();
609    fn setup_logger() {
610        use env_logger::{Builder, Env};
611
612        INIT.call_once(|| {
613            Builder::from_env(Env::default().default_filter_or("debug")).init();
614        });
615    }
616
617    // 测试 无节点 的 图
618    #[test]
619    fn test_empty() {
620        setup_logger();
621
622        let graph = NGraphBuilder::<DefaultKey, u32>::new().build();
623
624        assert_eq!(graph.is_ok(), true);
625
626        let graph = graph.unwrap();
627        assert_eq!(graph.node_count(), 0);
628
629        assert_eq!(graph.from_len(), 0);
630        assert_eq!(graph.from(), &[]);
631
632        assert_eq!(graph.to_len(), 0);
633        assert_eq!(graph.to(), &[]);
634
635        assert_eq!(graph.topological_sort(), &[]);
636    }
637
638    // 测试 1个节点的 图
639    #[test]
640    fn test_one_node() {
641        setup_logger();
642		let mut map = SlotMap::<DefaultKey, ()>::default();
643		let node = map.insert(());
644        let mut graph = NGraphBuilder::new();
645		graph.node(node, 111);
646		let graph = graph.build();
647
648        assert_eq!(graph.is_ok(), true);
649
650        let graph = graph.unwrap();
651        assert_eq!(graph.node_count(), 1);
652
653        assert_eq!(graph.from_len(), 1);
654        assert_eq!(graph.from(), &[node]);
655
656        assert_eq!(graph.to_len(), 1);
657        assert_eq!(graph.to(), &[node]);
658
659        assert_eq!(graph.topological_sort(), &[node]);
660    }
661
662    // 测试 无边 的 图
663    #[test]
664    fn test_no_edge() {
665        setup_logger();
666		let mut map = SlotMap::<DefaultKey, ()>::default();
667		let node = [map.insert(()), map.insert(()), map.insert(())];
668        // 1 2 3
669        let mut graph = NGraphBuilder::new();
670		graph.node(node[0], 1)
671            .node(node[1], 2)
672            .node(node[2], 3);
673		let graph = graph.build();
674
675        assert_eq!(graph.is_ok(), true);
676
677        let graph = graph.unwrap();
678        assert_eq!(graph.node_count(), 3);
679
680        assert_eq!(graph.from_len(), 3);
681        assert_eq!(graph.from(), node.as_slice());
682
683        assert_eq!(graph.to_len(), 3);
684        assert_eq!(graph.to(), node.as_slice());
685
686        assert_eq!(graph.topological_sort(), node.as_slice());
687    }
688
689	// 测试 无边 的 图
690    #[test]
691    fn test_no_edge1() {
692        setup_logger();
693		let mut map = SlotMap::<DefaultKey, ()>::default();
694		let node = [map.insert(()), map.insert(()), map.insert(()), map.insert(())];
695        // 1 2 3
696        let mut graph = NGraphBuilder::new();
697        graph.node(node[0], 1)
698            .node(node[1], 2)
699            .node(node[2], 3)
700			.node(node[3], 4)
701			.edge(node[0], node[1])
702            .edge(node[0], node[2])
703			.edge(node[2], node[1])
704			.edge(node[1], node[3]);
705        let _graph = graph.build();
706
707        // assert_eq!(graph.is_ok(), true);
708
709        // let graph = graph.unwrap();
710        // assert_eq!(graph.node_count(), 3);
711
712        // assert_eq!(graph.from_len(), 3);
713        // assert_eq!(graph.from(), &[1, 2, 3]);
714
715        // assert_eq!(graph.to_len(), 3);
716        // assert_eq!(graph.to(), &[1, 2, 3]);
717
718        // assert_eq!(graph.topological_sort(), &[1, 2, 3]);
719    }
720
721    // 测试 简单的 图
722    #[test]
723    fn test_simple() {
724        setup_logger();
725		let mut map = SlotMap::<DefaultKey, ()>::default();
726		let node = [map.insert(()), map.insert(()), map.insert(()), map.insert(())];
727        // 1 --> 2 --> 3
728        let mut graph = NGraphBuilder::new();
729        graph.node(node[1], 1)
730            .node(node[2], 2)
731            .node(node[3], 3)
732            .edge(node[1], node[2])
733            .edge(node[2], node[3]);
734        let graph = graph.build();
735
736        assert_eq!(graph.is_ok(), true);
737
738        let graph = graph.unwrap();
739        assert_eq!(graph.node_count(), 3);
740
741        assert_eq!(graph.from_len(), 1);
742        assert_eq!(graph.from(), &[node[1]]);
743
744        assert_eq!(graph.to_len(), 1);
745        assert_eq!(graph.to(), &[node[3]]);
746
747        assert_eq!(graph.topological_sort(), &[node[1], node[2], node[3]]);
748    }
749
750    // 测试 循环图
751    #[test]
752    fn test_cycle_graph() {
753        setup_logger();
754		let mut map = SlotMap::<DefaultKey, ()>::default();
755		let node = [map.insert(()), map.insert(()), map.insert(()), map.insert(())];
756        // 1 --> 2 --> 3 --> 1
757        let mut graph = NGraphBuilder::new();
758        graph.node(node[1], 1)
759            .node(node[2], 2)
760            .node(node[3], 3)
761            .edge(node[1], node[2])
762            .edge(node[2], node[3])
763            .edge(node[3], node[1]);
764        let graph = graph.build();
765
766        assert_eq!(graph.is_err(), true);
767        if let Err(r) = graph {
768            assert_eq!(&r, &[node[1], node[2], node[3]]);
769        }
770    }
771
772    // 测试 局部 循环
773    #[test]
774    fn test_cycle_local() {
775        setup_logger();
776		let mut map = SlotMap::<DefaultKey, ()>::default();
777		let node = [map.insert(()), map.insert(()), map.insert(()), map.insert(())];
778        // 1 --> 2 <--> 3
779        let mut graph = NGraphBuilder::new();
780		graph.node(node[1], 1)
781            .node(node[2], 2)
782            .node(node[3], 3)
783            .edge(node[1], node[2])
784            .edge(node[2], node[3])
785            .edge(node[3], node[2]);
786        let graph = graph.build();
787
788        assert_eq!(graph.is_err(), true);
789        if let Err(r) = graph {
790            assert_eq!(&r, &[node[2], node[3]]);
791        }
792    }
793
794    // 生成局部图
795    #[test]
796    fn test_gen_graph() {
797        setup_logger();
798		let mut map = SlotMap::<DefaultKey, ()>::default();
799		let node = [
800			map.insert(()), map.insert(()), map.insert(()), map.insert(()),
801			map.insert(()), map.insert(()), map.insert(()), map.insert(())
802		];
803        // 7 --> 2, 6
804        // 2, 3 --> 1
805        // 5, 6 --> 4
806        let mut graph = NGraphBuilder::new();
807        graph.node(node[1], 1)
808            .node(node[2], 2)
809            .node(node[3], 3)
810            .node(node[4], 4)
811            .node(node[5], 5)
812            .node(node[6], 6)
813            .node(node[7], 7)
814            .edge(node[7], node[2])
815            .edge(node[7], node[6])
816            .edge(node[2], node[1])
817            .edge(node[3], node[1])
818            .edge(node[5], node[4])
819            .edge(node[6], node[4]);
820        let graph = graph.build();
821
822        assert_eq!(graph.is_ok(), true);
823
824        let graph = graph.unwrap();
825        let g2 = graph.gen_graph_from_keys(&[node[7]]);
826        assert_eq!(g2.node_count(), 1);
827    }
828
829    // 复杂
830    #[test]
831    fn test_complex() {
832        setup_logger();
833		let mut map = SlotMap::<DefaultKey, ()>::default();
834		let node = [
835			map.insert(()), map.insert(()), map.insert(()), map.insert(()),
836			map.insert(()), map.insert(()),
837		];
838        // 1 --> 3
839        // 2 --> 3, 4, 5
840        // 4 --> 5
841        let mut graph = NGraphBuilder::new();
842        graph.node(node[1], 1)
843            .node(node[2], 2)
844            .node(node[3], 3)
845            .node(node[4], 4)
846            .node(node[5], 5)
847            .edge(node[1], node[3])
848            .edge(node[2], node[3])
849            .edge(node[2], node[4])
850            .edge(node[2], node[5])
851            .edge(node[4], node[5]);
852        let graph = graph.build();
853
854        assert_eq!(graph.is_ok(), true);
855
856        let graph = graph.unwrap();
857        assert_eq!(graph.node_count(), 5);
858
859        assert_eq!(graph.from_len(), 2);
860
861        let mut v: Vec<DefaultKey> = graph.from().iter().cloned().collect();
862        v.sort();
863        assert_eq!(&v, &[node[1], node[2]]);
864
865        assert_eq!(graph.to_len(), 2);
866        let mut v: Vec<DefaultKey> = graph.to().iter().cloned().collect();
867        v.sort();
868        assert_eq!(&v, &[node[3], node[5]]);
869
870        assert_eq!(graph.topological_sort(), &[node[1], node[2], node[3], node[4], node[5]]);
871    }
872
873    #[test]
874    fn test_graph() {
875        setup_logger();
876		let mut map = SlotMap::<DefaultKey, ()>::default();
877		let node = [
878			map.insert(()), map.insert(()), map.insert(()), map.insert(()),
879			map.insert(()), map.insert(()), map.insert(()), map.insert(()),
880			map.insert(()), map.insert(()), map.insert(()), map.insert(()),
881		];
882        let mut graph = NGraphBuilder::new();
883        graph.node(node[1], 1)
884            .node(node[2], 2)
885            .node(node[3], 3)
886            .node(node[4], 4)
887            .node(node[5], 5)
888            .node(node[6], 6)
889            .node(node[7], 7)
890            .node(node[8], 8)
891            .node(node[9], 9)
892            .node(node[10], 10)
893            .node(node[11], 11)
894            .edge(node[1], node[4])
895            .edge(node[2], node[4])
896            .edge(node[2], node[5])
897            .edge(node[3], node[5])
898            .edge(node[4], node[6])
899            .edge(node[4], node[7])
900            .edge(node[5], node[8])
901            .edge(node[9], node[10])
902            .edge(node[10], node[11])
903            .edge(node[11], node[5])
904            .edge(node[5], node[10]);
905        let graph = graph.build();
906
907        assert_eq!(graph.is_err(), true);
908        if let Err(v) = graph {
909            assert_eq!(&v, &[node[5], node[10], node[11]]);
910        }
911    }
912
913	// 添加重复边、不存在节点的边、相同节点但是反向的边(循环依赖)
914    #[test]
915    fn test_add_repeat_edge() {
916        setup_logger();
917		let mut map = SlotMap::<DefaultKey, ()>::default();
918		let node = [
919			map.insert(()), map.insert(()), map.insert(()), map.insert(()),
920			map.insert(()), map.insert(()),
921		];
922        // 1 --> 3
923        // 2 --> 3, 4, 5
924        // 4 --> 5
925        let mut graph = NGraphBuilder::new();
926        graph.node(node[1], 1)
927            .node(node[2], 2)
928            .edge(node[1], node[2])
929            .edge(node[1], node[2])
930            // .edge(node[2], node[1])
931            .edge(node[2], node[3]);
932        let graph = graph.build();
933
934        assert_eq!(graph.is_ok(), true);
935
936        let graph = graph.unwrap();
937
938        let v: Vec<DefaultKey> = graph.from().iter().cloned().collect();
939        assert_eq!(&v, &[node[1]]);
940
941        let v: Vec<DefaultKey> = graph.get(node[1]).unwrap().to().iter().cloned().collect();
942        assert_eq!(&v, &[node[2]]);
943
944    }
945}