malachite_q/conversion/
from_natural.rs

1// Copyright © 2025 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::Rational;
10use malachite_base::num::basic::traits::One;
11use malachite_nz::natural::Natural;
12
13impl From<Natural> for Rational {
14    /// Converts a [`Natural`] to a [`Rational`], taking the [`Natural`] by value.
15    ///
16    /// # Worst-case complexity
17    /// Constant time and additional memory.
18    ///
19    /// # Examples
20    /// ```
21    /// use malachite_nz::natural::Natural;
22    /// use malachite_q::Rational;
23    ///
24    /// assert_eq!(Rational::from(Natural::from(123u32)), 123);
25    /// ```
26    fn from(value: Natural) -> Self {
27        Self {
28            sign: true,
29            numerator: value,
30            denominator: Natural::ONE,
31        }
32    }
33}
34
35impl From<&Natural> for Rational {
36    /// Converts a [`Natural`] to a [`Rational`], taking the [`Natural`] by reference.
37    ///
38    /// # Worst-case complexity
39    /// $T(n) = O(n)$
40    ///
41    /// $M(n) = O(n)$
42    ///
43    /// where $T$ is time, $M$ is additional memory, and $n$ is `value.significant_bits()`.
44    ///
45    /// # Examples
46    /// ```
47    /// use malachite_nz::natural::Natural;
48    /// use malachite_q::Rational;
49    ///
50    /// assert_eq!(Rational::from(&Natural::from(123u32)), 123);
51    /// ```
52    fn from(value: &Natural) -> Self {
53        Self {
54            sign: true,
55            numerator: value.clone(),
56            denominator: Natural::ONE,
57        }
58    }
59}