From 727f7bdc1295ea9111fbcd285a10be8b3854eacf Mon Sep 17 00:00:00 2001 From: Conrad Meyer Date: Thu, 9 Dec 2021 10:51:58 -0800 Subject: [PATCH 1/2] Fix #56 - Don't consume self in Dijkstra::get_path_to We only consume `self` for `iterator: VecDequeue`, which is unused outside of this routine and might as well be a local variable. --- src/iterators/dijkstra.rs | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/src/iterators/dijkstra.rs b/src/iterators/dijkstra.rs index cf9166f..0bae8b5 100644 --- a/src/iterators/dijkstra.rs +++ b/src/iterators/dijkstra.rs @@ -52,7 +52,6 @@ impl Ord for VertexMeta { pub struct Dijkstra<'a, T> { source: &'a VertexId, iterable: &'a Graph, - iterator: VecDeque, distances: HashMap, previous: HashMap>, } @@ -74,7 +73,6 @@ impl<'a, T> Dijkstra<'a, T> { let mut instance = Dijkstra { source: src, iterable: graph, - iterator: VecDeque::with_capacity(graph.vertex_count()), distances: HashMap::with_capacity(graph.vertex_count()), previous: HashMap::with_capacity(graph.vertex_count()), }; @@ -97,25 +95,25 @@ impl<'a, T> Dijkstra<'a, T> { Ok(()) } - pub fn get_path_to(mut self, vert: &'a VertexId) -> Result { + pub fn get_path_to(&self, vert: &'a VertexId) -> Result, GraphErr> { if self.iterable.fetch(vert).is_none() { return Err(GraphErr::NoSuchVertex); } if self.previous.contains_key(vert) { let mut cur_vert = Some(vert); - self.iterator.clear(); + let mut iterator = VecDeque::new(); - while cur_vert.is_some() { - self.iterator.push_front(*cur_vert.unwrap()); + while let Some(cur_vert_inner) = cur_vert { + iterator.push_front(*cur_vert_inner); - match self.previous.get(cur_vert.unwrap()) { + match self.previous.get(cur_vert_inner) { Some(v) => cur_vert = v.as_ref(), None => cur_vert = None, } } - return Ok(VertexIter(Box::new(OwningIterator::new(self.iterator)))); + return Ok(VertexIter(Box::new(OwningIterator::new(iterator)))); } Ok(VertexIter(Box::new(iter::empty()))) From de406aba7017d9041d15708c009f99719f25fdf3 Mon Sep 17 00:00:00 2001 From: Conrad Meyer Date: Thu, 9 Dec 2021 10:55:53 -0800 Subject: [PATCH 2/2] Fix #56 - Drop unneeded mut from Dijkstra::get_distance While here, drop an unnecessary bare `Option::unwrap()`. --- src/iterators/dijkstra.rs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/iterators/dijkstra.rs b/src/iterators/dijkstra.rs index 0bae8b5..ef69b37 100644 --- a/src/iterators/dijkstra.rs +++ b/src/iterators/dijkstra.rs @@ -119,16 +119,12 @@ impl<'a, T> Dijkstra<'a, T> { Ok(VertexIter(Box::new(iter::empty()))) } - pub fn get_distance(&mut self, vert: &'a VertexId) -> Result { + pub fn get_distance(&self, vert: &'a VertexId) -> Result { if self.iterable.fetch(vert).is_none() { return Err(GraphErr::NoSuchVertex); } - if self.distances.contains_key(vert) { - return Ok(*self.distances.get(vert).unwrap()); - } - - Ok(f32::MAX) + Ok(self.distances.get(vert).copied().unwrap_or(f32::MAX)) } fn calc_distances(&mut self) {