Skip to content

Instantly share code, notes, and snippets.

@RReverser
Last active January 25, 2018 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RReverser/7f4caf4d6aeef3713d05bfad2e3c012e to your computer and use it in GitHub Desktop.
Save RReverser/7f4caf4d6aeef3713d05bfad2e3c012e to your computer and use it in GitHub Desktop.
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