Skip to main content

malachite_nz/gaussian_integer/conversion/
primitive_int_from_gaussian_integer.rs

1// Copyright © 2026 Mikhail Hogrefe
2//
3// This file is part of Malachite.
4//
5// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
6// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
7// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
8
9use crate::gaussian_integer::GaussianInteger;
10use crate::integer::Integer;
11use malachite_base::num::conversion::traits::ConvertibleFrom;
12
13#[derive(Clone, Copy, Debug, Eq, PartialEq)]
14pub struct PrimitiveIntFromGaussianIntegerError;
15
16fn try_from_helper<'a, T: TryFrom<&'a Integer>>(
17    x: &'a GaussianInteger,
18) -> Result<T, PrimitiveIntFromGaussianIntegerError> {
19    if x.imaginary == 0u32 {
20        T::try_from(&x.real).map_err(|_| PrimitiveIntFromGaussianIntegerError)
21    } else {
22        Err(PrimitiveIntFromGaussianIntegerError)
23    }
24}
25
26fn convertible_from_helper<T: for<'a> ConvertibleFrom<&'a Integer>>(x: &GaussianInteger) -> bool {
27    x.imaginary == 0u32 && T::convertible_from(&x.real)
28}
29
30macro_rules! impl_primitive_int_from_gaussian_integer {
31    ($t:ident) => {
32        impl TryFrom<&GaussianInteger> for $t {
33            type Error = PrimitiveIntFromGaussianIntegerError;
34
35            /// Converts a [`GaussianInteger`] to a primitive integer, returning an error if the
36            /// [`GaussianInteger`] is not real or cannot be represented.
37            ///
38            /// # Worst-case complexity
39            /// Constant time and additional memory.
40            ///
41            /// # Examples
42            /// See [here](super::primitive_int_from_gaussian_integer#try_from).
43            #[inline]
44            fn try_from(x: &GaussianInteger) -> Result<$t, Self::Error> {
45                try_from_helper(x)
46            }
47        }
48
49        impl ConvertibleFrom<&GaussianInteger> for $t {
50            /// Determines whether a [`GaussianInteger`] can be converted to a primitive integer
51            /// (that is, whether it is real and representable), taking the [`GaussianInteger`] by
52            /// reference.
53            ///
54            /// # Worst-case complexity
55            /// Constant time and additional memory.
56            ///
57            /// # Examples
58            /// See [here](super::primitive_int_from_gaussian_integer#convertible_from).
59            #[inline]
60            fn convertible_from(x: &GaussianInteger) -> bool {
61                convertible_from_helper::<$t>(x)
62            }
63        }
64    };
65}
66apply_to_primitive_ints!(impl_primitive_int_from_gaussian_integer);