Skip to content

Commit

Permalink
Merge pull request #46 from matthewmcintire-savantx/master
Browse files Browse the repository at this point in the history
Implement Serialize and Deserialize
  • Loading branch information
coriolinus authored Sep 29, 2023
2 parents 1d41465 + ec3c4e0 commit 5cb4da6
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 1 deletion.
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;
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() {
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)
}
}

0 comments on commit 5cb4da6

Please sign in to comment.