1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
// Copyright © 2024 Mikhail Hogrefe
//
// This file is part of Malachite.
//
// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.

use crate::natural::InnerNatural::{Large, Small};
use crate::natural::Natural;
use crate::platform::Limb;
use alloc::vec::Vec;
use malachite_base::num::basic::traits::Zero;

// # Worst-case complexity
// $T(n) = O(n)$
//
// $M(n) = O(1)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `xs.len()`.
//
// Returns the length of `xs`, excluding trailing zeros.
fn limbs_significant_length(xs: &[Limb]) -> usize {
    xs.iter()
        .enumerate()
        .rev()
        .find(|&(_, &x)| x != 0)
        .map_or(0, |(i, _)| i + 1)
}

impl Natural {
    /// Converts a slice of [limbs](crate#limbs) to a [`Natural`].
    ///
    /// The limbs are in ascending order, so that less-significant limbs have lower indices in the
    /// input slice.
    ///
    /// This function borrows the limbs. If taking ownership of limbs is possible,
    /// [`from_owned_limbs_asc`](Self::from_owned_limbs_asc) is more efficient.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n)$
    ///
    /// $M(n) = O(n)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `xs.len()`.
    ///
    /// This function is more efficient than [`from_limbs_desc`](Self::from_limbs_desc).
    ///
    /// # Examples
    /// ```
    /// use malachite_base::num::basic::integers::PrimitiveInt;
    /// use malachite_nz::natural::Natural;
    /// use malachite_nz::platform::Limb;
    ///
    /// if Limb::WIDTH == u32::WIDTH {
    ///     assert_eq!(Natural::from_limbs_asc(&[]), 0);
    ///     assert_eq!(Natural::from_limbs_asc(&[123]), 123);
    ///     // 10^12 = 232 * 2^32 + 3567587328
    ///     assert_eq!(Natural::from_limbs_asc(&[3567587328, 232]), 1000000000000u64);
    /// }
    /// ```
    pub fn from_limbs_asc(xs: &[Limb]) -> Natural {
        let significant_length = limbs_significant_length(xs);
        match significant_length {
            0 => Natural::ZERO,
            1 => Natural(Small(xs[0])),
            _ => Natural(Large(xs[..significant_length].to_vec())),
        }
    }

    /// Converts a slice of [limbs](crate#limbs) to a [`Natural`].
    ///
    /// The limbs in descending order, so that less-significant limbs have higher indices in the
    /// input slice.
    ///
    /// This function borrows the limbs. If taking ownership of the limbs is possible,
    /// [`from_owned_limbs_desc`](Self::from_owned_limbs_desc) is more efficient.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n)$
    ///
    /// $M(n) = O(n)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `xs.len()`.
    ///
    /// This function is less efficient than [`from_limbs_asc`](Self::from_limbs_asc).
    ///
    /// # Examples
    /// ```
    /// use malachite_base::num::basic::integers::PrimitiveInt;
    /// use malachite_nz::natural::Natural;
    /// use malachite_nz::platform::Limb;
    ///
    /// if Limb::WIDTH == u32::WIDTH {
    ///     assert_eq!(Natural::from_limbs_desc(&[]), 0);
    ///     assert_eq!(Natural::from_limbs_desc(&[123]), 123);
    ///     // 10^12 = 232 * 2^32 + 3567587328
    ///     assert_eq!(Natural::from_limbs_desc(&[232, 3567587328]), 1000000000000u64);
    /// }
    /// ```
    pub fn from_limbs_desc(xs: &[Limb]) -> Natural {
        Natural::from_owned_limbs_asc(xs.iter().cloned().rev().collect())
    }

    /// Converts a [`Vec`] of [limbs](crate#limbs) to a [`Natural`].
    ///
    /// The limbs are in ascending order, so that less-significant limbs have lower indices in the
    /// input [`Vec`].
    ///
    /// This function takes ownership of the limbs. If it's necessary to borrow the limbs instead,
    /// use [`from_limbs_asc`](Self::from_limbs_asc).
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n)$
    ///
    /// $M(n) = O(1)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `xs.len()`.
    ///
    /// This function is more efficient than [`from_limbs_desc`](Self::from_limbs_desc).
    ///
    /// # Examples
    /// ```
    /// use malachite_base::num::basic::integers::PrimitiveInt;
    /// use malachite_nz::natural::Natural;
    /// use malachite_nz::platform::Limb;
    ///
    /// if Limb::WIDTH == u32::WIDTH {
    ///     assert_eq!(Natural::from_owned_limbs_asc(vec![]), 0);
    ///     assert_eq!(Natural::from_owned_limbs_asc(vec![123]), 123);
    ///     // 10^12 = 232 * 2^32 + 3567587328
    ///     assert_eq!(Natural::from_owned_limbs_asc(vec![3567587328, 232]), 1000000000000u64);
    /// }
    /// ```
    pub fn from_owned_limbs_asc(mut xs: Vec<Limb>) -> Natural {
        let significant_length = limbs_significant_length(&xs);
        match significant_length {
            0 => Natural::ZERO,
            1 => Natural(Small(xs[0])),
            _ => {
                xs.truncate(significant_length);
                Natural(Large(xs))
            }
        }
    }

    /// Converts a [`Vec`] of [limbs](crate#limbs) to a [`Natural`].
    ///
    /// The limbs are in descending order, so that less-significant limbs have higher indices in the
    /// input [`Vec`].
    ///
    /// This function takes ownership of the limbs. If it's necessary to borrow the limbs instead,
    /// use [`from_limbs_desc`](Self::from_limbs_desc).
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n)$
    ///
    /// $M(n) = O(1)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `xs.len()`.
    ///
    /// This function is less efficient than [`from_limbs_asc`](Self::from_limbs_asc).
    ///
    /// # Examples
    /// ```
    /// use malachite_base::num::basic::integers::PrimitiveInt;
    /// use malachite_nz::natural::Natural;
    /// use malachite_nz::platform::Limb;
    ///
    /// if Limb::WIDTH == u32::WIDTH {
    ///     assert_eq!(Natural::from_owned_limbs_desc(vec![]), 0);
    ///     assert_eq!(Natural::from_owned_limbs_desc(vec![123]), 123);
    ///     // 10^12 = 232 * 2^32 + 3567587328
    ///     assert_eq!(Natural::from_owned_limbs_desc(vec![232, 3567587328]), 1000000000000u64);
    /// }
    /// ```
    pub fn from_owned_limbs_desc(mut xs: Vec<Limb>) -> Natural {
        xs.reverse();
        Natural::from_owned_limbs_asc(xs)
    }
}