Skip to content

Commit 35442f2

Browse files
committed
Correctly return None for label for invalid edge/vertex and default to empty string when no label has been set
1 parent da4bd2f commit 35442f2

2 files changed

Lines changed: 20 additions & 12 deletions

File tree

src/dot.rs

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -48,17 +48,13 @@ impl<'a, T> dot::Labeller<'a, Nd, Ed<'a>> for DotGraph<'a, T> {
4848
}
4949

5050
fn node_label<'b>(&'b self, n: &Nd) -> dot::LabelText<'b> {
51-
let label = self.graph.vertex_label(n)
52-
.cloned()
53-
.unwrap_or_else(|| String::new());
54-
dot::LabelText::label(Cow::Owned(label))
51+
let label = self.graph.vertex_label(n).unwrap();
52+
dot::LabelText::label(Cow::Borrowed(label))
5553
}
5654

5755
fn edge_label<'b>(&'b self, e: &Ed) -> dot::LabelText<'b> {
58-
let label = self.graph.edge_label(e.0, e.1)
59-
.cloned()
60-
.unwrap_or_else(|| String::new());
61-
dot::LabelText::LabelStr(Cow::Owned(label))
56+
let label = self.graph.edge_label(e.0, e.1).unwrap();
57+
dot::LabelText::LabelStr(Cow::Borrowed(label))
6258
}
6359
}
6460

src/graph.rs

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,6 @@ use std::fmt::Debug;
1717

1818
#[cfg(feature = "no_std")]
1919
use core::mem;
20-
#[cfg(not(feature = "no_std"))]
21-
use std::mem;
2220

2321
#[cfg(feature = "no_std")]
2422
extern crate alloc;
@@ -91,6 +89,8 @@ pub struct Graph<T> {
9189
edge_labels: HashMap<Edge, String>,
9290
}
9391

92+
const DEFAULT_LABEL: &str = "";
93+
9494
impl<T> Graph<T> {
9595
/// Creates a new graph.
9696
///
@@ -1437,8 +1437,14 @@ impl<T> Graph<T> {
14371437
/// This method requires the `dot` crate feature.
14381438
///
14391439
/// Returns `None` if there is no vertex associated with the given id in the graph.
1440-
pub fn vertex_label(&self, vertex_id: &VertexId) -> Option<&String> {
1440+
pub fn vertex_label(&self, vertex_id: &VertexId) -> Option<&str> {
1441+
if !self.vertices.contains_key(vertex_id) {
1442+
return None;
1443+
}
1444+
14411445
self.vertex_labels.get(vertex_id)
1446+
.map(|x| x.as_str())
1447+
.or(Some(&DEFAULT_LABEL))
14421448
}
14431449

14441450
#[cfg(feature = "dot")]
@@ -1447,8 +1453,14 @@ impl<T> Graph<T> {
14471453
/// This method requires the `dot` crate feature.
14481454
///
14491455
/// Returns `None` if there is no edge associated with the given vertices in the graph.
1450-
pub fn edge_label(&self, a: &VertexId, b: &VertexId) -> Option<&String> {
1456+
pub fn edge_label(&self, a: &VertexId, b: &VertexId) -> Option<&str> {
1457+
if !self.has_edge(a, b) {
1458+
return None;
1459+
}
1460+
14511461
self.edge_labels.get(&Edge::new(*a, *b))
1462+
.map(|x| x.as_str())
1463+
.or(Some(&DEFAULT_LABEL))
14521464
}
14531465

14541466
#[cfg(feature = "dot")]

0 commit comments

Comments
 (0)