Skip to content

Commit

Permalink
cidr: improve diagnostics for invalid cidr
Browse files Browse the repository at this point in the history
This is done in two parts:

1. Showing the list of bad cidrs and their corresponding error messages
2. Upgrading to a yet-to-be-released branch of the underlying cidr
   library that can provide a helpful suggestion of how to fix it

refs: stbuehler/rust-cidr#8
  • Loading branch information
wez committed Jun 20, 2024
1 parent 77f9830 commit 7eb5bdc
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 4 deletions.
3 changes: 1 addition & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion crates/cidr-map/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ lua = ["dep:config", "dep:mlua", "dep:mod-memoize"]
[dependencies]
anyhow = "1.0"
bitstring = "0.1"
cidr = {version="0.2", features=["serde", "bitstring"]}
cidr = {git="https://github.com/stbuehler/rust-cidr", branch="fix-8-improve-cidr-invalid-host-part", features=["serde", "bitstring"]}
config = {path="../config", optional=true}
mlua = {workspace=true, features=["vendored", "lua54", "async", "send", "serialize"], optional=true}
mod-memoize = {path="../mod-memoize", optional=true}
Expand Down
36 changes: 35 additions & 1 deletion crates/cidr-map/src/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize};
use std::net::IpAddr;

#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)]
#[serde(from = "Vec<AnyIpCidr>", into = "Vec<AnyIpCidr>")]
#[serde(try_from = "Vec<String>", into = "Vec<String>")]
pub struct CidrSet(CidrMap<()>);

impl CidrSet {
Expand Down Expand Up @@ -48,6 +48,40 @@ where
}
}

impl TryFrom<Vec<String>> for CidrSet {
type Error = String;

fn try_from(v: Vec<std::string::String>) -> Result<Self, String> {
let mut set = CidrMap::new();
let mut problems = vec![];
for entry in v {
match entry.parse() {
Ok(cidr) => {
set.insert(cidr, ());
}
Err(err) => {
problems.push(format!("{entry}: {err:#}"));
}
}
}
if problems.is_empty() {
Ok(Self(set))
} else {
Err(problems.join(", "))
}
}
}

impl Into<Vec<String>> for CidrSet {
fn into(self) -> Vec<String> {
let mut result = vec![];
for (key, _unit) in self.0.iter() {
result.push(key.to_string());
}
result
}
}

impl From<Vec<AnyIpCidr>> for CidrSet {
fn from(entries: Vec<AnyIpCidr>) -> Self {
entries.into_iter().collect()
Expand Down

0 comments on commit 7eb5bdc

Please sign in to comment.