Last active
June 27, 2023 06:11
-
-
Save matthewjberger/c7670bf8f936ef66382ad751a157695a to your computer and use it in GitHub Desktop.
custom hashmap serialization in rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use serde::{Deserialize, Serialize}; | |
use serde_json::{json, Value}; | |
use std::collections::HashMap; | |
#[derive(Debug, PartialEq, Serialize, Deserialize)] | |
enum UnitEnum { | |
Variant1, | |
Variant2, | |
Variant3, | |
} | |
fn serialize_enum_to_u64<S>(value: &UnitEnum, serializer: S) -> Result<S::Ok, S::Error> | |
where | |
S: serde::Serializer, | |
{ | |
match value { | |
UnitEnum::Variant1 => serializer.serialize_u64(1), | |
UnitEnum::Variant2 => serializer.serialize_u64(2), | |
UnitEnum::Variant3 => serializer.serialize_u64(3), | |
} | |
} | |
fn deserialize_u64_to_enum<'de, D>(deserializer: D) -> Result<UnitEnum, D::Error> | |
where | |
D: serde::Deserializer<'de>, | |
{ | |
let u64_value = u64::deserialize(deserializer)?; | |
match u64_value { | |
1 => Ok(UnitEnum::Variant1), | |
2 => Ok(UnitEnum::Variant2), | |
3 => Ok(UnitEnum::Variant3), | |
_ => Err(serde::de::Error::custom("Invalid value for UnitEnum")), | |
} | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::*; | |
#[test] | |
fn test_serialization_deserialization() { | |
let mut hashmap: HashMap<&str, UnitEnum> = HashMap::new(); | |
hashmap.insert("key1", UnitEnum::Variant1); | |
hashmap.insert("key2", UnitEnum::Variant2); | |
hashmap.insert("key3", UnitEnum::Variant3); | |
let serialized: HashMap<&str, Value> = hashmap | |
.iter() | |
.map(|(k, v)| (*k, json!(v))) | |
.collect(); | |
let serialized_string = serde_json::to_string(&serialized).unwrap(); | |
let deserialized: HashMap<&str, UnitEnum> = | |
serde_json::from_str(&serialized_string).unwrap(); | |
assert_eq!(hashmap, deserialized); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment