Skip to content

Commit ab6f101

Browse files
authored
Correct and validate JsonSchema for Ipv4Network, Ipv6Network, and IpNetwork (#157)
* show failed test cases * add proper JSON schema
1 parent 5146125 commit ab6f101

6 files changed

Lines changed: 164 additions & 11 deletions

File tree

.github/workflows/rust.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,6 @@ jobs:
2323
- name: Build
2424
run: cargo build --verbose
2525
- name: Run tests
26-
run: cargo test --verbose
26+
run: cargo test --verbose --all-features
2727
- name: Build docs
2828
run: cargo doc --verbose

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@ schemars = { version = "0.8.10", optional = true }
1616

1717
[dev-dependencies]
1818
serde_json = "1.0"
19-
serde_derive = "1"
2019
criterion = {version = "0.3.4", features= ["html_reports"]}
20+
does-it-json = "0.0.3"
2121

2222
[badges]
2323
travis-ci = { repository = "achanda/ipnetwork" }

src/ipv4.rs

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
use crate::common::{cidr_parts, parse_prefix, IpNetworkError};
2-
use std::{fmt, net::Ipv4Addr, str::FromStr, convert::TryFrom};
2+
use std::{convert::TryFrom, fmt, net::Ipv4Addr, str::FromStr};
33

44
const IPV4_BITS: u8 = 32;
55

66
/// Represents a network range where the IP addresses are of v4
77
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
8-
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
98
pub struct Ipv4Network {
109
addr: Ipv4Addr,
1110
prefix: u8,
@@ -32,6 +31,36 @@ impl serde::Serialize for Ipv4Network {
3231
}
3332
}
3433

34+
#[cfg(feature = "schemars")]
35+
impl schemars::JsonSchema for Ipv4Network {
36+
fn schema_name() -> String {
37+
"Ipv4Network".to_string()
38+
}
39+
40+
fn json_schema(_: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
41+
schemars::schema::SchemaObject {
42+
instance_type: Some(schemars::schema::InstanceType::String.into()),
43+
string: Some(Box::new(schemars::schema::StringValidation {
44+
pattern: Some(
45+
concat!(
46+
r#"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}"#,
47+
r#"(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"#,
48+
r#"\/(3[0-2]|[0-2]?[0-9])$"#,
49+
)
50+
.to_string(),
51+
),
52+
..Default::default()
53+
})),
54+
extensions: [("x-rust-type".to_string(), "ipnetwork::Ipv4Network".into())]
55+
.iter()
56+
.cloned()
57+
.collect(),
58+
..Default::default()
59+
}
60+
.into()
61+
}
62+
}
63+
3564
impl Ipv4Network {
3665
/// Constructs a new `Ipv4Network` from any `Ipv4Addr` and a prefix denoting the network size.
3766
///

src/ipv6.rs

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
use crate::common::{cidr_parts, parse_prefix, IpNetworkError};
2-
use std::{cmp, fmt, net::Ipv6Addr, str::FromStr, convert::TryFrom};
2+
use std::{cmp, convert::TryFrom, fmt, net::Ipv6Addr, str::FromStr};
33

44
const IPV6_BITS: u8 = 128;
55
const IPV6_SEGMENT_BITS: u8 = 16;
66

77
/// Represents a network range where the IP addresses are of v6
88
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
9-
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
109
pub struct Ipv6Network {
1110
addr: Ipv6Addr,
1211
prefix: u8,
@@ -33,6 +32,46 @@ impl serde::Serialize for Ipv6Network {
3332
}
3433
}
3534

35+
#[cfg(feature = "schemars")]
36+
impl schemars::JsonSchema for Ipv6Network {
37+
fn schema_name() -> String {
38+
"Ipv6Network".to_string()
39+
}
40+
41+
fn json_schema(_: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
42+
schemars::schema::SchemaObject {
43+
instance_type: Some(schemars::schema::InstanceType::String.into()),
44+
string: Some(Box::new(schemars::schema::StringValidation {
45+
pattern: Some(
46+
concat!(
47+
r#"^("#,
48+
r#"([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}"#,
49+
r#"|([0-9a-fA-F]{1,4}:){1,7}:"#,
50+
r#"|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}"#,
51+
r#"|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}"#,
52+
r#"|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}"#,
53+
r#"|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}"#,
54+
r#"|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}"#,
55+
r#"|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})"#,
56+
r#"|:((:[0-9a-fA-F]{1,4}){1,7}|:)"#,
57+
r#"|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}"#,
58+
r#"|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])"#,
59+
r#"|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])"#,
60+
r#"")[/](12[0-8]|1[0-1][0-9]|[0-9]?[0-9])$"#,
61+
).to_string(),
62+
),
63+
..Default::default()
64+
})),
65+
extensions: [("x-rust-type".to_string(), "ipnetwork::Ipv6Network".into())]
66+
.iter()
67+
.cloned()
68+
.collect(),
69+
..Default::default()
70+
}
71+
.into()
72+
}
73+
}
74+
3675
impl Ipv6Network {
3776
/// Constructs a new `Ipv6Network` from any `Ipv6Addr` and a prefix denoting the network size.
3877
///

src/lib.rs

Lines changed: 71 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
//! The `ipnetwork` crate provides a set of APIs to work with IP CIDRs in
22
//! Rust.
33
#![crate_type = "lib"]
4-
54
#![deny(
65
missing_debug_implementations,
76
unsafe_code,
87
unused_extern_crates,
9-
unused_import_braces)]
8+
unused_import_braces
9+
)]
1010

11-
use std::{fmt, net::IpAddr, str::FromStr, convert::TryFrom};
11+
use std::{convert::TryFrom, fmt, net::IpAddr, str::FromStr};
1212

1313
mod common;
1414
mod ipv4;
@@ -23,7 +23,6 @@ pub use crate::ipv6::{ipv6_mask_to_prefix, Ipv6Network};
2323
/// Represents a generic network range. This type can have two variants:
2424
/// the v4 and the v6 case.
2525
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
26-
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2726
pub enum IpNetwork {
2827
V4(Ipv4Network),
2928
V6(Ipv6Network),
@@ -50,6 +49,74 @@ impl serde::Serialize for IpNetwork {
5049
}
5150
}
5251

52+
#[cfg(feature = "schemars")]
53+
impl schemars::JsonSchema for IpNetwork {
54+
fn schema_name() -> String {
55+
"IpNetwork".to_string()
56+
}
57+
58+
fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
59+
schemars::schema::SchemaObject {
60+
metadata: Some(
61+
schemars::schema::Metadata {
62+
..Default::default()
63+
}
64+
.into(),
65+
),
66+
subschemas: Some(
67+
schemars::schema::SubschemaValidation {
68+
one_of: Some(vec![
69+
schemars::schema::SchemaObject {
70+
metadata: Some(
71+
schemars::schema::Metadata {
72+
title: Some("v4".to_string()),
73+
..Default::default()
74+
}
75+
.into(),
76+
),
77+
subschemas: Some(
78+
schemars::schema::SubschemaValidation {
79+
all_of: Some(vec![gen.subschema_for::<Ipv4Network>()]),
80+
..Default::default()
81+
}
82+
.into(),
83+
),
84+
..Default::default()
85+
}
86+
.into(),
87+
schemars::schema::SchemaObject {
88+
metadata: Some(
89+
schemars::schema::Metadata {
90+
title: Some("v6".to_string()),
91+
..Default::default()
92+
}
93+
.into(),
94+
),
95+
subschemas: Some(
96+
schemars::schema::SubschemaValidation {
97+
all_of: Some(vec![gen.subschema_for::<Ipv6Network>()]),
98+
..Default::default()
99+
}
100+
.into(),
101+
),
102+
..Default::default()
103+
}
104+
.into(),
105+
]),
106+
..Default::default()
107+
}
108+
.into(),
109+
),
110+
extensions: [("x-rust-type".to_string(), "ipnetwork::IpNetwork".into())]
111+
.iter()
112+
.cloned()
113+
.collect(),
114+
..Default::default()
115+
}
116+
.into()
117+
}
118+
}
119+
53120
/// Represents a generic network size. For IPv4, the max size is a u32 and for IPv6, it is a u128
54121
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
55122
pub enum NetworkSize {

tests/test_json.rs

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,15 @@
33
#[cfg(test)]
44
mod tests {
55
use ipnetwork::{IpNetwork, Ipv4Network, Ipv6Network};
6-
use serde_derive::{Deserialize, Serialize};
6+
use serde::{Deserialize, Serialize};
77
use std::net::{Ipv4Addr, Ipv6Addr};
88

99
#[test]
1010
fn test_ipv4_json() {
1111
let json_string = r#"{"ipnetwork":"127.1.0.0/24"}"#;
1212

1313
#[derive(Serialize, Deserialize)]
14+
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1415
struct MyStruct {
1516
ipnetwork: Ipv4Network,
1617
}
@@ -21,13 +22,19 @@ mod tests {
2122
assert_eq!(mystruct.ipnetwork.prefix(), 24);
2223

2324
assert_eq!(::serde_json::to_string(&mystruct).unwrap(), json_string);
25+
26+
#[cfg(feature = "schemars")]
27+
if let Err(s) = does_it_json::validate_with_output(&mystruct) {
28+
panic!("{}", s);
29+
}
2430
}
2531

2632
#[test]
2733
fn test_ipv6_json() {
2834
let json_string = r#"{"ipnetwork":"::1/0"}"#;
2935

3036
#[derive(Serialize, Deserialize)]
37+
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3138
struct MyStruct {
3239
ipnetwork: Ipv6Network,
3340
}
@@ -41,13 +48,19 @@ mod tests {
4148
assert_eq!(mystruct.ipnetwork.prefix(), 0);
4249

4350
assert_eq!(::serde_json::to_string(&mystruct).unwrap(), json_string);
51+
52+
#[cfg(feature = "schemars")]
53+
if let Err(s) = does_it_json::validate_with_output(&mystruct) {
54+
panic!("{}", s);
55+
}
4456
}
4557

4658
#[test]
4759
fn test_ipnetwork_json() {
4860
let json_string = r#"{"ipnetwork":["127.1.0.0/24","::1/0"]}"#;
4961

5062
#[derive(Serialize, Deserialize)]
63+
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5164
struct MyStruct {
5265
ipnetwork: Vec<IpNetwork>,
5366
}
@@ -63,5 +76,10 @@ mod tests {
6376
assert_eq!(mystruct.ipnetwork[1].prefix(), 0);
6477

6578
assert_eq!(::serde_json::to_string(&mystruct).unwrap(), json_string);
79+
80+
#[cfg(feature = "schemars")]
81+
if let Err(s) = does_it_json::validate_with_output(&mystruct) {
82+
panic!("{}", s);
83+
}
6684
}
6785
}

0 commit comments

Comments
 (0)