Skip to content

Instantly share code, notes, and snippets.

@therustmonk
Created March 11, 2021 07:18
Show Gist options
  • Save therustmonk/7bd337bdd895f841e6a60af9019024f8 to your computer and use it in GitHub Desktop.
Save therustmonk/7bd337bdd895f841e6a60af9019024f8 to your computer and use it in GitHub Desktop.
Serialize maps (HashMap, BTreeMap) with complex keys (tuples, etc) [Rust]
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
struct Attributes {
#[serde(with = "attr")]
pub attr: HashMap<Request, u32>,
}
mod attr {
use serde::{Deserializer, Serializer};
type Attr = std::collections::HashMap<super::Request, u32>;
pub(super) fn serialize<S: Serializer>(attr: &Attr, ser: S) -> Result<S::Ok, S::Error> {
let attr: Vec<_> = attr.iter().collect();
serde::Serialize::serialize(&attr, ser)
}
pub(super) fn deserialize<'de, D: Deserializer<'de>>(des: D) -> Result<Attr, D::Error> {
let attr: Vec<_> = serde::Deserialize::deserialize(des)?;
Ok(attr.into_iter().collect())
}
}
// source: https://users.rust-lang.org/t/serde-hashmap-serialization-key-error/49776/8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment