Skip to content

Instantly share code, notes, and snippets.

@RReverser RReverser/cidr-repr.rs
Last active Jan 25, 2018

Embed
What would you like to do?
extern crate bincode;
extern crate cidr;
extern crate hex_slice;
extern crate rmp_serde;
extern crate serde;
extern crate serde_bytes;
extern crate serde_cbor;
#[macro_use]
extern crate serde_derive;
use cidr::{Cidr, IpCidr, Ipv4Cidr};
use std::net::Ipv4Addr;
use serde::{Serialize, Serializer};
use std::borrow::Cow;
use hex_slice::AsHex;
pub struct CidrWrapper(::cidr::IpCidr);
#[derive(Serialize)]
struct IpCidrRepr<'a>(
#[serde(borrow)]
#[serde(with = "::serde_bytes")]
Cow<'a, [u8]>,
u8,
);
impl Serialize for CidrWrapper {
fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
match self.0 {
::cidr::IpCidr::V4(ref cidr) => IpCidrRepr(
Cow::Borrowed(&cidr.first_address().octets()),
cidr.network_length(),
).serialize(ser),
::cidr::IpCidr::V6(ref cidr) => IpCidrRepr(
Cow::Borrowed(&cidr.first_address().octets()),
cidr.network_length(),
).serialize(ser),
}
}
}
fn main() {
let cidr = IpCidr::V4(Ipv4Cidr::new(Ipv4Addr::new(192, 168, 100, 0), 24).unwrap());
let wrapped = CidrWrapper(cidr.clone());
println!("bincode");
println!(
" Current implementation: {:02X}",
bincode::serialize(&cidr, bincode::Infinite)
.unwrap()
.as_hex()
);
println!(
" Length-based implementation: {:02X}",
bincode::serialize(&wrapped, bincode::Infinite)
.unwrap()
.as_hex()
);
println!("cbor");
println!(
" Current implementation: {:02X}",
serde_cbor::to_vec(&cidr).unwrap().as_hex()
);
println!(
" Length-based implementation: {:02X}",
serde_cbor::to_vec(&wrapped).unwrap().as_hex()
);
println!("MessagePack");
println!(
" Current implementation: {:02X}",
rmp_serde::to_vec(&cidr).unwrap().as_hex()
);
println!(
" Length-based implementation: {:02X}",
rmp_serde::to_vec(&wrapped).unwrap().as_hex()
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.