Skip to content

Commit

Permalink
Add ser_as_str feature to serialize using serialize_str()
Browse files Browse the repository at this point in the history
Serializer may not support collect_str, as is the case with
serde_json_core crate.
  • Loading branch information
elrafoon committed Oct 11, 2023
1 parent 6155c21 commit cd940a0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,12 @@ default = ["std"]
std = []
# Implements "schemars::JsonSchema". Also implies "serde".
json = ["serde", "schemars"]
ser_as_str = ["heapless"]

[dependencies]
serde = { package = "serde", version = "1", features = ["derive"], optional = true, default-features=false }
schemars = { version = "0.8", optional = true }
heapless = { version = "*", optional = true }

[dev-dependencies]
serde_test = "1"
Expand Down
14 changes: 14 additions & 0 deletions src/ipnet_serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,13 @@ impl Serialize for Ipv4Net {
where S: Serializer
{
if serializer.is_human_readable() {
#[cfg(feature = "ser_as_str")]
{
let mut buf = heapless::String::<18>::new();
fmt::write(&mut buf, format_args!("{self}")).unwrap();
serializer.serialize_str(&buf)
}
#[cfg(not(feature = "ser_as_str"))]
serializer.collect_str(self)
} else {
let mut seq = serializer.serialize_tuple(5)?;
Expand Down Expand Up @@ -130,6 +137,13 @@ impl Serialize for Ipv6Net {
where S: Serializer
{
if serializer.is_human_readable() {
#[cfg(feature = "ser_as_str")]
{
let mut buf = heapless::String::<43>::new();
fmt::write(&mut buf, format_args!("{self}")).unwrap();
serializer.serialize_str(&buf)
}
#[cfg(not(feature = "ser_as_str"))]
serializer.collect_str(self)
} else {
let mut seq = serializer.serialize_tuple(17)?;
Expand Down

0 comments on commit cd940a0

Please sign in to comment.