Skip to content

Commit 7fa6c77

Browse files
committed
Added Graph::map_labels() api
1 parent 6663ebb commit 7fa6c77

1 file changed

Lines changed: 51 additions & 1 deletion

File tree

src/graph.rs

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1297,7 +1297,7 @@ impl<T> Graph<T>
12971297

12981298
let encoded = hex::encode(&to_encode);
12991299
let label = format!("N_{}", encoded);
1300-
assert!(dot::Id::new(label.to_owned()).is_ok());
1300+
debug_assert!(dot::Id::new(label.to_owned()).is_ok());
13011301

13021302
unsafe {
13031303
let labels_ptr = mem::transmute::<&HashMap<VertexId, String>, &mut HashMap<VertexId, String>>(&self.labels);
@@ -1307,6 +1307,56 @@ impl<T> Graph<T>
13071307
self.labels.get(vertex_id).map(|s| s.clone())
13081308
}
13091309

1310+
#[cfg(feature = "dot")]
1311+
/// Maps each label that is placed on a vertex to a new label.
1312+
///
1313+
/// ```rust
1314+
/// use std::collections::HashMap;
1315+
/// use graphlib::{Graph, VertexId};
1316+
///
1317+
/// let mut graph: Graph<usize> = Graph::new();
1318+
/// let random_id = VertexId::random();
1319+
/// let mut vertex_id: usize = 1;
1320+
///
1321+
/// let v1 = graph.add_vertex(0);
1322+
/// let v2 = graph.add_vertex(1);
1323+
/// let v3 = graph.add_vertex(2);
1324+
///
1325+
/// assert!(graph.label_vertex(&v1, &format!("V{}", vertex_id)).is_ok());
1326+
/// vertex_id += 1;
1327+
///
1328+
/// assert!(graph.label_vertex(&v2, &format!("V{}", vertex_id)).is_ok());
1329+
/// vertex_id += 1;
1330+
///
1331+
/// assert!(graph.label_vertex(&v3, &format!("V{}", vertex_id)).is_ok());
1332+
///
1333+
/// assert_eq!(graph.label(&v1).unwrap(), "V1");
1334+
/// assert_eq!(graph.label(&v2).unwrap(), "V2");
1335+
/// assert_eq!(graph.label(&v3).unwrap(), "V3");
1336+
///
1337+
/// let new_labels: HashMap<VertexId, String> = vec![v1.clone(), v2.clone(), v3.clone()]
1338+
/// .iter()
1339+
/// .map(|id| {
1340+
/// vertex_id += 1;
1341+
/// let label = format!("V{}", vertex_id);
1342+
///
1343+
/// (id.clone(), label)
1344+
/// })
1345+
/// .collect();
1346+
///
1347+
/// graph.map_labels(|id, _old_label| new_labels.get(id).unwrap().clone());
1348+
///
1349+
/// assert_eq!(graph.label(&v1).unwrap(), "V4");
1350+
/// assert_eq!(graph.label(&v2).unwrap(), "V5");
1351+
/// assert_eq!(graph.label(&v3).unwrap(), "V6");
1352+
/// ```
1353+
pub fn map_labels(&mut self, mut fun: impl FnMut(&VertexId, &str) -> String) {
1354+
for (id, l) in self.labels.iter_mut() {
1355+
let new_label = fun(id, l);
1356+
*l = new_label;
1357+
}
1358+
}
1359+
13101360
fn do_add_edge(&mut self, a: &VertexId, b: &VertexId, weight: f32) -> Result<(), GraphErr> {
13111361
let id_ptr1 = if self.vertices.get(a).is_some() {
13121362
a.clone()

0 commit comments

Comments
 (0)