Skip to content

Commit

Permalink
Add Human readable Serializers
Browse files Browse the repository at this point in the history
  • Loading branch information
density215 committed Dec 20, 2023
1 parent 4397eed commit 0022cf8
Show file tree
Hide file tree
Showing 3 changed files with 477 additions and 2 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,4 @@ default = ["octseq"]
bgp = ["bytes", "log", "octseq", "const-str"]
bmp = ["bgp", "bytes", "chrono", "log", "octseq"]
std = []
human_serde = []
47 changes: 46 additions & 1 deletion src/bgp/aspath.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ use std::{error, fmt};

use crate::asn::{Asn, LargeAsnError};

#[cfg(feature = "human_serde")]
use serde::ser::SerializeSeq;

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

use octseq::builder::{infallible, EmptyBuilder, FromBuilder, OctetsBuilder};
use octseq::octets::{Octets, OctetsFrom, OctetsInto};
use octseq::parse::Parser;
Expand All @@ -23,6 +29,16 @@ use crate::util::parser::ParseError;

pub type OwnedHop = Hop<Vec<u8>>;

#[cfg(feature = "human_serde")]
pub trait SerializeForOperators: Serialize {
fn serialize_for_operator<S>(
&self,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer;
}

//------------ HopPath -------------------------------------------------------

/// Represents an AS PATH as a vec of actual network hops.
Expand All @@ -43,7 +59,6 @@ pub type OwnedHop = Hop<Vec<u8>>;
/// ```Hop(AS10), Hop(AS20), Hop(AS30), Hop(Set(AS40, AS50))```
///
#[derive(Clone, Debug, Default, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct HopPath {
/// The hops in this HopPath.
hops: Vec<OwnedHop>,
Expand Down Expand Up @@ -405,6 +420,36 @@ impl fmt::Display for HopPath {
}
}

#[cfg(feature = "human_serde")]
impl Serialize for HopPath {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if serializer.is_human_readable() {
self.serialize_for_operator(serializer)
} else {
self.serialize(serializer)
}
}
}

#[cfg(feature = "human_serde")]
impl SerializeForOperators for HopPath {
fn serialize_for_operator<S>(
&self,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(Some(self.hop_count()))?;
for hop in self.iter() {
seq.serialize_element(&format!("{}", hop))?;
}
seq.end()
}
}

//----------- AsPath ---------------------------------------------------------

Expand Down
Loading

0 comments on commit 0022cf8

Please sign in to comment.