malachite_nz/integer/arithmetic/canonicalize_unit.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 malachite_base::num::arithmetic::traits::{
11 Abs, AbsAssign, CanonicalizeUnit, CanonicalizeUnitAssign,
12};
13
14impl CanonicalizeUnit for Integer {
15 type Output = Self;
16
17 /// Brings a [`Integer`] into canonical unit form, taking it by value. The canonical unit form
18 /// of an [`Integer`] is its absolute value.
19 ///
20 /// # Worst-case complexity
21 /// Constant time and additional memory.
22 ///
23 /// # Examples
24 /// ```
25 /// use malachite_base::num::arithmetic::traits::CanonicalizeUnit;
26 /// use malachite_nz::integer::Integer;
27 ///
28 /// assert_eq!(Integer::from(-123).canonicalize_unit(), 123);
29 /// ```
30 #[inline]
31 fn canonicalize_unit(self) -> Self {
32 self.abs()
33 }
34}
35
36impl CanonicalizeUnit for &Integer {
37 type Output = Integer;
38
39 /// Brings a [`Integer`] into canonical unit form, taking it by reference. The canonical unit
40 /// form of an [`Integer`] is its absolute value.
41 ///
42 /// # Worst-case complexity
43 /// $T(n) = O(n)$
44 ///
45 /// $M(n) = O(n)$
46 ///
47 /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
48 ///
49 /// # Examples
50 /// ```
51 /// use malachite_base::num::arithmetic::traits::CanonicalizeUnit;
52 /// use malachite_nz::integer::Integer;
53 ///
54 /// assert_eq!((&Integer::from(-123)).canonicalize_unit(), 123);
55 /// ```
56 #[inline]
57 fn canonicalize_unit(self) -> Integer {
58 self.abs()
59 }
60}
61
62impl CanonicalizeUnitAssign for Integer {
63 /// Replaces a [`Integer`] with its canonical unit form. The canonical unit form of an
64 /// [`Integer`] is its absolute value.
65 ///
66 /// # Worst-case complexity
67 /// Constant time and additional memory.
68 ///
69 /// # Examples
70 /// ```
71 /// use malachite_base::num::arithmetic::traits::CanonicalizeUnitAssign;
72 /// use malachite_nz::integer::Integer;
73 ///
74 /// let mut x = Integer::from(-123);
75 /// x.canonicalize_unit_assign();
76 /// assert_eq!(x, 123);
77 /// ```
78 #[inline]
79 fn canonicalize_unit_assign(&mut self) {
80 self.abs_assign();
81 }
82}