From d6b95c19f75e279e95a30aaef339a75a709ea604 Mon Sep 17 00:00:00 2001 From: Eric Rodrigues Pires Date: Sun, 19 Oct 2025 19:51:55 -0300 Subject: [PATCH] Add ipnet and regex support --- Cargo.lock | 66 +++++++++- README.md | 2 +- duper-py/python/duper/_duper.pyi | 4 +- duper/src/format.rs | 26 ++-- serde-duper/Cargo.toml | 4 + serde-duper/src/types/mod.rs | 160 ++++++++++++++++++++++++- serde-duper/tests/types_option_none.rs | 53 ++++++++ serde-duper/tests/types_option_some.rs | 61 ++++++++++ serde-duper/tests/types_plain.rs | 58 +++++++++ 9 files changed, 417 insertions(+), 17 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7a8b284..ed044b2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -28,6 +28,15 @@ dependencies = [ "version_check", ] +[[package]] +name = "aho-corasick" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" +dependencies = [ + "memchr", +] + [[package]] name = "android_system_properties" version = "0.1.5" @@ -257,7 +266,7 @@ dependencies = [ "encode_unicode", "libc", "once_cell", - "windows-sys", + "windows-sys 0.59.0", ] [[package]] @@ -337,7 +346,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -515,6 +524,15 @@ dependencies = [ "similar", ] +[[package]] +name = "ipnet" +version = "2.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130" +dependencies = [ + "serde", +] + [[package]] name = "is_ci" version = "1.2.0" @@ -874,6 +892,35 @@ dependencies = [ "getrandom", ] +[[package]] +name = "regex" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843bc0191f75f3e22651ae5f1e72939ab2f72a4bc30fa80a066bd66edefc24d4" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5276caf25ac86c8d810222b3dbb938e512c55c6831a10f3e6ed1c93b84041f1c" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58" + [[package]] name = "rend" version = "0.4.2" @@ -955,7 +1002,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -993,7 +1040,9 @@ dependencies = [ "bytes", "chrono", "duper", + "ipnet", "pest", + "regex", "rust_decimal", "serde", "serde-duper-macros", @@ -1152,7 +1201,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "45c6481c4829e4cc63825e62c49186a34538b7b2750b73b266581ffb612fb5ed" dependencies = [ "rustix", - "windows-sys", + "windows-sys 0.59.0", ] [[package]] @@ -1434,6 +1483,15 @@ dependencies = [ "windows-targets", ] +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + [[package]] name = "windows-targets" version = "0.52.6" diff --git a/README.md b/README.md index e90b1b1..fb8a1a7 100644 --- a/README.md +++ b/README.md @@ -97,7 +97,7 @@ We can get rid of the quotes for simple keys, use trailing commas, and include c } ``` -Duper also adds supports for tuples (`(-23.561384, -46.655891)`), bytes (`b"\x1b[1mDuper\x1b[0m"`), raw strings (`r#"I can use "quotes" in here!"#`), and raw bytes (`br#"/\ Check this out! #wombo_combo"#`). Also, integers are a separate type from floats. +Duper also adds supports for tuples (`(-23.561384, -46.655891)`), bytes (`b"\x1b[1mDuper\x1b[0m"`), raw strings (`r#"I can use "quotes" in here!"#`), and raw bytes (`br"/\ Check this out! #wombo_combo"`). Also, integers are a separate type from floats. --- diff --git a/duper-py/python/duper/_duper.pyi b/duper-py/python/duper/_duper.pyi index 44eeab1..a4f1d5e 100644 --- a/duper-py/python/duper/_duper.pyi +++ b/duper-py/python/duper/_duper.pyi @@ -11,7 +11,7 @@ __all__ = [ def dumps( obj: Any, *, - indent: int | None = None, + indent: str | int | None = None, strip_identifiers: bool = False, ) -> str: """Serialize obj as a Duper value formatted str.""" @@ -20,7 +20,7 @@ def dump( obj: Any, fp: TextIOBase, *, - indent: int | None = None, + indent: str | int | None = None, strip_identifiers: bool = False, ) -> None: """Serialize obj as a Duper value formatted stream to fp (a file-like object).""" diff --git a/duper/src/format.rs b/duper/src/format.rs index 3dfe41f..c05d29e 100644 --- a/duper/src/format.rs +++ b/duper/src/format.rs @@ -23,7 +23,7 @@ fn format_cow_str<'a>(string: &Cow<'a, str>) -> Cow<'a, str> { Cow::Borrowed(r#""""#) } else { // Check if it's benefic to turn into a raw string - let mut quotes = 0usize; + let mut chars_to_escape = 0usize; let mut was_quotes = false; let mut was_hashtag = false; let mut curr_hashtags = 0usize; @@ -34,7 +34,7 @@ fn format_cow_str<'a>(string: &Cow<'a, str>) -> Cow<'a, str> { '"' => { was_hashtag = false; was_quotes = true; - quotes += 1; + chars_to_escape += 1; } '#' if was_hashtag => { curr_hashtags += 1; @@ -50,6 +50,11 @@ fn format_cow_str<'a>(string: &Cow<'a, str>) -> Cow<'a, str> { was_hashtag = false; was_quotes = false; } + '\\' => { + was_hashtag = false; + was_quotes = false; + chars_to_escape += 1; + } char if char.is_control() || char.is_whitespace() || is_invisible_unicode(char) => { has_char_that_should_be_escaped = true; break; @@ -60,9 +65,9 @@ fn format_cow_str<'a>(string: &Cow<'a, str>) -> Cow<'a, str> { } } } - if quotes > max_hashtags && !has_char_that_should_be_escaped { + if chars_to_escape > max_hashtags && !has_char_that_should_be_escaped { // Raw string - let hashtags: String = (0..=max_hashtags).map(|_| '#').collect(); + let hashtags: String = (0..max_hashtags).map(|_| '#').collect(); Cow::Owned(format!(r#"r{}"{}"{}"#, hashtags, string, hashtags)) } else { // Regular string with escaping @@ -78,7 +83,7 @@ pub(crate) fn format_duper_bytes<'a>(bytes: &'a DuperBytes<'a>) -> Cow<'a, str> Cow::Borrowed(r#"b"""#) } else { // Check if it's benefic to turn into raw bytes - let mut quotes = 0usize; + let mut bytes_to_escape = 0usize; let mut was_quotes = false; let mut was_hashtag = false; let mut curr_hashtags = 0usize; @@ -89,7 +94,7 @@ pub(crate) fn format_duper_bytes<'a>(bytes: &'a DuperBytes<'a>) -> Cow<'a, str> b'"' => { was_hashtag = false; was_quotes = true; - quotes += 1; + bytes_to_escape += 1; } b'#' if was_hashtag => { curr_hashtags += 1; @@ -105,6 +110,11 @@ pub(crate) fn format_duper_bytes<'a>(bytes: &'a DuperBytes<'a>) -> Cow<'a, str> was_hashtag = false; was_quotes = false; } + b'\\' => { + was_hashtag = false; + was_quotes = false; + bytes_to_escape += 1; + } byte if byte.is_ascii_control() || byte.is_ascii_whitespace() => { has_char_that_should_be_escaped = true; break; @@ -115,9 +125,9 @@ pub(crate) fn format_duper_bytes<'a>(bytes: &'a DuperBytes<'a>) -> Cow<'a, str> } } } - if quotes > max_hashtags && !has_char_that_should_be_escaped { + if bytes_to_escape > max_hashtags && !has_char_that_should_be_escaped { // Raw bytes - let hashtags: String = (0..=max_hashtags).map(|_| '#').collect(); + let hashtags: String = (0..max_hashtags).map(|_| '#').collect(); let unesecaped_bytes: String = bytes.0.iter().copied().map(|b| b as char).collect(); Cow::Owned(format!( r#"br{}"{}"{}"#, diff --git a/serde-duper/Cargo.toml b/serde-duper/Cargo.toml index 6d113a6..09f6f19 100644 --- a/serde-duper/Cargo.toml +++ b/serde-duper/Cargo.toml @@ -16,6 +16,8 @@ macros = ["dep:serde-duper-macros"] bytes = ["dep:bytes"] chrono = ["dep:chrono"] decimal = ["dep:rust_decimal"] +ipnet = ["dep:ipnet"] +regex = ["dep:regex"] uuid = ["dep:uuid"] [dependencies] @@ -31,6 +33,8 @@ serde-duper-macros = { path = "../serde-duper-macros", optional = true } # Type dependencies bytes = { version = "1", features = ["serde"], optional = true } chrono = { version = "0.4", features = ["serde"], optional = true } +ipnet = { version = "2", features = ["serde"], optional = true } +regex = { version = "1", optional = true } rust_decimal = { version = "1", features = ["serde-str"], optional = true } uuid = { version = "1", features = ["serde"], optional = true } diff --git a/serde-duper/src/types/mod.rs b/serde-duper/src/types/mod.rs index eca980d..8af0081 100644 --- a/serde-duper/src/types/mod.rs +++ b/serde-duper/src/types/mod.rs @@ -25,7 +25,24 @@ macro_rules! duper_serde_module { where D: Deserializer<'de>, { - <$wrapped_type>::deserialize(deserializer) + struct Visitor; + + impl<'de> serde_core::de::Visitor<'de> for Visitor { + type Value = $wrapped_type; + + fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + formatter.write_str("a newtype struct") + } + + fn visit_newtype_struct(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + <$wrapped_type>::deserialize(deserializer) + } + } + + deserializer.deserialize_newtype_struct($type_name, Visitor) } } pub mod $option_mod_name { @@ -42,7 +59,24 @@ macro_rules! duper_serde_module { where D: Deserializer<'de>, { - >::deserialize(deserializer) + struct Visitor; + + impl<'de> serde_core::de::Visitor<'de> for Visitor { + type Value = Option<$wrapped_type>; + + fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + formatter.write_str("a newtype struct") + } + + fn visit_newtype_struct(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + >::deserialize(deserializer) + } + } + + deserializer.deserialize_newtype_struct($type_name, Visitor) } } }; @@ -69,6 +103,7 @@ macro_rules! duper_serde_module { D: Deserializer<'de>, $wrapped_type: Deserialize<'de>, { + // TODO: Use newtype struct deserialization <$wrapped_type>::deserialize(deserializer) } } @@ -88,6 +123,7 @@ macro_rules! duper_serde_module { D: Deserializer<'de>, Option<$wrapped_type>: Deserialize<'de>, { + // TODO: Use newtype struct deserialization >::deserialize(deserializer) } } @@ -501,5 +537,125 @@ pub mod DuperOptionDecimal { } } +#[cfg(feature = "ipnet")] +duper_serde_module!(DuperIpNet, DuperOptionIpNet, ::ipnet::IpNet, "IpNet"); +#[cfg(feature = "ipnet")] +duper_serde_module!( + DuperIpv4Net, + DuperOptionIpv4Net, + ::ipnet::Ipv4Net, + "Ipv4Net" +); +#[cfg(feature = "ipnet")] +duper_serde_module!( + DuperIpv6Net, + DuperOptionIpv6Net, + ::ipnet::Ipv6Net, + "Ipv6Net" +); + +#[cfg(feature = "regex")] +pub mod DuperRegex { + use super::*; + use ::regex::Regex as WrappedType; + + pub fn serialize(value: &WrappedType, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_newtype_struct("Regex", value.as_str()) + } + + pub fn deserialize<'de, D>(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct Visitor; + + impl<'de> serde_core::de::Visitor<'de> for Visitor { + type Value = WrappedType; + + fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + formatter.write_str("a Regex") + } + + fn visit_str(self, v: &str) -> Result + where + E: serde_core::de::Error, + { + WrappedType::new(v).map_err(|error| E::custom(error)) + } + + fn visit_newtype_struct(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_str(self) + } + } + + deserializer.deserialize_newtype_struct("Regex", Visitor) + } +} +pub mod DuperOptionRegex { + use super::*; + use ::regex::Regex as WrappedType; + + pub fn serialize(value: &Option, serializer: S) -> Result + where + S: Serializer, + { + match value { + Some(value) => serializer.serialize_newtype_struct("Regex", value.as_str()), + None => serializer.serialize_newtype_struct("Regex", &Option::<&str>::None), + } + } + + pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> + where + D: Deserializer<'de>, + { + struct Visitor; + + impl<'de> serde_core::de::Visitor<'de> for Visitor { + type Value = Option; + + fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + formatter.write_str("a Regex") + } + + fn visit_str(self, v: &str) -> Result + where + E: serde_core::de::Error, + { + Some(WrappedType::new(v).map_err(|error| E::custom(error))).transpose() + } + + fn visit_some(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_str(self) + } + + fn visit_none(self) -> Result + where + E: serde_core::de::Error, + { + Ok(None) + } + + fn visit_newtype_struct(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_option(self) + } + } + + deserializer.deserialize_newtype_struct("Regex", Visitor) + } +} + #[cfg(feature = "uuid")] duper_serde_module!(DuperUuid, DuperOptionUuid, ::uuid::Uuid, "Uuid"); diff --git a/serde-duper/tests/types_option_none.rs b/serde-duper/tests/types_option_none.rs index b83b553..0d41cd2 100644 --- a/serde-duper/tests/types_option_none.rs +++ b/serde-duper/tests/types_option_none.rs @@ -517,6 +517,59 @@ fn none_decimal() { assert!(deserialized.cost.is_none()); } +#[test] +#[cfg(feature = "ipnet")] +fn none_ipnet() { + use ipnet::{IpNet, Ipv4Net, Ipv6Net}; + use serde_duper::types::{DuperOptionIpNet, DuperOptionIpv4Net, DuperOptionIpv6Net}; + + #[derive(Debug, Serialize, Deserialize)] + struct Test { + #[serde(with = "DuperOptionIpNet")] + generic: Option, + #[serde(with = "DuperOptionIpv4Net")] + v4: Option, + #[serde(with = "DuperOptionIpv6Net")] + v6: Option, + } + + let value = Test { + generic: None, + v4: None, + v6: None, + }; + let serialized = serde_duper::to_string(&value).unwrap(); + assert_eq!( + serialized, + r#"Test({generic: IpNet(null), v4: Ipv4Net(null), v6: Ipv6Net(null)})"# + ); + + let deserialized: Test = serde_duper::from_string(&serialized).unwrap(); + assert!(deserialized.generic.is_none()); + assert!(deserialized.v4.is_none()); + assert!(deserialized.v6.is_none()); +} + +#[test] +#[cfg(feature = "regex")] +fn none_regex() { + use regex::Regex; + use serde_duper::types::DuperOptionRegex; + + #[derive(Debug, Serialize, Deserialize)] + struct Test { + #[serde(with = "DuperOptionRegex")] + pattern: Option, + } + + let value = Test { pattern: None }; + let serialized = serde_duper::to_string(&value).unwrap(); + assert_eq!(serialized, r##"Test({pattern: Regex(null)})"##); + + let deserialized: Test = serde_duper::from_string(&serialized).unwrap(); + assert!(deserialized.pattern.is_none()); +} + #[test] #[cfg(feature = "uuid")] fn none_uuid() { diff --git a/serde-duper/tests/types_option_some.rs b/serde-duper/tests/types_option_some.rs index bd99bb4..6dfd52e 100644 --- a/serde-duper/tests/types_option_some.rs +++ b/serde-duper/tests/types_option_some.rs @@ -686,6 +686,67 @@ fn some_decimal() { assert_eq!(value.cost, deserialized.cost); } +#[test] +#[cfg(feature = "ipnet")] +fn some_ipnet() { + use ipnet::{IpNet, Ipv4Net, Ipv6Net}; + use serde_duper::types::{DuperOptionIpNet, DuperOptionIpv4Net, DuperOptionIpv6Net}; + + #[derive(Debug, Serialize, Deserialize)] + struct Test { + #[serde(with = "DuperOptionIpNet")] + generic: Option, + #[serde(with = "DuperOptionIpv4Net")] + v4: Option, + #[serde(with = "DuperOptionIpv6Net")] + v6: Option, + } + + let value = Test { + generic: Some(IpNet::V4("192.168.0.0/24".parse().unwrap())), + v4: Some("10.15.0.0/16".parse().unwrap()), + v6: Some("2001:db8::/32".parse().unwrap()), + }; + let serialized = serde_duper::to_string(&value).unwrap(); + assert_eq!( + serialized, + r#"Test({generic: IpNet("192.168.0.0/24"), v4: Ipv4Net("10.15.0.0/16"), v6: Ipv6Net("2001:db8::/32")})"# + ); + + let deserialized: Test = serde_duper::from_string(&serialized).unwrap(); + assert_eq!(value.generic, deserialized.generic); + assert_eq!(value.v4, deserialized.v4); + assert_eq!(value.v6, deserialized.v6); +} + +#[test] +#[cfg(feature = "regex")] +fn some_regex() { + use regex::Regex; + use serde_duper::types::DuperOptionRegex; + + #[derive(Debug, Serialize, Deserialize)] + struct Test { + #[serde(with = "DuperOptionRegex")] + pattern: Option, + } + + let value = Test { + pattern: Some(Regex::new(r"Hello (?\w+)!").unwrap()), + }; + let serialized = serde_duper::to_string(&value).unwrap(); + assert_eq!( + serialized, + r##"Test({pattern: Regex(r"Hello (?\w+)!")})"## + ); + + let deserialized: Test = serde_duper::from_string(&serialized).unwrap(); + assert_eq!( + value.pattern.unwrap().as_str(), + deserialized.pattern.unwrap().as_str() + ); +} + #[test] #[cfg(feature = "uuid")] fn some_uuid() { diff --git a/serde-duper/tests/types_plain.rs b/serde-duper/tests/types_plain.rs index 0148574..5a8d046 100644 --- a/serde-duper/tests/types_plain.rs +++ b/serde-duper/tests/types_plain.rs @@ -606,6 +606,64 @@ fn decimal() { assert_eq!(value.cost, deserialized.cost); } +#[test] +#[cfg(feature = "ipnet")] +fn ipnet() { + use ipnet::{IpNet, Ipv4Net, Ipv6Net}; + use serde_duper::types::{DuperIpNet, DuperIpv4Net, DuperIpv6Net}; + + #[derive(Debug, Serialize, Deserialize)] + struct Test { + #[serde(with = "DuperIpNet")] + generic: IpNet, + #[serde(with = "DuperIpv4Net")] + v4: Ipv4Net, + #[serde(with = "DuperIpv6Net")] + v6: Ipv6Net, + } + + let value = Test { + generic: IpNet::V4("192.168.0.0/24".parse().unwrap()), + v4: "10.15.0.0/16".parse().unwrap(), + v6: "2001:db8::/32".parse().unwrap(), + }; + let serialized = serde_duper::to_string(&value).unwrap(); + assert_eq!( + serialized, + r#"Test({generic: IpNet("192.168.0.0/24"), v4: Ipv4Net("10.15.0.0/16"), v6: Ipv6Net("2001:db8::/32")})"# + ); + + let deserialized: Test = serde_duper::from_string(&serialized).unwrap(); + assert_eq!(value.generic, deserialized.generic); + assert_eq!(value.v4, deserialized.v4); + assert_eq!(value.v6, deserialized.v6); +} + +#[test] +#[cfg(feature = "regex")] +fn regex() { + use regex::Regex; + use serde_duper::types::DuperRegex; + + #[derive(Debug, Serialize, Deserialize)] + struct Test { + #[serde(with = "DuperRegex")] + pattern: Regex, + } + + let value = Test { + pattern: Regex::new(r"Hello (?\w+)!").unwrap(), + }; + let serialized = serde_duper::to_string(&value).unwrap(); + assert_eq!( + serialized, + r#"Test({pattern: Regex(r"Hello (?\w+)!")})"# + ); + + let deserialized: Test = serde_duper::from_string(&serialized).unwrap(); + assert_eq!(value.pattern.as_str(), deserialized.pattern.as_str()); +} + #[test] #[cfg(feature = "uuid")] fn uuid() { -- knotmirror 0.0.1