Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Serialize and Deserialize #46

Merged
merged 9 commits into from
Sep 29, 2023
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ edition = "2021"

[dependencies]
num-traits = "0.2"
serde = { version = "1.0.188", optional = true}

[dev-dependencies]
maplit = "1.0"
rand = "0.8.5"

serde_json = "1.0.107"
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ union, etc. are of course still supported.

[multiset]: https://en.wikipedia.org/wiki/Set_(abstract_data_type)#Multiset

## Cargo Features

- `serde` implements `serde::Serialize` and `serde::Deserialize` for `Counter`.

## Examples

### Just count an iterable
Expand Down
2 changes: 2 additions & 0 deletions src/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ mod from_iterator;
mod index;
mod intersection;
mod into_iterator;
#[cfg(feature = "serde")]
mod serialize;
coriolinus marked this conversation as resolved.
Show resolved Hide resolved
mod sub_iterable;
mod sub_self;
mod union;
32 changes: 32 additions & 0 deletions src/impls/serialize.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use crate::Counter;

use std::hash::Hash;
use num_traits::Zero;
use serde::{Serialize, Deserialize};
use serde::ser::Serializer;
use serde::de::Deserializer;


impl<T, N> Serialize for Counter<T, N>
where
T: Serialize + Hash + Eq,
N: Serialize,
{
fn serialize<S>(&self, serializer:S) -> Result<S::Ok, S::Error>
where S: Serializer {
self.map.serialize(serializer)
}
}

impl<'de, T, N> Deserialize<'de> for Counter<T, N>
where
T: Deserialize<'de> + Hash + Eq,
N: Deserialize<'de> + Zero,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de> {
let map = <_>::deserialize(deserializer)?;
let zero = N::zero();
Ok(Counter { map, zero })
}
}
9 changes: 9 additions & 0 deletions tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,4 +185,13 @@ mod tests {
a[&'e'] = -2;
assert!(a.is_subset(&b));
}

#[cfg(feature = "serde")]
#[test]
fn test_serialize_deserialize() {
coriolinus marked this conversation as resolved.
Show resolved Hide resolved
let a = "abbccc".chars().collect::<Counter<_>>();
let serialized = serde_json::to_string(&a).unwrap();
let b: Counter<char> = serde_json::from_str(&serialized).unwrap();
assert!(a == b)
}
}
Loading