src/cube.rs

changeset 34
aa6129697116
parent 30
4fc8c93ed7e8
child 37
d7cd14b8ccc0
--- a/src/cube.rs	Thu Nov 07 13:51:16 2024 -0500
+++ b/src/cube.rs	Thu Nov 07 16:52:05 2024 -0500
@@ -26,28 +26,44 @@
 
 /// An iterator over paths on a cube, from a source face to a destination face.
 #[derive(Clone, Debug)]
-pub struct PathIter {
-    destination : Face,
-    intermediate : AdjacentFaces,
-    current : usize
+pub enum PathIter {
+    Same {
+        destination : Face,
+        exhausted : bool
+    },
+    Indirect {
+        destination : Face,
+        intermediate : AdjacentFaces,
+        current : usize
+    }
 }
 
 impl std::iter::Iterator for PathIter {
     type Item = Path;
     
     fn next(&mut self) -> Option<Self::Item> {
-        let PathIter { destination, intermediate : ref i, ref mut current } = *self;
-        while *current < i.len() {
-            let intermediate = i[*current];
-            *current += 1;
-            if intermediate == destination {
-                return Some(Path::Direct { destination })
-            } else if intermediate != destination.opposing_face() {
-                return Some(Path::Indirect{ destination, intermediate })
+        match *self {
+            PathIter::Same { destination, ref mut exhausted } => {
+                if !*exhausted {
+                    *exhausted = true;
+                    return Some(Path::Direct { destination })
+                }
+                None
+            },
+            PathIter::Indirect { destination, intermediate : ref i, ref mut current } => {
+                while *current < i.len() {
+                    let intermediate = i[*current];
+                    *current += 1;
+                    if intermediate == destination {
+                        return Some(Path::Direct { destination })
+                    } else if intermediate != destination.opposing_face() {
+                        return Some(Path::Indirect{ destination, intermediate })
+                    }
+                    // Paths should never go through a face opposing the destination.
+                }
+                None
             }
-            // Paths should never go through a face opposing the destination.
         }
-        None
     }
 }
 
@@ -166,10 +182,17 @@
 
     /// Returns an iterator over all the paths from `self` to `other`.
     fn paths(&self, other : Face) -> PathIter {
-        PathIter {
-            intermediate : self.adjacent_faces(),
-            destination : other,
-            current : 0
+        if other == *self {
+            PathIter::Same {
+                destination : other,
+                exhausted : false
+            }
+        } else {
+            PathIter::Indirect {
+                intermediate : self.adjacent_faces(),
+                destination : other,
+                current : 0
+            }
         }
     }
 

mercurial