another unsuccessful attempt to ser hints

This commit is contained in:
Candifloss 2024-10-21 10:10:53 +05:30
parent 2d42401b52
commit f25f2ce2ca

View File

@ -1,8 +1,8 @@
use serde::{Serialize, Serializer}; use serde::ser::{Serialize, Serializer, SerializeMap};
use std::collections::HashMap; use std::collections::HashMap;
use zvariant::OwnedValue; use zvariant::OwnedValue;
//use std::hash::BuildHasher; //use std::hash::BuildHasher;
use serde::ser::SerializeMap; //use serde::ser::SerializeMap;
use serde_json::{Map,Value}; use serde_json::{Map,Value};
use zvariant::SerializeValue; use zvariant::SerializeValue;
@ -29,52 +29,31 @@ pub fn serialize_hints<S>(
where where
S: Serializer, S: Serializer,
{ {
// You can customize the serialization logic here // Start serializing the map
let mut state = serializer.serialize_map(Some(hints.len()))?;
for (key, value) in hints {
state.serialize_entry(key, value)?;
}
state.end()
}
/*
pub fn serialize_hints<S>(hints: &HashMap<String, OwnedValue>, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut map = serializer.serialize_map(Some(hints.len()))?; let mut map = serializer.serialize_map(Some(hints.len()))?;
for (key, value) in hints { for (key, value) in hints {
// Try to cast the value to a string, otherwise fallback to debug format // Serialize each entry as desired
let value_str = match value.downcast_ref::<String>() { map.serialize_entry(key, &HintValueSerializer(value))?;
Ok(s) => s.clone(), // Successfully cast to String
Err(_) => format!("{:?}", value), // Fallback for non-String values
};
map.serialize_entry(key, &value_str)?;
} }
map.end() map.end()
} }
*/
/* // A custom struct to handle serialization of OwnedValue
pub fn serialize_hints<S, H>( struct HintValueSerializer<'a>(&'a OwnedValue);
hints: &HashMap<String, OwnedValue, H>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
H: BuildHasher,
{
let mut map = serde_json::Map::new();
for (key, value) in hints { impl<'a> Serialize for HintValueSerializer<'a> {
// Customize OwnedValue serialization as needed fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
map.insert(key.clone(), serde_json::Value::String(value.to_string())); where
S: Serializer,
{
// Access the signature and value parts of the OwnedValue
let signature = self.0.value_signature().to_string();
let value = &self.0;
// Serialize them as a map with "signature" and "value" fields
let mut map = serializer.serialize_map(Some(2))?;
map.serialize_entry("signature", &signature)?;
map.serialize_entry("value", value)?;
map.end()
} }
map.serialize(serializer)
} }
*/