malachite_nz/gaussian_integer/conversion/from_primitive_float.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 GaussianIntegerFromPrimitiveFloatError;
15
16macro_rules! float_impls {
17 ($f: ident) => {
18 impl TryFrom<$f> for GaussianInteger {
19 type Error = GaussianIntegerFromPrimitiveFloatError;
20
21 /// Converts a primitive float to a [`GaussianInteger`], producing a purely real value.
22 ///
23 /// If the input isn't exactly equal to some [`Integer`], an error is returned.
24 ///
25 /// # Worst-case complexity
26 /// $T(n) = O(n)$
27 ///
28 /// $M(n) = O(n)$
29 ///
30 /// where $T$ is time, $M$ is additional memory, and $n$ is `value.sci_exponent()`.
31 ///
32 /// # Examples
33 /// See [here](super::from_primitive_float#try_from).
34 fn try_from(value: $f) -> Result<GaussianInteger, Self::Error> {
35 Integer::try_from(value)
36 .map(GaussianInteger::from)
37 .map_err(|_| GaussianIntegerFromPrimitiveFloatError)
38 }
39 }
40
41 impl ConvertibleFrom<$f> for GaussianInteger {
42 /// Determines whether a primitive float can be converted to a [`GaussianInteger`] (that
43 /// is, whether it is finite and an integer).
44 ///
45 /// # Worst-case complexity
46 /// Constant time and additional memory.
47 ///
48 /// # Examples
49 /// See [here](super::from_primitive_float#convertible_from).
50 #[inline]
51 fn convertible_from(value: $f) -> bool {
52 Integer::convertible_from(value)
53 }
54 }
55 };
56}
57apply_to_primitive_floats!(float_impls);