Skip to content

Commit

Permalink
Allow serializing Map.
Browse files Browse the repository at this point in the history
  • Loading branch information
reitermarkus committed Nov 26, 2021
1 parent 815c17c commit b6c682e
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
1 change: 1 addition & 0 deletions phf/Cargo.toml
Expand Up @@ -27,6 +27,7 @@ macros = [
proc-macro-hack = { version = "0.5.4", optional = true }
phf_macros = { version = "0.10.0", optional = true }
phf_shared = { version = "0.10.0", default-features = false }
serde = { version = "1.0", optional = true }

[package.metadata.docs.rs]
features = ["macros"]
20 changes: 20 additions & 0 deletions phf/src/map.rs
Expand Up @@ -5,6 +5,8 @@ use core::iter::IntoIterator;
use core::ops::Index;
use core::slice;
use phf_shared::{self, HashKey, PhfBorrow, PhfHash};
#[cfg(feature = "serde")]
use serde::ser::{Serialize, SerializeMap, Serializer};

/// An immutable map constructed at compile time.
///
Expand Down Expand Up @@ -279,3 +281,21 @@ impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {}

impl<'a, K, V> FusedIterator for Values<'a, K, V> {}

#[cfg(feature = "serde")]
impl<K, V> Serialize for Map<K, V>
where
K: Serialize,
V: Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut map = serializer.serialize_map(Some(self.len()))?;
for (k, v) in self.entries() {
map.serialize_entry(k, v)?;
}
map.end()
}
}

0 comments on commit b6c682e

Please sign in to comment.