Skip to content

Commit

Permalink
serialize (Node/Port)Index as 0-indexed (#64)
Browse files Browse the repository at this point in the history
* serialize NodeIndex as 0-indexed

Direct serialization stores the underlying NonZeroU32 which can be confusing

* serialize PortIndex as 0-indexed
  • Loading branch information
ss2165 authored Jun 12, 2023
1 parent 60d471b commit 6531ef2
Showing 1 changed file with 45 additions and 3 deletions.
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

0 comments on commit 6531ef2

Please sign in to comment.