Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an as_range method to NodePortOffsets #50

Merged
merged 1 commit into from
May 25, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 34 additions & 11 deletions src/portgraph/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ use std::{
ops::Range,
};

use crate::portgraph::{NodeEntry, PortEntry, PortGraph};
use crate::{
portgraph::{NodeEntry, PortEntry, PortGraph},
Direction,
};
use crate::{NodeIndex, PortIndex, PortOffset};

/// Iterator over the ports of a node.
Expand Down Expand Up @@ -130,18 +133,13 @@ impl<'a> Iterator for Ports<'a> {
type Item = PortIndex;

fn next(&mut self) -> Option<Self::Item> {
if self.len == 0 {
return None;
}

for (index, port_entry) in &mut self.iter {
if let PortEntry::Port(_) = port_entry {
self.iter.find_map(|(index, port_entry)| match port_entry {
PortEntry::Port(_) => {
self.len -= 1;
return Some(PortIndex::new(index));
Some(PortIndex::new(index))
}
}

None
_ => None,
})
}

fn count(self) -> usize {
Expand All @@ -153,6 +151,20 @@ impl<'a> Iterator for Ports<'a> {
}
}

impl<'a> DoubleEndedIterator for Ports<'a> {
fn next_back(&mut self) -> Option<Self::Item> {
while let Some((index, port_entry)) = self.iter.next_back() {
if let PortEntry::Port(_) = port_entry {
self.len -= 1;
return Some(PortIndex::new(index));
}
}
None
}
}

impl<'a> FusedIterator for Ports<'a> {}

/// Iterator over the port offsets of a node. See [`PortGraph::input_offsets`],
/// [`PortGraph::output_offsets`], and [`PortGraph::all_port_offsets`].
#[derive(Clone)]
Expand All @@ -162,6 +174,17 @@ pub struct NodePortOffsets {
pub(super) outgoing: Range<u32>,
}

impl NodePortOffsets {
/// Return the leftover ports in the iterator as a range of integer indexes.
#[inline]
pub fn as_range(&self, dir: Direction) -> Range<usize> {
match dir {
Direction::Incoming => self.incoming.start as usize..self.incoming.end as usize,
Direction::Outgoing => self.outgoing.start as usize..self.outgoing.end as usize,
}
}
}

impl Iterator for NodePortOffsets {
type Item = PortOffset;

Expand Down