Merge pull request #74 from sharksforarms/serde-issue-73

Serde serialize/deserialize
This commit is contained in:
Abhishek Chanda
2018-04-18 23:53:24 +02:00
committed by GitHub
8 changed files with 141 additions and 34 deletions

1
.gitignore vendored
View File

@ -2,3 +2,4 @@
Cargo.lock Cargo.lock
target target
.vscode .vscode
.idea/

View File

@ -11,7 +11,7 @@ env:
matrix: matrix:
include: include:
- rust: nightly - rust: nightly
env: FEATURES=ipv6-iterator,ipv6-methods,with-serde env: FEATURES=ipv6-iterator,ipv6-methods
script: script:
- cargo build --features $FEATURES --verbose - cargo build --features $FEATURES --verbose

View File

@ -12,8 +12,11 @@ categories = ["network-programming", "os"]
[dependencies] [dependencies]
clippy = {version = "0.0.104", optional = true} clippy = {version = "0.0.104", optional = true}
serde = { version = ">=0.8.0, <2.0", optional = true } serde = ">=0.8.0, <2.0"
serde_derive = { version = ">=0.8.0, <2.0", optional = true } serde_derive = ">=0.8.0, <2.0"
[dev-dependencies]
serde_json = "1.0"
[badges] [badges]
travis-ci = { repository = "achanda/ipnetwork" } travis-ci = { repository = "achanda/ipnetwork" }
@ -23,4 +26,3 @@ default = []
dev = ["clippy"] dev = ["clippy"]
ipv6-iterator = [] ipv6-iterator = []
ipv6-methods = [] ipv6-methods = []
with-serde = ["serde", "serde_derive"]

View File

@ -1,6 +1,6 @@
use std::net::Ipv4Addr;
use std::fmt;
use std::error::Error; use std::error::Error;
use std::fmt;
use std::net::Ipv4Addr;
/// Represents a bunch of errors that can occur while working with a `IpNetwork` /// Represents a bunch of errors that can occur while working with a `IpNetwork`
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]

View File

@ -2,18 +2,38 @@ use std::fmt;
use std::net::Ipv4Addr; use std::net::Ipv4Addr;
use std::str::FromStr; use std::str::FromStr;
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use common::{cidr_parts, parse_addr, parse_prefix, IpNetworkError}; use common::{cidr_parts, parse_addr, parse_prefix, IpNetworkError};
const IPV4_BITS: u8 = 32; const IPV4_BITS: u8 = 32;
/// Represents a network range where the IP addresses are of v4 /// Represents a network range where the IP addresses are of v4
#[cfg_attr(feature = "with-serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)] #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Ipv4Network { pub struct Ipv4Network {
addr: Ipv4Addr, addr: Ipv4Addr,
prefix: u8, prefix: u8,
} }
impl<'de> Deserialize<'de> for Ipv4Network {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = <&str>::deserialize(deserializer)?;
Ipv4Network::from_str(s).map_err(de::Error::custom)
}
}
impl Serialize for Ipv4Network {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.to_string())
}
}
impl Ipv4Network { impl Ipv4Network {
/// Constructs a new `Ipv4Network` from any `Ipv4Addr` and a prefix denoting the network size. /// Constructs a new `Ipv4Network` from any `Ipv4Addr` and a prefix denoting the network size.
/// If the prefix is larger than 32 this will return an `IpNetworkError::InvalidPrefix`. /// If the prefix is larger than 32 this will return an `IpNetworkError::InvalidPrefix`.
@ -21,10 +41,7 @@ impl Ipv4Network {
if prefix > IPV4_BITS { if prefix > IPV4_BITS {
Err(IpNetworkError::InvalidPrefix) Err(IpNetworkError::InvalidPrefix)
} else { } else {
Ok(Ipv4Network { Ok(Ipv4Network { addr, prefix })
addr: addr,
prefix: prefix,
})
} }
} }
@ -34,10 +51,7 @@ impl Ipv4Network {
pub fn iter(&self) -> Ipv4NetworkIterator { pub fn iter(&self) -> Ipv4NetworkIterator {
let start = u64::from(u32::from(self.network())); let start = u64::from(u32::from(self.network()));
let end = start + self.size(); let end = start + self.size();
Ipv4NetworkIterator { Ipv4NetworkIterator { next: start, end }
next: start,
end: end,
}
} }
pub fn ip(&self) -> Ipv4Addr { pub fn ip(&self) -> Ipv4Addr {
@ -234,7 +248,7 @@ pub fn ipv4_mask_to_prefix(mask: Ipv4Addr) -> Result<u8, IpNetworkError> {
let mask = u32::from(mask); let mask = u32::from(mask);
let prefix = (!mask).leading_zeros() as u8; let prefix = (!mask).leading_zeros() as u8;
if ((mask as u64) << prefix) & 0xffff_ffff != 0 { if (u64::from(mask) << prefix) & 0xffff_ffff != 0 {
Err(IpNetworkError::InvalidPrefix) Err(IpNetworkError::InvalidPrefix)
} else { } else {
Ok(prefix) Ok(prefix)
@ -243,10 +257,10 @@ pub fn ipv4_mask_to_prefix(mask: Ipv4Addr) -> Result<u8, IpNetworkError> {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use std::mem;
use std::collections::HashMap;
use std::net::Ipv4Addr;
use super::*; use super::*;
use std::collections::HashMap;
use std::mem;
use std::net::Ipv4Addr;
#[test] #[test]
fn create_v4() { fn create_v4() {

View File

@ -3,19 +3,39 @@ use std::fmt;
use std::net::Ipv6Addr; use std::net::Ipv6Addr;
use std::str::FromStr; use std::str::FromStr;
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use common::{cidr_parts, parse_prefix, IpNetworkError}; use common::{cidr_parts, parse_prefix, IpNetworkError};
const IPV6_BITS: u8 = 128; const IPV6_BITS: u8 = 128;
const IPV6_SEGMENT_BITS: u8 = 16; const IPV6_SEGMENT_BITS: u8 = 16;
/// Represents a network range where the IP addresses are of v6 /// Represents a network range where the IP addresses are of v6
#[cfg_attr(feature = "with-serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)] #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Ipv6Network { pub struct Ipv6Network {
addr: Ipv6Addr, addr: Ipv6Addr,
prefix: u8, prefix: u8,
} }
impl<'de> Deserialize<'de> for Ipv6Network {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = <&str>::deserialize(deserializer)?;
Ipv6Network::from_str(s).map_err(de::Error::custom)
}
}
impl Serialize for Ipv6Network {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.to_string())
}
}
impl Ipv6Network { impl Ipv6Network {
/// Constructs a new `Ipv6Network` from any `Ipv6Addr` and a prefix denoting the network size. /// Constructs a new `Ipv6Network` from any `Ipv6Addr` and a prefix denoting the network size.
/// If the prefix is larger than 128 this will return an `IpNetworkError::InvalidPrefix`. /// If the prefix is larger than 128 this will return an `IpNetworkError::InvalidPrefix`.
@ -23,10 +43,7 @@ impl Ipv6Network {
if prefix > IPV6_BITS { if prefix > IPV6_BITS {
Err(IpNetworkError::InvalidPrefix) Err(IpNetworkError::InvalidPrefix)
} else { } else {
Ok(Ipv6Network { Ok(Ipv6Network { addr, prefix })
addr: addr,
prefix: prefix,
})
} }
} }
@ -253,8 +270,8 @@ pub fn ipv6_mask_to_prefix(mask: Ipv6Addr) -> Result<u8, IpNetworkError> {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use std::net::Ipv6Addr;
use super::*; use super::*;
use std::net::Ipv6Addr;
#[test] #[test]
fn create_v6() { fn create_v6() {

View File

@ -8,29 +8,27 @@
#![crate_type = "lib"] #![crate_type = "lib"]
#![doc(html_root_url = "https://docs.rs/ipnetwork/0.12.8")] #![doc(html_root_url = "https://docs.rs/ipnetwork/0.12.8")]
#[cfg(feature = "with-serde")]
extern crate serde; extern crate serde;
#[cfg(feature = "with-serde")]
#[macro_use] #[macro_use]
extern crate serde_derive; extern crate serde_derive;
use std::fmt; use std::fmt;
use std::net::IpAddr; use std::net::IpAddr;
mod common;
mod ipv4; mod ipv4;
mod ipv6; mod ipv6;
mod common;
use std::str::FromStr; use std::str::FromStr;
pub use ipv4::{Ipv4Network, ipv4_mask_to_prefix};
pub use ipv6::{Ipv6Network, ipv6_mask_to_prefix};
pub use common::IpNetworkError; pub use common::IpNetworkError;
pub use ipv4::{ipv4_mask_to_prefix, Ipv4Network};
pub use ipv6::{ipv6_mask_to_prefix, Ipv6Network};
/// Represents a generic network range. This type can have two variants: /// Represents a generic network range. This type can have two variants:
/// the v4 and the v6 case. /// the v4 and the v6 case.
#[cfg_attr(feature = "with-serde", derive(Serialize, Deserialize))] #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)] #[serde(untagged)]
pub enum IpNetwork { pub enum IpNetwork {
V4(Ipv4Network), V4(Ipv4Network),
V6(Ipv6Network), V6(Ipv6Network),
@ -79,6 +77,7 @@ impl IpNetwork {
/// That means the `prefix` most significant bits will be 1 and the rest 0 /// That means the `prefix` most significant bits will be 1 and the rest 0
/// ///
/// # Example /// # Example
///
/// ``` /// ```
/// use ipnetwork::IpNetwork; /// use ipnetwork::IpNetwork;
/// use std::net::{Ipv4Addr, Ipv6Addr}; /// use std::net::{Ipv4Addr, Ipv6Addr};

74
tests/test_json.rs Normal file
View File

@ -0,0 +1,74 @@
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
extern crate ipnetwork;
#[cfg(test)]
mod tests {
use ipnetwork::{IpNetwork, Ipv4Network, Ipv6Network};
use std::net::{Ipv4Addr, Ipv6Addr};
#[test]
fn test_ipv4_json() {
let json_string = r#"{"ipnetwork":"127.1.0.0/24"}"#;
#[derive(Serialize, Deserialize)]
struct MyStruct {
ipnetwork: Ipv4Network,
}
let mystruct: MyStruct = ::serde_json::from_str(json_string).unwrap();
assert_eq!(mystruct.ipnetwork.ip(), Ipv4Addr::new(127, 1, 0, 0));
assert_eq!(mystruct.ipnetwork.prefix(), 24);
assert_eq!(::serde_json::to_string(&mystruct).unwrap(), json_string);
}
#[test]
fn test_ipv6_json() {
let json_string = r#"{"ipnetwork":"::1/0"}"#;
#[derive(Serialize, Deserialize)]
struct MyStruct {
ipnetwork: Ipv6Network,
}
let mystruct: MyStruct = ::serde_json::from_str(json_string).unwrap();
assert_eq!(
mystruct.ipnetwork.ip(),
Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)
);
assert_eq!(mystruct.ipnetwork.prefix(), 0);
assert_eq!(::serde_json::to_string(&mystruct).unwrap(), json_string);
}
#[test]
fn test_ipnetwork_json() {
let json_string = r#"{"ipnetwork":["127.1.0.0/24","::1/0"]}"#;
#[derive(Serialize, Deserialize)]
struct MyStruct {
ipnetwork: Vec<IpNetwork>,
}
let mystruct: MyStruct = ::serde_json::from_str(json_string).unwrap();
assert_eq!(mystruct.ipnetwork[0].ip(), Ipv4Addr::new(127, 1, 0, 0));
assert_eq!(mystruct.ipnetwork[0].prefix(), 24);
assert_eq!(
mystruct.ipnetwork[1].ip(),
Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)
);
assert_eq!(mystruct.ipnetwork[1].prefix(), 0);
assert_eq!(::serde_json::to_string(&mystruct).unwrap(), json_string);
}
}