Skip to content

Commit

Permalink
feat: port.as_directed to match on either direction (#647)
Browse files Browse the repository at this point in the history
This replaces boilerplate like
```rust
match port.direction() {
    Direction::Incoming => {
        let incoming = port.as_incoming().unwrap();
        ...
    }
    Direction::Outgoing => {
        let outgoing = port.as_outgoing().unwrap();
        ...
    }
}
```
with
```rust
match port.as_directed() {
    Left(incoming) => ...
    Right(outgoing) => ...
}
```

drive-by: Drop leftover `Port::try_new_outgoing`.
  • Loading branch information
aborgna-q authored Nov 7, 2023
1 parent ed2c48c commit d34cd5c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 19 deletions.
36 changes: 18 additions & 18 deletions src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
//!
//! These types are re-exported in the root of the crate.
pub use itertools::Either;

use derive_more::From;
use itertools::Either::{Left, Right};

#[cfg(feature = "pyo3")]
use pyo3::pyclass;
Expand Down Expand Up @@ -92,35 +95,32 @@ impl Port {
/// [HugrError::InvalidPortDirection]
#[inline]
pub fn as_incoming(&self) -> Result<IncomingPort, HugrError> {
match self.direction() {
Direction::Incoming => Ok(IncomingPort {
index: self.index() as u16,
}),
dir @ Direction::Outgoing => Err(HugrError::InvalidPortDirection(dir)),
}
self.as_directed()
.left()
.ok_or(HugrError::InvalidPortDirection(self.direction()))
}

/// Converts to an [OutgoingPort] if this port is one; else fails with
/// [HugrError::InvalidPortDirection]
#[inline]
pub fn as_outgoing(&self) -> Result<OutgoingPort, HugrError> {
self.as_directed()
.right()
.ok_or(HugrError::InvalidPortDirection(self.direction()))
}

/// Converts to either an [IncomingPort] or an [OutgoingPort], as appropriate.
#[inline]
pub fn as_directed(&self) -> Either<IncomingPort, OutgoingPort> {
match self.direction() {
Direction::Outgoing => Ok(OutgoingPort {
Direction::Incoming => Left(IncomingPort {
index: self.index() as u16,
}),
Direction::Outgoing => Right(OutgoingPort {
index: self.index() as u16,
}),
dir @ Direction::Incoming => Err(HugrError::InvalidPortDirection(dir)),
}
}
/// Creates a new outgoing port.
#[inline]
pub fn try_new_outgoing(port: impl TryInto<OutgoingPort>) -> Result<Self, HugrError> {
let Ok(port) = port.try_into() else {
return Err(HugrError::InvalidPortDirection(Direction::Incoming));
};
Ok(Self {
offset: portgraph::PortOffset::new_outgoing(port.index()),
})
}

/// Returns the direction of the port.
#[inline]
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

pub mod algorithm;
pub mod builder;
mod core;
pub mod core;
pub mod extension;
pub mod hugr;
pub mod macros;
Expand Down

0 comments on commit d34cd5c

Please sign in to comment.