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