From b6c682e81ea537b967ba055a0e464d24f5ea795c Mon Sep 17 00:00:00 2001 From: Markus Reiter Date: Fri, 26 Nov 2021 15:47:22 +0100 Subject: [PATCH] Allow serializing `Map`. --- phf/Cargo.toml | 1 + phf/src/map.rs | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/phf/Cargo.toml b/phf/Cargo.toml index 5c394543..4c2c4a39 100644 --- a/phf/Cargo.toml +++ b/phf/Cargo.toml @@ -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"] diff --git a/phf/src/map.rs b/phf/src/map.rs index 4d558359..5b74445c 100644 --- a/phf/src/map.rs +++ b/phf/src/map.rs @@ -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. /// @@ -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 Serialize for Map +where + K: Serialize, + V: Serialize, +{ + fn serialize(&self, serializer: S) -> Result + 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() + } +}