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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
use crate::natural::InnerNatural::{Large, Small};
use crate::natural::Natural;
use crate::platform::Limb;
use malachite_base::num::conversion::traits::ExactFrom;
use std::ops::Index;

/// A double-ended iterator over the [limbs](crate#limbs) of a [`Natural`].
///
/// The forward order is ascending (least-significant first). The iterator does not iterate over
/// any implicit leading zero limbs.
///
/// This struct also supports retrieving limbs by index. This functionality is completely
/// independent of the iterator's state. Indexing the implicit leading zero limbs is allowed.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct LimbIterator<'a> {
    pub(crate) n: &'a Natural,
    pub(crate) limb_count: usize,
    // This is true iff `n` is nonzero and `i` and `j` are not yet equal. The iterator returns
    // `Some` iff this is true.
    pub(crate) some_remaining: bool,
    // If `n` is nonzero, this index initially points to the least-significant limb, and is
    // incremented by next().
    pub(crate) i: u64,
    // If `n` is nonzero, this index initially points to the most-significant limb, and is
    // decremented by next_back().
    pub(crate) j: u64,
}

impl<'a> Iterator for LimbIterator<'a> {
    type Item = Limb;

    /// A function to iterate through the [limbs](crate#limbs) of a [`Natural`] in ascending order
    /// (least-significant first).
    ///
    /// # Worst-case complexity
    /// Constant time and additional memory.
    ///
    /// # Examples
    /// ```
    /// extern crate malachite_base;
    ///
    /// use malachite_base::num::arithmetic::traits::Pow;
    /// use malachite_base::num::basic::integers::PrimitiveInt;
    /// use malachite_base::num::basic::traits::Zero;
    /// use malachite_nz::natural::Natural;
    /// use malachite_nz::platform::Limb;
    ///
    /// if Limb::WIDTH == u32::WIDTH {
    ///     assert_eq!(Natural::ZERO.limbs().next(), None);
    ///
    ///     // 10^12 = 232 * 2^32 + 3567587328
    ///     let trillion = Natural::from(10u32).pow(12);
    ///     let mut limbs = trillion.limbs();
    ///     assert_eq!(limbs.next(), Some(3567587328));
    ///     assert_eq!(limbs.next(), Some(232));
    ///     assert_eq!(limbs.next(), None);
    /// }
    /// ```
    fn next(&mut self) -> Option<Limb> {
        if self.some_remaining {
            let limb = match *self.n {
                Natural(Small(small)) => small,
                Natural(Large(ref limbs)) => limbs[usize::exact_from(self.i)],
            };
            if self.i == self.j {
                self.some_remaining = false;
            } else {
                self.i += 1;
            }
            Some(limb)
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.limb_count, Some(self.limb_count))
    }
}

impl<'a> DoubleEndedIterator for LimbIterator<'a> {
    /// A function to iterate through the [limbs](crate#limbs) of a [`Natural`] in descending order
    /// (most-significant first).
    ///
    /// # Worst-case complexity
    /// Constant time and additional memory.
    ///
    /// # Examples
    /// ```
    /// extern crate malachite_base;
    ///
    /// use malachite_base::num::arithmetic::traits::Pow;
    /// use malachite_base::num::basic::integers::PrimitiveInt;
    /// use malachite_base::num::basic::traits::Zero;
    /// use malachite_nz::natural::Natural;
    /// use malachite_nz::platform::Limb;
    ///
    /// if Limb::WIDTH == u32::WIDTH {
    ///     assert_eq!(Natural::ZERO.limbs().next_back(), None);
    ///
    ///     // 10^12 = 232 * 2^32 + 3567587328
    ///     let trillion = Natural::from(10u32).pow(12);
    ///     let mut limbs = trillion.limbs();
    ///     assert_eq!(limbs.next_back(), Some(232));
    ///     assert_eq!(limbs.next_back(), Some(3567587328));
    ///     assert_eq!(limbs.next_back(), None);
    /// }
    /// ```
    fn next_back(&mut self) -> Option<Limb> {
        if self.some_remaining {
            let limb = match *self.n {
                Natural(Small(small)) => small,
                Natural(Large(ref limbs)) => limbs[usize::exact_from(self.j)],
            };
            if self.j == self.i {
                self.some_remaining = false;
            } else {
                self.j -= 1;
            }
            Some(limb)
        } else {
            None
        }
    }
}

impl<'a> ExactSizeIterator for LimbIterator<'a> {}

impl<'a> Index<usize> for LimbIterator<'a> {
    type Output = Limb;

    /// A function to retrieve a [`Natural`]'s [limbs](crate#limbs) by index.
    ///
    /// The index is the power of $2^W$ of which the limbs is a coefficient, where $W$ is the width
    /// of a limb. Indexing at or above the limb count returns zeros.
    ///
    /// # Worst-case complexity
    /// Constant time and additional memory.
    ///
    /// # Examples
    /// ```
    /// extern crate malachite_base;
    ///
    /// use malachite_base::num::arithmetic::traits::Pow;
    /// use malachite_base::num::basic::integers::PrimitiveInt;
    /// use malachite_base::num::basic::traits::Zero;
    /// use malachite_nz::natural::Natural;
    /// use malachite_nz::platform::Limb;
    ///
    /// if Limb::WIDTH == u32::WIDTH {
    ///     assert_eq!(Natural::ZERO.limbs()[0], 0);
    ///
    ///     // 10^12 = 232 * 2^32 + 3567587328
    ///     let trillion = Natural::from(10u32).pow(12);
    ///     let limbs = trillion.limbs();
    ///     assert_eq!(limbs[0], 3567587328);
    ///     assert_eq!(limbs[1], 232);
    ///     assert_eq!(limbs[2], 0);
    ///     assert_eq!(limbs[100], 0);
    /// }
    /// ```
    fn index(&self, index: usize) -> &Limb {
        if index >= self.limb_count {
            &0
        } else {
            match *self.n {
                Natural(Small(ref small)) => small,
                Natural(Large(ref limbs)) => limbs.index(index),
            }
        }
    }
}

impl Natural {
    /// Returns the [limbs](crate#limbs) of a [`Natural`], in ascending order, so that
    /// less-significant limbs have lower indices in the output vector.
    ///
    /// There are no trailing zero limbs.
    ///
    /// This function borrows the [`Natural`]. If taking ownership is possible instead,
    /// [`into_limbs_asc`](Self::into_limbs_asc) is more efficient.
    ///
    /// This function is more efficient than [`to_limbs_desc`](Self::to_limbs_desc).
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n)$
    ///
    /// $M(n) = O(n)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
    ///
    /// # Examples
    /// ```
    /// extern crate malachite_base;
    ///
    /// use malachite_base::num::arithmetic::traits::Pow;
    /// use malachite_base::num::basic::integers::PrimitiveInt;
    /// use malachite_base::num::basic::traits::Zero;
    /// use malachite_nz::natural::Natural;
    /// use malachite_nz::platform::Limb;
    ///
    /// if Limb::WIDTH == u32::WIDTH {
    ///     assert!(Natural::ZERO.to_limbs_asc().is_empty());
    ///     assert_eq!(Natural::from(123u32).to_limbs_asc(), &[123]);
    ///     // 10^12 = 232 * 2^32 + 3567587328
    ///     assert_eq!(Natural::from(10u32).pow(12).to_limbs_asc(), &[3567587328, 232]);
    /// }
    /// ```
    pub fn to_limbs_asc(&self) -> Vec<Limb> {
        match *self {
            natural_zero!() => Vec::new(),
            Natural(Small(small)) => vec![small],
            Natural(Large(ref limbs)) => limbs.clone(),
        }
    }

    /// Returns the [limbs](crate#limbs) of a [`Natural`] in descending order, so that
    /// less-significant limbs have higher indices in the output vector.
    ///
    /// There are no leading zero limbs.
    ///
    /// This function borrows the [`Natural`]. If taking ownership is possible instead,
    /// [`into_limbs_desc`](Self::into_limbs_desc) is more efficient.
    ///
    /// This function is less efficient than [`to_limbs_asc`](Self::to_limbs_asc).
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n)$
    ///
    /// $M(n) = O(n)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
    ///
    /// # Examples
    /// ```
    /// extern crate malachite_base;
    ///
    /// use malachite_base::num::arithmetic::traits::Pow;
    /// use malachite_base::num::basic::integers::PrimitiveInt;
    /// use malachite_base::num::basic::traits::Zero;
    /// use malachite_nz::natural::Natural;
    /// use malachite_nz::platform::Limb;
    ///
    /// if Limb::WIDTH == u32::WIDTH {
    ///     assert!(Natural::ZERO.to_limbs_desc().is_empty());
    ///     assert_eq!(Natural::from(123u32).to_limbs_desc(), &[123]);
    ///     // 10^12 = 232 * 2^32 + 3567587328
    ///     assert_eq!(Natural::from(10u32).pow(12).to_limbs_desc(), &[232, 3567587328]);
    /// }
    /// ```
    pub fn to_limbs_desc(&self) -> Vec<Limb> {
        match *self {
            natural_zero!() => Vec::new(),
            Natural(Small(small)) => vec![small],
            Natural(Large(ref limbs)) => limbs.iter().cloned().rev().collect(),
        }
    }

    /// Returns the [limbs](crate#limbs) of a [`Natural`], in ascending order, so that
    /// less-significant limbs have lower indices in the output vector.
    ///
    /// There are no trailing zero limbs.
    ///
    /// This function takes ownership of the [`Natural`]. If it's necessary to borrow instead, use
    /// [`to_limbs_asc`](Self::to_limbs_asc).
    ///
    /// This function is more efficient than [`into_limbs_desc`](Self::into_limbs_desc).
    ///
    /// # Worst-case complexity
    /// Constant time and additional memory.
    ///
    /// # Examples
    /// ```
    /// extern crate malachite_base;
    ///
    /// use malachite_base::num::arithmetic::traits::Pow;
    /// use malachite_base::num::basic::integers::PrimitiveInt;
    /// use malachite_base::num::basic::traits::Zero;
    /// use malachite_nz::natural::Natural;
    /// use malachite_nz::platform::Limb;
    ///
    /// if Limb::WIDTH == u32::WIDTH {
    ///     assert!(Natural::ZERO.into_limbs_asc().is_empty());
    ///     assert_eq!(Natural::from(123u32).into_limbs_asc(), &[123]);
    ///     // 10^12 = 232 * 2^32 + 3567587328
    ///     assert_eq!(Natural::from(10u32).pow(12).into_limbs_asc(), &[3567587328, 232]);
    /// }
    /// ```
    pub fn into_limbs_asc(self) -> Vec<Limb> {
        match self {
            natural_zero!() => Vec::new(),
            Natural(Small(small)) => vec![small],
            Natural(Large(limbs)) => limbs,
        }
    }

    /// Returns the [limbs](crate#limbs) of a [`Natural`], in descending order, so that
    /// less-significant limbs have higher indices in the output vector.
    ///
    /// There are no leading zero limbs.
    ///
    /// This function takes ownership of the [`Natural`]. If it's necessary to borrow instead, use
    /// [`to_limbs_desc`](Self::to_limbs_desc).
    ///
    /// This function is less efficient than [`into_limbs_asc`](Self::into_limbs_asc).
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n)$
    ///
    /// $M(n) = O(1)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
    ///
    /// # Examples
    /// ```
    /// extern crate malachite_base;
    ///
    /// use malachite_base::num::arithmetic::traits::Pow;
    /// use malachite_base::num::basic::integers::PrimitiveInt;
    /// use malachite_base::num::basic::traits::Zero;
    /// use malachite_nz::natural::Natural;
    /// use malachite_nz::platform::Limb;
    ///
    /// if Limb::WIDTH == u32::WIDTH {
    ///     assert!(Natural::ZERO.into_limbs_desc().is_empty());
    ///     assert_eq!(Natural::from(123u32).into_limbs_desc(), &[123]);
    ///     // 10^12 = 232 * 2^32 + 3567587328
    ///     assert_eq!(Natural::from(10u32).pow(12).into_limbs_desc(), &[232, 3567587328]);
    /// }
    /// ```
    pub fn into_limbs_desc(self) -> Vec<Limb> {
        match self {
            natural_zero!() => Vec::new(),
            Natural(Small(small)) => vec![small],
            Natural(Large(mut limbs)) => {
                limbs.reverse();
                limbs
            }
        }
    }

    /// Returns a double-ended iterator over the [limbs](crate#limbs) of a [`Natural`].
    ///
    /// The forward order is ascending, so that less-significant limbs appear first. There are no
    /// trailing zero limbs going forward, or leading zeros going backward.
    ///
    /// If it's necessary to get a [`Vec`] of all the limbs, consider using
    /// [`to_limbs_asc`](Self::to_limbs_asc), [`to_limbs_desc`](Self::to_limbs_desc),
    /// [`into_limbs_asc`](Self::into_limbs_asc), or [`into_limbs_desc`](Self::into_limbs_desc)
    /// instead.
    ///
    /// # Worst-case complexity
    /// Constant time and additional memory.
    ///
    /// # Examples
    /// ```
    /// extern crate itertools;
    /// extern crate malachite_base;
    ///
    /// use itertools::Itertools;
    /// use malachite_base::num::arithmetic::traits::Pow;
    /// use malachite_base::num::basic::integers::PrimitiveInt;
    /// use malachite_base::num::basic::traits::Zero;
    /// use malachite_nz::natural::Natural;
    /// use malachite_nz::platform::Limb;
    ///
    /// if Limb::WIDTH == u32::WIDTH {
    ///     assert!(Natural::ZERO.limbs().next().is_none());
    ///     assert_eq!(Natural::from(123u32).limbs().collect_vec(), &[123]);
    ///     // 10^12 = 232 * 2^32 + 3567587328
    ///     assert_eq!(Natural::from(10u32).pow(12).limbs().collect_vec(), &[3567587328, 232]);
    ///
    ///     assert!(Natural::ZERO.limbs().rev().next().is_none());
    ///     assert_eq!(Natural::from(123u32).limbs().rev().collect_vec(), &[123]);
    ///     // 10^12 = 232 * 2^32 + 3567587328
    ///     assert_eq!(
    ///         Natural::from(10u32).pow(12).limbs().rev().collect_vec(),
    ///         &[232, 3567587328]
    ///     );
    /// }
    /// ```
    pub fn limbs(&self) -> LimbIterator {
        let limb_count = self.limb_count();
        LimbIterator {
            n: self,
            limb_count: usize::exact_from(limb_count),
            some_remaining: limb_count != 0,
            i: 0,
            j: limb_count.saturating_sub(1),
        }
    }
}