73 lines
2.2 KiB
Rust
73 lines
2.2 KiB
Rust
use serde::ser::{Serialize, SerializeMap, Serializer};
|
|
use serde_json::{Map, Value};
|
|
use std::collections::HashMap;
|
|
use zvariant::OwnedValue;
|
|
|
|
pub fn serialize_actions<S>(actions: &[String], serializer: S) -> Result<S::Ok, S::Error>
|
|
where
|
|
S: Serializer,
|
|
{
|
|
let mut map = Map::new();
|
|
|
|
// Actions are in pairs: [id, label, id, label, ...]
|
|
for pair in actions.chunks(2) {
|
|
if let [id, label] = pair {
|
|
map.insert(id.clone(), Value::String(label.clone()));
|
|
}
|
|
}
|
|
|
|
map.serialize(serializer)
|
|
}
|
|
|
|
pub fn serialize_hints<S>(
|
|
hints: &HashMap<String, OwnedValue>,
|
|
serializer: S,
|
|
) -> Result<S::Ok, S::Error>
|
|
where
|
|
S: Serializer,
|
|
{
|
|
// Start serializing the map
|
|
let mut map = serializer.serialize_map(Some(hints.len()))?;
|
|
for (key, value) in hints {
|
|
// Serialize each entry as desired
|
|
map.serialize_entry(key, &HintValueSerializer(value))?;
|
|
}
|
|
map.end()
|
|
}
|
|
|
|
// A custom struct to handle serialization of OwnedValue
|
|
struct HintValueSerializer<'a>(&'a OwnedValue);
|
|
|
|
impl Serialize for HintValueSerializer<'_> {
|
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
|
where
|
|
S: Serializer,
|
|
{
|
|
// Signature
|
|
let signature = self.0.value_signature().to_string();
|
|
|
|
// Extract the raw value correctly
|
|
let raw_value = if let Ok(v) = self.0.downcast_ref::<u8>() {
|
|
Value::from(v)
|
|
} else if let Ok(v) = self.0.downcast_ref::<i32>() {
|
|
Value::from(v)
|
|
} else if let Ok(v) = self.0.downcast_ref::<u64>() {
|
|
Value::from(v)
|
|
} else if let Ok(v) = self.0.downcast_ref::<bool>() {
|
|
Value::Bool(v)
|
|
} else if let Ok(v) = self.0.downcast_ref::<String>() {
|
|
Value::String(v.clone())
|
|
} else if let Ok(v) = self.0.downcast_ref::<&str>() {
|
|
Value::String(v.to_string())
|
|
} else {
|
|
Value::Null // Unsupported types fallback to Null
|
|
};
|
|
|
|
// Serialize the final structure as a map
|
|
let mut map = serializer.serialize_map(Some(2))?;
|
|
map.serialize_entry("signature", &signature)?;
|
|
map.serialize_entry("value", &raw_value)?;
|
|
map.end()
|
|
}
|
|
}
|