Skip to main content

malachite_nz/integer/conversion/
natural_from_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::integer::Integer;
10use crate::natural::Natural;
11use malachite_base::num::basic::traits::Zero;
12use malachite_base::num::conversion::traits::{ConvertibleFrom, SaturatingFrom};
13
14#[derive(Clone, Copy, Debug, Eq, PartialEq)]
15pub struct NaturalFromIntegerError;
16
17impl TryFrom<Integer> for Natural {
18    type Error = NaturalFromIntegerError;
19
20    /// Converts an [`Integer`] to a [`Natural`], taking the [`Integer`] by value. If the
21    /// [`Integer`] is negative, an error is returned.
22    ///
23    /// # Worst-case complexity
24    /// Constant time and additional memory.
25    ///
26    /// # Examples
27    /// ```
28    /// use malachite_base::num::arithmetic::traits::Pow;
29    /// use malachite_base::strings::ToDebugString;
30    /// use malachite_nz::integer::Integer;
31    /// use malachite_nz::natural::Natural;
32    ///
33    /// assert_eq!(
34    ///     Natural::try_from(Integer::from(123)).to_debug_string(),
35    ///     "Ok(123)"
36    /// );
37    /// assert_eq!(
38    ///     Natural::try_from(Integer::from(-123)).to_debug_string(),
39    ///     "Err(NaturalFromIntegerError)"
40    /// );
41    /// assert_eq!(
42    ///     Natural::try_from(Integer::from(10u32).pow(12)).to_debug_string(),
43    ///     "Ok(1000000000000)"
44    /// );
45    /// assert_eq!(
46    ///     Natural::try_from(-Integer::from(10u32).pow(12)).to_debug_string(),
47    ///     "Err(NaturalFromIntegerError)"
48    /// );
49    /// ```
50    fn try_from(value: Integer) -> Result<Self, Self::Error> {
51        match value {
52            Integer { sign: false, .. } => Err(NaturalFromIntegerError),
53            Integer { sign: true, abs } => Ok(abs),
54        }
55    }
56}
57
58impl<'a> TryFrom<&'a Integer> for Natural {
59    type Error = NaturalFromIntegerError;
60
61    /// Converts an [`Integer`] to a [`Natural`], taking the [`Integer`] by reference. If the
62    /// [`Integer`] is negative, an error is returned.
63    ///
64    /// # Worst-case complexity
65    /// $T(n) = O(n)$
66    ///
67    /// $M(n) = O(n)$
68    ///
69    /// where $T$ is time, $M$ is additional memory, and $n$ is `value.significant_bits()`.
70    ///
71    /// # Examples
72    /// ```
73    /// use malachite_base::num::arithmetic::traits::Pow;
74    /// use malachite_base::strings::ToDebugString;
75    /// use malachite_nz::integer::Integer;
76    /// use malachite_nz::natural::Natural;
77    ///
78    /// assert_eq!(
79    ///     Natural::try_from(&Integer::from(123)).to_debug_string(),
80    ///     "Ok(123)"
81    /// );
82    /// assert_eq!(
83    ///     Natural::try_from(&Integer::from(-123)).to_debug_string(),
84    ///     "Err(NaturalFromIntegerError)"
85    /// );
86    /// assert_eq!(
87    ///     Natural::try_from(&Integer::from(10u32).pow(12)).to_debug_string(),
88    ///     "Ok(1000000000000)"
89    /// );
90    /// assert_eq!(
91    ///     Natural::try_from(&(-Integer::from(10u32).pow(12))).to_debug_string(),
92    ///     "Err(NaturalFromIntegerError)"
93    /// );
94    /// ```
95    fn try_from(value: &'a Integer) -> Result<Self, Self::Error> {
96        match *value {
97            Integer { sign: false, .. } => Err(NaturalFromIntegerError),
98            Integer {
99                sign: true,
100                ref abs,
101            } => Ok(abs.clone()),
102        }
103    }
104}
105
106impl SaturatingFrom<Integer> for Natural {
107    /// Converts an [`Integer`] to a [`Natural`], taking the [`Integer`] by value. If the
108    /// [`Integer`] is negative, 0 is returned.
109    ///
110    /// # Worst-case complexity
111    /// Constant time and additional memory.
112    ///
113    /// # Examples
114    /// ```
115    /// use malachite_base::num::arithmetic::traits::Pow;
116    /// use malachite_base::num::conversion::traits::SaturatingFrom;
117    /// use malachite_nz::integer::Integer;
118    /// use malachite_nz::natural::Natural;
119    ///
120    /// assert_eq!(Natural::saturating_from(Integer::from(123)), 123);
121    /// assert_eq!(Natural::saturating_from(Integer::from(-123)), 0);
122    /// assert_eq!(
123    ///     Natural::saturating_from(Integer::from(10u32).pow(12)),
124    ///     1000000000000u64
125    /// );
126    /// assert_eq!(Natural::saturating_from(-Integer::from(10u32).pow(12)), 0);
127    /// ```
128    fn saturating_from(value: Integer) -> Self {
129        match value {
130            Integer { sign: false, .. } => Self::ZERO,
131            Integer { sign: true, abs } => abs,
132        }
133    }
134}
135
136impl<'a> SaturatingFrom<&'a Integer> for Natural {
137    /// Converts an [`Integer`] to a [`Natural`], taking the [`Integer`] by reference. If the
138    /// [`Integer`] is negative, 0 is returned.
139    ///
140    /// # Worst-case complexity
141    /// $T(n) = O(n)$
142    ///
143    /// $M(n) = O(n)$
144    ///
145    /// where $T$ is time, $M$ is additional memory, and $n$ is `value.significant_bits()`.
146    ///
147    /// # Examples
148    /// ```
149    /// use malachite_base::num::arithmetic::traits::Pow;
150    /// use malachite_base::num::conversion::traits::SaturatingFrom;
151    /// use malachite_nz::integer::Integer;
152    /// use malachite_nz::natural::Natural;
153    ///
154    /// assert_eq!(Natural::saturating_from(&Integer::from(123)), 123);
155    /// assert_eq!(Natural::saturating_from(&Integer::from(-123)), 0);
156    /// assert_eq!(
157    ///     Natural::saturating_from(&Integer::from(10u32).pow(12)),
158    ///     1000000000000u64
159    /// );
160    /// assert_eq!(Natural::saturating_from(&-Integer::from(10u32).pow(12)), 0);
161    /// ```
162    fn saturating_from(value: &'a Integer) -> Self {
163        match *value {
164            Integer { sign: false, .. } => Self::ZERO,
165            Integer {
166                sign: true,
167                ref abs,
168            } => abs.clone(),
169        }
170    }
171}
172
173impl ConvertibleFrom<Integer> for Natural {
174    /// Determines whether an [`Integer`] can be converted to a [`Natural`] (when the [`Integer`] is
175    /// non-negative). Takes the [`Integer`] by value.
176    ///
177    /// # Worst-case complexity
178    /// Constant time and additional memory.
179    ///
180    /// # Examples
181    /// ```
182    /// use malachite_base::num::arithmetic::traits::Pow;
183    /// use malachite_base::num::conversion::traits::ConvertibleFrom;
184    /// use malachite_nz::integer::Integer;
185    /// use malachite_nz::natural::Natural;
186    ///
187    /// assert_eq!(Natural::convertible_from(Integer::from(123)), true);
188    /// assert_eq!(Natural::convertible_from(Integer::from(-123)), false);
189    /// assert_eq!(
190    ///     Natural::convertible_from(Integer::from(10u32).pow(12)),
191    ///     true
192    /// );
193    /// assert_eq!(
194    ///     Natural::convertible_from(-Integer::from(10u32).pow(12)),
195    ///     false
196    /// );
197    /// ```
198    #[inline]
199    fn convertible_from(value: Integer) -> bool {
200        value.sign
201    }
202}
203
204impl<'a> ConvertibleFrom<&'a Integer> for Natural {
205    /// Determines whether an [`Integer`] can be converted to a [`Natural`] (when the [`Integer`] is
206    /// non-negative). Takes the [`Integer`] by reference.
207    ///
208    /// # Worst-case complexity
209    /// Constant time and additional memory.
210    ///
211    /// # Examples
212    /// ```
213    /// use malachite_base::num::arithmetic::traits::Pow;
214    /// use malachite_base::num::conversion::traits::ConvertibleFrom;
215    /// use malachite_nz::integer::Integer;
216    /// use malachite_nz::natural::Natural;
217    ///
218    /// assert_eq!(Natural::convertible_from(&Integer::from(123)), true);
219    /// assert_eq!(Natural::convertible_from(&Integer::from(-123)), false);
220    /// assert_eq!(
221    ///     Natural::convertible_from(&Integer::from(10u32).pow(12)),
222    ///     true
223    /// );
224    /// assert_eq!(
225    ///     Natural::convertible_from(&-Integer::from(10u32).pow(12)),
226    ///     false
227    /// );
228    /// ```
229    #[inline]
230    fn convertible_from(value: &'a Integer) -> bool {
231        value.sign
232    }
233}