use qtbridge_type_lib::QVariant;
use crate::QMetaTypeCompatible;
pub trait QVariantConvertible: Sized {
fn to_qvariant(&self) -> QVariant;
fn try_from_qvariant(value: &QVariant) -> Result<Self, ()>;
}
macro_rules! impl_to_qvariant_and_try_from_qvariant {
($($t:ty),*) => {
$(
impl QVariantConvertible for $t {
fn to_qvariant(&self) -> QVariant {
let compat = QMetaTypeCompatible::to_compatible(self);
(&compat).into()
}
fn try_from_qvariant(value: &QVariant) -> Result<Self, ()> {
let compat: <$t as QMetaTypeCompatible>::CompatibleType = value.value()
.ok_or(())?;
Ok(<Self as QMetaTypeCompatible>::from_compatible(&compat))
}
}
)*
}
}
impl_to_qvariant_and_try_from_qvariant!(
bool, i8, u8, i16, u16, i32, u32, i64, u64, isize, usize, f32, f64, String,
Vec<bool>, Vec<i8>, Vec<u8>, Vec<i16>, Vec<u16>, Vec<i32>, Vec<u32>, Vec<i64>, Vec<u64>,
Vec<isize>, Vec<usize>, Vec<f32>, Vec<f64>, Vec<String>
);
impl QVariantConvertible for () {
fn to_qvariant(&self) -> QVariant {
QVariant::default()
}
fn try_from_qvariant(value: &QVariant) -> Result<Self, ()> {
match value.is_valid() {
true => Err(()),
false => Ok(()),
}
}
}
#[cfg(feature = "serde_json")]
impl QVariantConvertible for serde_json::Value {
fn to_qvariant(&self) -> QVariant {
let jv = crate::serde_tools::serde_to_qjsonvalue(self);
(&jv).into()
}
fn try_from_qvariant(value: &QVariant) -> Result<Self, ()> {
crate::serde_tools::qvariant_to_serde(value)
}
}
#[cfg(feature = "serde_json")]
impl QVariantConvertible for Vec<serde_json::Value> {
fn to_qvariant(&self) -> QVariant {
let ja = crate::serde_tools::serde_to_qjsonarray(self);
(&ja).into()
}
fn try_from_qvariant(value: &QVariant) -> Result<Self, ()> {
match crate::serde_tools::qvariant_to_serde(value)? {
serde_json::Value::Array(arr) => Ok(arr),
_ => Err(()),
}
}
}