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

serialize NodeIndex as 0-indexed #64

Merged
merged 2 commits into from
Jun 12, 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
48 changes: 45 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ use thiserror::Error;
use pyo3::prelude::*;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

pub mod algorithms;
pub mod dot;
Expand Down Expand Up @@ -140,9 +140,30 @@ impl TryFrom<usize> for Direction {
/// as a `NodeIndex` by itself.
#[repr(transparent)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct NodeIndex(NonZeroU32);

#[cfg(feature = "serde")]
impl Serialize for NodeIndex {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.index().serialize(serializer)
}
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for NodeIndex {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
usize::deserialize(deserializer).map(NodeIndex::new)
}
}

impl NodeIndex {
/// Maximum allowed index. The higher bit is reserved for efficient encoding of the port graph.
const MAX: usize = (u32::MAX / 2) as usize - 1;
Expand Down Expand Up @@ -199,9 +220,30 @@ impl std::fmt::Debug for NodeIndex {
/// as a `PortIndex` by itself.
#[repr(transparent)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct PortIndex(NonZeroU32);

#[cfg(feature = "serde")]
impl Serialize for PortIndex {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.index().serialize(serializer)
}
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for PortIndex {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
usize::deserialize(deserializer).map(PortIndex::new)
}
}

impl PortIndex {
/// Maximum allowed index. The higher bit is reserved for efficient encoding of the port graph.
const MAX: usize = (u32::MAX / 2) as usize - 1;
Expand Down