use std::{collections::HashMap, hash::Hash};
pub fn convert_vec<T, U>(v: Vec<T>) -> Vec<U>
where
U: From<T>,
{
v.into_iter().map(|v| v.into()).collect()
}
pub fn convert_map<A: Hash + Eq, T, U>(v: HashMap<A, T>) -> HashMap<A, U>
where
U: From<T>,
{
v.into_iter().map(|(k, v)| (k, v.into())).collect()
}
pub fn convert_opt_vec<T, U>(v: Option<Vec<T>>) -> Option<Vec<U>>
where
U: From<T>,
{
v.map(|item| convert_vec(item))
}
pub fn convert_opt_map<A: Hash + Eq, T, U>(v: Option<HashMap<A, T>>) -> Option<HashMap<A, U>>
where
U: From<T>,
{
v.map(|item| convert_map(item))
}
pub(crate) trait ConvertFrom<T>: ConvertFromWithContext<T, ()> + Sized {
fn from(value: T) -> Self {
<Self as ConvertFromWithContext<T, ()>>::from(value, ())
}
}
impl<T, U> ConvertFrom<T> for U where U: ConvertFromWithContext<T, ()> {}
pub(crate) trait ConvertFromWithContext<T, C>
where
C: Copy,
{
fn from(value: T, context: C) -> Self;
}
pub(crate) trait ConvertInto<T>
where
T: ConvertFrom<Self>,
Self: Sized,
{
fn convert_into(self) -> T {
<T as ConvertFrom<Self>>::from(self)
}
}
impl<T, U> ConvertInto<T> for U where T: ConvertFrom<U> {}
pub(crate) trait ConvertIntoWithContext<T, C>
where
T: ConvertFromWithContext<Self, C>,
Self: Sized,
C: Copy,
{
fn convert_into_with_context(self, context: C) -> T {
T::from(self, context)
}
}
impl<T, U, C> ConvertIntoWithContext<T, C> for U
where
T: ConvertFromWithContext<U, C>,
C: Copy,
{
}