use crate::gaussian_integer::GaussianInteger;
use crate::integer::Integer;
use malachite_base::num::conversion::traits::ConvertibleFrom;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct PrimitiveIntFromGaussianIntegerError;
fn try_from_helper<'a, T: TryFrom<&'a Integer>>(
x: &'a GaussianInteger,
) -> Result<T, PrimitiveIntFromGaussianIntegerError> {
if x.imaginary == 0u32 {
T::try_from(&x.real).map_err(|_| PrimitiveIntFromGaussianIntegerError)
} else {
Err(PrimitiveIntFromGaussianIntegerError)
}
}
fn convertible_from_helper<T: for<'a> ConvertibleFrom<&'a Integer>>(x: &GaussianInteger) -> bool {
x.imaginary == 0u32 && T::convertible_from(&x.real)
}
macro_rules! impl_primitive_int_from_gaussian_integer {
($t:ident) => {
impl TryFrom<&GaussianInteger> for $t {
type Error = PrimitiveIntFromGaussianIntegerError;
#[inline]
fn try_from(x: &GaussianInteger) -> Result<$t, Self::Error> {
try_from_helper(x)
}
}
impl ConvertibleFrom<&GaussianInteger> for $t {
#[inline]
fn convertible_from(x: &GaussianInteger) -> bool {
convertible_from_helper::<$t>(x)
}
}
};
}
apply_to_primitive_ints!(impl_primitive_int_from_gaussian_integer);