use std::result::Result;
use std::sync::Arc;
use serde::de::Error;
use serde::Deserialize;
use serde::Deserializer;
use serde::Serialize;
use serde::Serializer;
use sync::Mutex;
pub fn serialize_arc_mutex<S: Serializer, T: Serialize + ?Sized>(
item: &Arc<Mutex<T>>,
serializer: S,
) -> Result<S::Ok, S::Error> {
let lock = item.lock();
serde::Serialize::serialize(&*lock, serializer)
}
pub fn serialize_arr<S, T: Sized + Serialize, const SIZE: usize>(
data: &[T; SIZE],
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serde::Serialize::serialize(&data[..], serializer)
}
pub fn deserialize_seq_to_arr<
'de,
D,
T: Sized + Deserialize<'de> + std::fmt::Debug,
const SIZE: usize,
>(
deserializer: D,
) -> Result<[T; SIZE], D::Error>
where
D: Deserializer<'de>,
{
let vals_vec: Vec<T> = serde::Deserialize::deserialize(deserializer)?;
let vals_arr: [T; SIZE] = vals_vec.try_into().map_err(|_| {
<D as Deserializer>::Error::custom("failed to convert vector to array while deserializing")
})?;
Ok(vals_arr)
}
pub fn serialize_map_as_kv_vec<
'se,
MapKeyType: 'se + Serialize,
MapValType: 'se + Serialize,
MapType: std::iter::IntoIterator<Item = (&'se MapKeyType, &'se MapValType)>,
S,
>(
map: MapType,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let kv_vec: Vec<(&MapKeyType, &MapValType)> = map.into_iter().collect();
serde::Serialize::serialize(&kv_vec, serializer)
}
pub fn deserialize_map_from_kv_vec<
'de,
MapKeyType: Deserialize<'de>,
MapValType: Deserialize<'de>,
MapType: std::iter::FromIterator<(MapKeyType, MapValType)>,
D,
>(
deserializer: D,
) -> Result<MapType, D::Error>
where
D: Deserializer<'de>,
{
let kv_vec: Vec<(MapKeyType, MapValType)> = serde::Deserialize::deserialize(deserializer)?;
Ok(MapType::from_iter(kv_vec))
}