malachite_nz/natural/conversion/limb_count.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::natural::InnerNatural::{Large, Small};
10use crate::natural::Natural;
11use malachite_base::num::basic::traits::Zero;
12use malachite_base::num::conversion::traits::WrappingFrom;
13
14impl Natural {
15 /// Returns the number of limbs of a [`Natural`].
16 ///
17 /// Zero has 0 limbs.
18 ///
19 /// # Worst-case complexity
20 /// Constant time and additional memory.
21 ///
22 /// # Examples
23 /// ```
24 /// use malachite_base::num::arithmetic::traits::Pow;
25 /// use malachite_base::num::basic::integers::PrimitiveInt;
26 /// use malachite_base::num::basic::traits::Zero;
27 /// use malachite_nz::natural::Natural;
28 /// use malachite_nz::platform::Limb;
29 ///
30 /// if Limb::WIDTH == u32::WIDTH {
31 /// assert_eq!(Natural::ZERO.limb_count(), 0);
32 /// assert_eq!(Natural::from(123u32).limb_count(), 1);
33 /// assert_eq!(Natural::from(10u32).pow(12).limb_count(), 2);
34 /// }
35 /// ```
36 pub fn limb_count(&self) -> u64 {
37 match self {
38 &Natural::ZERO => 0,
39 Natural(Small(_)) => 1,
40 Natural(Large(limbs)) => u64::wrapping_from(limbs.len()),
41 }
42 }
43}