mirror of
https://github.com/achanda/ipnetwork.git
synced 2025-06-18 01:38:51 +00:00
direct serialize/deserialize from string/to string
This commit is contained in:
25
src/ipv4.rs
25
src/ipv4.rs
@ -2,18 +2,41 @@ use std::fmt;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::str::FromStr;
|
||||
|
||||
#[cfg(feature = "with-serde")]
|
||||
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
|
||||
|
||||
use common::{cidr_parts, parse_addr, parse_prefix, IpNetworkError};
|
||||
|
||||
const IPV4_BITS: u8 = 32;
|
||||
|
||||
/// 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)]
|
||||
pub struct Ipv4Network {
|
||||
addr: Ipv4Addr,
|
||||
prefix: u8,
|
||||
}
|
||||
|
||||
#[cfg(feature = "with-serde")]
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "with-serde")]
|
||||
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 {
|
||||
/// 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`.
|
||||
|
Reference in New Issue
Block a user