1use indexmap::IndexMap;
2use std::hash::Hash;
3
4#[cfg(feature = "serde")]
5use serde::{Deserialize, Serialize};
6
7pub type NodeMap<T> = IndexMap<NodeId, T>;
8
9pub trait IdAnnotated<T: Copy> {
10 fn id(&self) -> T;
11}
12
13#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
14#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
15pub struct NodeId(pub u32);
16
17impl IdAnnotated<NodeId> for NodeId {
18 fn id(&self) -> NodeId {
19 *self
20 }
21}
22
23#[derive(Debug)]
24pub struct AutoNodeIdGenerator {
26 next_id: NodeId,
27}
28
29impl Default for AutoNodeIdGenerator {
30 fn default() -> Self {
31 AutoNodeIdGenerator { next_id: NodeId(1) }
32 }
33}
34
35pub trait NodeIdGenerator {
37 fn next_id(&mut self) -> NodeId;
39}
40
41impl NodeIdGenerator for AutoNodeIdGenerator {
42 #[inline]
43 fn next_id(&mut self) -> NodeId {
44 let mut next = NodeId(&self.next_id.0 + 1);
45 std::mem::swap(&mut self.next_id, &mut next);
46 next
47 }
48}
49
50#[derive(Default)]
52pub struct NullIdGenerator {}
53
54impl NodeIdGenerator for NullIdGenerator {
55 fn next_id(&mut self) -> NodeId {
56 NodeId(0)
57 }
58}
59
60#[cfg(test)]
61mod tests {
62 use crate::node::{AutoNodeIdGenerator, NodeIdGenerator};
63
64 #[test]
65 fn unique_ids() {
66 let mut gen = AutoNodeIdGenerator::default();
67
68 let ids: Vec<_> = std::iter::repeat_with(|| gen.next_id()).take(15).collect();
69 dbg!(&ids);
70 for i in 0..ids.len() {
71 for j in i + 1..ids.len() {
72 assert_ne!(ids[i], ids[j]);
73 }
74 }
75 }
76}