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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
use std::collections::BTreeMap;
use std::fmt::Debug;
use fast_paths::{InputGraph, NodeId};
use serde::{Deserialize, Deserializer, Serialize};
#[derive(Clone, Serialize)]
pub struct NodeMap<T: Copy + Ord + Debug + Serialize> {
#[serde(skip_serializing)]
node_to_id: BTreeMap<T, NodeId>,
id_to_node: Vec<T>,
}
impl<T: Copy + Ord + Debug + Serialize> NodeMap<T> {
pub fn new() -> NodeMap<T> {
NodeMap {
node_to_id: BTreeMap::new(),
id_to_node: Vec::new(),
}
}
pub fn get_or_insert(&mut self, node: T) -> NodeId {
if let Some(id) = self.node_to_id.get(&node) {
return *id;
}
let id = self.id_to_node.len();
self.node_to_id.insert(node, id);
self.id_to_node.push(node);
id
}
pub fn get(&self, node: T) -> NodeId {
if let Some(id) = self.node_to_id.get(&node) {
*id
} else {
panic!("{:?} not in NodeMap", node);
}
}
pub fn translate_id(&self, id: usize) -> T {
self.id_to_node[id]
}
pub fn guarantee_node_ordering(&self, input_graph: &mut InputGraph) {
let last_node = self.id_to_node.len() - 1;
input_graph.freeze();
for edge in input_graph.get_edges() {
if edge.from == last_node || edge.to == last_node {
input_graph.thaw();
return;
}
}
input_graph.thaw();
let first_node = 0;
input_graph.add_edge(last_node, first_node, 1);
}
}
#[derive(Deserialize)]
struct InnerNodeMap<T: Copy + Ord + Debug> {
id_to_node: Vec<T>,
}
pub fn deserialize_nodemap<
'de,
D: Deserializer<'de>,
T: Deserialize<'de> + Copy + Ord + Debug + Serialize,
>(
d: D,
) -> Result<NodeMap<T>, D::Error> {
let inner = <InnerNodeMap<T>>::deserialize(d)?;
let id_to_node = inner.id_to_node;
let mut node_to_id = BTreeMap::new();
for (id, node) in id_to_node.iter().enumerate() {
node_to_id.insert(*node, id);
}
Ok(NodeMap {
node_to_id,
id_to_node,
})
}