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 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
use itertools::Itertools;
use malachite_base::num::arithmetic::traits::{CheckedLogBase2, DivRound, PowerOf2};
use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::basic::traits::Zero;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base::num::conversion::traits::{
CheckedFrom, ExactFrom, PowerOf2Digits, WrappingFrom,
};
use malachite_base::num::iterators::iterator_to_bit_chunks;
use malachite_base::num::logic::traits::{BitBlockAccess, SignificantBits};
use malachite_base::rounding_modes::RoundingMode;
use malachite_base::slices::slice_trailing_zeros;
use natural::InnerNatural::{Large, Small};
use natural::Natural;
use platform::Limb;
use std::cmp::{min, Ordering};
impl Natural {
pub_test! {to_power_of_2_digits_asc_naive<
T: for<'a> CheckedFrom<&'a Natural> + PrimitiveUnsigned,
>(
&self,
log_base: u64,
) -> Vec<T> {
assert_ne!(log_base, 0);
if log_base > T::WIDTH {
panic!(
"type {:?} is too small for a digit of width {}",
T::NAME,
log_base
);
}
let digit_len = self
.significant_bits()
.div_round(log_base, RoundingMode::Ceiling);
let mut digits = Vec::with_capacity(usize::exact_from(digit_len));
let mut previous_index = 0;
for _ in 0..digit_len {
let index = previous_index + log_base;
digits.push(T::exact_from(&self.get_bits(previous_index, index)));
previous_index = index;
}
digits
}}
pub_test! {from_power_of_2_digits_asc_naive<T: PrimitiveUnsigned, I: Iterator<Item = T>>(
log_base: u64,
digits: I,
) -> Option<Natural>
where
Natural: From<T>,
{
assert_ne!(log_base, 0);
if log_base > T::WIDTH {
panic!(
"type {:?} is too small for a digit of width {}",
T::NAME,
log_base
);
}
let mut n = Natural::ZERO;
let mut previous_index = 0;
for digit in digits {
if digit.significant_bits() > log_base {
return None;
}
let index = previous_index + log_base;
n.assign_bits(previous_index, index, &Natural::from(digit));
previous_index = index;
}
Some(n)
}}
}
fn to_power_of_2_digits_asc_nz<T: PrimitiveUnsigned>(x: &Natural, log_base: u64) -> Vec<T>
where
Limb: PowerOf2Digits<T>,
{
assert_ne!(log_base, 0);
if log_base > T::WIDTH {
panic!(
"type {:?} is too small for a digit of width {}",
T::NAME,
log_base
);
}
let limbs = match *x {
Natural(Small(ref small)) => {
return PowerOf2Digits::<T>::to_power_of_2_digits_asc(small, min(log_base, Limb::WIDTH))
}
Natural(Large(ref limbs)) => limbs,
};
let mut digits = iterator_to_bit_chunks(limbs.iter().cloned(), Limb::WIDTH, log_base)
.map(Option::unwrap)
.collect_vec();
digits.truncate(digits.len() - slice_trailing_zeros(&digits));
digits
}
fn to_power_of_2_digits_desc_nz<T>(x: &Natural, log_base: u64) -> Vec<T>
where
Natural: PowerOf2Digits<T>,
{
let mut digits = x.to_power_of_2_digits_asc(log_base);
digits.reverse();
digits
}
fn from_power_of_2_digits_asc_nz<T: PrimitiveUnsigned, I: Iterator<Item = T>>(
log_base: u64,
digits: I,
) -> Option<Natural>
where
Limb: WrappingFrom<T>,
{
assert_ne!(log_base, 0);
if log_base > T::WIDTH {
panic!(
"type {:?} is too small for a digit of width {}",
T::NAME,
log_base
);
}
let mut limbs = Vec::new();
for digit in iterator_to_bit_chunks(digits, log_base, Limb::WIDTH) {
limbs.push(digit?);
}
Some(Natural::from_owned_limbs_asc(limbs))
}
fn from_power_of_2_digits_desc_nz<T: PrimitiveUnsigned, I: Iterator<Item = T>>(
log_base: u64,
digits: I,
) -> Option<Natural>
where
Limb: WrappingFrom<T>,
{
assert_ne!(log_base, 0);
if log_base > T::WIDTH {
panic!(
"type {:?} is too small for a digit of width {}",
T::NAME,
log_base
);
}
let digits = digits.collect_vec();
let mut limbs = Vec::new();
for digit in iterator_to_bit_chunks(digits.iter().cloned().rev(), log_base, Limb::WIDTH) {
limbs.push(digit?);
}
Some(Natural::from_owned_limbs_asc(limbs))
}
macro_rules! power_of_2_digits_unsigned {
(
$t: ident
) => {
impl PowerOf2Digits<$t> for Natural {
/// Returns a [`Vec`] containing the base-$2^k$ digits of a [`Natural`] in ascending
/// order: least- to most-significant.
///
/// The base-2 logarithm of the base is specified. Each digit has primitive integer
/// type, and `log_base` must be no larger than the width of that type. If the
/// [`Natural`] is 0, the [`Vec`] is empty; otherwise, it ends with a nonzero digit.
///
/// $f(x, k) = (d_i)_ {i=0}^{n-1}$, where $0 \leq d_i < 2^k$ for all $i$, $n=0$ or
/// $d_{n-1} \neq 0$, and
///
/// $$
/// \sum_{i=0}^{n-1}2^{ki}d_i = x.
/// $$
///
/// # 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()`.
///
/// # Panics
/// Panics if `log_base` is greater than the width of the digit type, or if `log_base`
/// is zero.
///
/// # Examples
/// See [here](super::power_of_2_digits#to_power_of_2_digits_asc).
#[inline]
fn to_power_of_2_digits_asc(&self, log_base: u64) -> Vec<$t> {
to_power_of_2_digits_asc_nz(self, log_base)
}
/// Returns a [`Vec`] containing the base-$2^k$ digits of a [`Natural`] in descending
/// order: most- to least-significant.
///
/// The base-2 logarithm of the base is specified. Each digit has primitive integer
/// type, and `log_base` must be no larger than the width of that type. If the
/// [`Natural`] is 0, the [`Vec`] is empty; otherwise, it begins with a nonzero digit.
///
/// $f(x, k) = (d_i)_ {i=0}^{n-1}$, where $0 \leq d_i < 2^k$ for all $i$, $n=0$ or
/// $d_0 \neq 0$, and
///
/// $$
/// \sum_{i=0}^{n-1}2^{k (n-i-1)}d_i = x.
/// $$
///
/// # 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()`.
///
/// # Panics
/// Panics if `log_base` is greater than the width of the digit type, or if `log_base`
/// is zero.
///
/// # Examples
/// See [here](super::power_of_2_digits#to_power_of_2_digits_desc).
#[inline]
fn to_power_of_2_digits_desc(&self, log_base: u64) -> Vec<$t> {
to_power_of_2_digits_desc_nz(self, log_base)
}
/// Converts an iterator of base-$2^k$ digits into a [`Natural`].
///
/// The base-2 logarithm of the base is specified. The input digits are in ascending
/// order: least- to most-significant. Each digit has primitive integer type, and
/// `log_base` must be no larger than the width of that type.
///
/// If some digit is greater than $2^k$, `None` is returned.
///
/// $$
/// f((d_i)_ {i=0}^{n-1}, k) = \sum_{i=0}^{n-1}2^{ki}d_i.
/// $$
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `digits.count()`.
///
/// # Panics
/// Panics if `log_base` is zero or greater than the width of the digit type.
///
/// # Examples
/// See [here](super::power_of_2_digits#from_power_of_2_digits_asc).
#[inline]
fn from_power_of_2_digits_asc<I: Iterator<Item = $t>>(
log_base: u64,
digits: I,
) -> Option<Natural> {
from_power_of_2_digits_asc_nz(log_base, digits)
}
/// Converts an iterator of base-$2^k$ digits into a [`Natural`].
///
/// The base-2 logarithm of the base is specified. The input digits are in descending
/// order: most- to least-significant. Each digit has primitive integer type, and
/// `log_base` must be no larger than the width of that type.
///
/// If some digit is greater than $2^k$, `None` is returned.
///
/// $$
/// f((d_i)_ {i=0}^{n-1}, k) = \sum_{i=0}^{n-1}2^{k (n-i-1)}d_i.
/// $$
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `digits.count()`.
///
/// # Panics
/// Panics if `log_base` is zero or greater than the width of the digit type.
///
/// # Examples
/// See [here](super::power_of_2_digits#from_power_of_2_digits_desc).
#[inline]
fn from_power_of_2_digits_desc<I: Iterator<Item = $t>>(
log_base: u64,
digits: I,
) -> Option<Natural> {
from_power_of_2_digits_desc_nz(log_base, digits)
}
}
};
}
apply_to_unsigneds!(power_of_2_digits_unsigned);
impl PowerOf2Digits<Natural> for Natural {
/// Returns a [`Vec`] containing the base-$2^k$ digits of a [`Natural`] in ascending order:
/// least- to most-significant.
///
/// The base-2 logarithm of the base is specified. The type of each digit is [`Natural`]. If
/// the [`Natural`] is 0, the [`Vec`] is empty; otherwise, it ends with a nonzero digit.
///
/// $f(x, k) = (d_i)_ {i=0}^{n-1}$, where $0 \leq d_i < 2^k$ for all $i$, $n=0$ or
/// $d_{n-1} \neq 0$, and
///
/// $$
/// \sum_{i=0}^{n-1}2^{ki}d_i = x.
/// $$
///
/// # 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()`.
///
/// # Panics
/// Panics if `log_base` is zero.
///
/// # Examples
/// ```
/// extern crate malachite_base;
///
/// use malachite_base::num::basic::traits::{Two, Zero};
/// use malachite_base::num::conversion::traits::PowerOf2Digits;
/// use malachite_base::strings::ToDebugString;
/// use malachite_nz::natural::Natural;
///
/// assert_eq!(
/// PowerOf2Digits::<Natural>::to_power_of_2_digits_asc(&Natural::ZERO, 6)
/// .to_debug_string(),
/// "[]"
/// );
/// assert_eq!(
/// PowerOf2Digits::<Natural>::to_power_of_2_digits_asc(&Natural::TWO, 6)
/// .to_debug_string(),
/// "[2]"
/// );
///
/// // 123_10 = 173_8
/// assert_eq!(
/// PowerOf2Digits::<Natural>::to_power_of_2_digits_asc(&Natural::from(123u32), 3)
/// .to_debug_string(),
/// "[3, 7, 1]"
/// );
/// ```
fn to_power_of_2_digits_asc(&self, log_base: u64) -> Vec<Natural> {
assert_ne!(log_base, 0);
if log_base <= Limb::WIDTH || self.limb_count() < 2 {
return PowerOf2Digits::<Limb>::to_power_of_2_digits_asc(
self,
min(log_base, Limb::WIDTH),
)
.iter()
.cloned()
.map(Natural::from)
.collect();
}
let limbs = match *self {
Natural(Large(ref limbs)) => limbs,
_ => unreachable!(),
};
let mut digits = Vec::new();
if let Some(log_log_base) = log_base.checked_log_base_2() {
assert!(log_log_base > Limb::LOG_WIDTH);
digits.extend(
limbs
.chunks(usize::power_of_2(log_log_base - Limb::LOG_WIDTH))
.map(Natural::from_limbs_asc),
);
} else {
let mut digit = Natural::ZERO;
let mut remaining_digit_bits = log_base;
for &limb in limbs {
let mut limb = limb;
let mut remaining_limb_bits = Limb::WIDTH;
while remaining_limb_bits != 0 {
let digit_index = log_base - remaining_digit_bits;
if remaining_limb_bits <= remaining_digit_bits {
digit.assign_bits(
digit_index,
digit_index + remaining_limb_bits,
&Natural::from(limb),
);
remaining_digit_bits -= remaining_limb_bits;
remaining_limb_bits = 0;
} else {
digit.assign_bits(digit_index, log_base, &Natural::from(limb));
limb >>= remaining_digit_bits;
remaining_limb_bits -= remaining_digit_bits;
remaining_digit_bits = 0;
}
if remaining_digit_bits == 0 {
digits.push(digit);
digit = Natural::ZERO;
remaining_digit_bits = log_base;
}
}
}
if digit != 0 {
digits.push(digit);
}
}
digits.truncate(digits.len() - slice_trailing_zeros(&digits));
digits
}
/// Returns a [`Vec`] containing the base-$2^k$ digits of a [`Natural`] in descending order:
/// most- to least-significant.
///
/// The base-2 logarithm of the base is specified. The type of each digit is [`Natural`]. If
/// the [`Natural`] is 0, the [`Vec`] is empty; otherwise, it begins with a nonzero digit.
///
/// $f(x, k) = (d_i)_ {i=0}^{n-1}$, where $0 \leq d_i < 2^k$ for all $i$, $n=0$ or
/// $d_0 \neq 0$, and
///
/// $$
/// \sum_{i=0}^{n-1}2^{k (n-i-1)}d_i = x.
/// $$
///
/// # 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()`.
///
/// # Panics
/// Panics if `log_base` is zero.
///
/// # Examples
/// ```
/// extern crate malachite_base;
///
/// use malachite_base::num::basic::traits::{Two, Zero};
/// use malachite_base::num::conversion::traits::PowerOf2Digits;
/// use malachite_base::strings::ToDebugString;
/// use malachite_nz::natural::Natural;
///
/// assert_eq!(
/// PowerOf2Digits::<Natural>::to_power_of_2_digits_desc(&Natural::ZERO, 6)
/// .to_debug_string(),
/// "[]"
/// );
/// assert_eq!(
/// PowerOf2Digits::<Natural>::to_power_of_2_digits_desc(&Natural::TWO, 6)
/// .to_debug_string(),
/// "[2]"
/// );
///
/// // 123_10 = 173_8
/// assert_eq!(
/// PowerOf2Digits::<Natural>::to_power_of_2_digits_desc(&Natural::from(123u32), 3)
/// .to_debug_string(),
/// "[1, 7, 3]"
/// );
/// ```
fn to_power_of_2_digits_desc(&self, log_base: u64) -> Vec<Natural> {
let mut digits = self.to_power_of_2_digits_asc(log_base);
digits.reverse();
digits
}
/// Converts an iterator of base-$2^k$ digits into a [`Natural`].
///
/// The base-2 logarithm of the base is specified. The input digits are in ascending order:
/// least- to most-significant. The type of each digit is [`Natural`].
///
/// If some digit is greater than $2^k$, `None` is returned.
///
/// $$
/// f((d_i)_ {i=0}^{n-1}, k) = \sum_{i=0}^{n-1}2^{ki}d_i.
/// $$
///
/// # Worst-case complexity
/// $T(n, m) = O(nm)$
///
/// $M(n, m) = O(nm)$
///
/// where $T$ is time, $M$ is additional memory, $n$ is `digits.count()`, and $m$ is
/// `log_base`.
///
/// # Panics
/// Panics if `log_base` is zero.
///
/// # Examples
/// ```
/// extern crate malachite_base;
///
/// use malachite_base::num::basic::traits::{One, Two, Zero};
/// use malachite_base::num::conversion::traits::PowerOf2Digits;
/// use malachite_base::strings::ToDebugString;
/// use malachite_nz::natural::Natural;
///
/// let digits = &[Natural::ZERO, Natural::ZERO, Natural::ZERO];
/// assert_eq!(
/// Natural::from_power_of_2_digits_asc(6, digits.iter().cloned()).to_debug_string(),
/// "Some(0)"
/// );
///
/// let digits = &[Natural::TWO, Natural::ZERO];
/// assert_eq!(
/// Natural::from_power_of_2_digits_asc(6, digits.iter().cloned()).to_debug_string(),
/// "Some(2)"
/// );
///
/// let digits = &[Natural::from(3u32), Natural::from(7u32), Natural::ONE];
/// assert_eq!(
/// Natural::from_power_of_2_digits_asc(3, digits.iter().cloned()).to_debug_string(),
/// "Some(123)"
/// );
///
/// let digits = &[Natural::from(100u32)];
/// assert_eq!(
/// Natural::from_power_of_2_digits_asc(3, digits.iter().cloned()).to_debug_string(),
/// "None"
/// );
/// ```
fn from_power_of_2_digits_asc<I: Iterator<Item = Natural>>(
log_base: u64,
digits: I,
) -> Option<Natural> {
assert_ne!(log_base, 0);
if let Some(log_log_base) = log_base.checked_log_base_2() {
let mut limbs = Vec::new();
match log_log_base.cmp(&Limb::LOG_WIDTH) {
Ordering::Equal => {
for digit in digits {
if digit.significant_bits() > log_base {
return None;
}
limbs.push(Limb::wrapping_from(&digit));
}
}
Ordering::Less => {
for chunk in &digits.chunks(usize::wrapping_from(Limb::WIDTH >> log_log_base)) {
let mut limb = 0;
let mut offset = 0;
for digit in chunk {
if digit.significant_bits() > log_base {
return None;
}
limb |= Limb::wrapping_from(&digit) << offset;
offset += log_base;
}
limbs.push(limb);
}
}
Ordering::Greater => {
let mut offset = 0;
let chunk_size = usize::wrapping_from(log_base >> Limb::LOG_WIDTH);
for digit in digits {
if digit.significant_bits() > log_base {
return None;
}
offset += chunk_size;
limbs.extend(digit.limbs());
limbs.resize(offset, 0);
}
}
}
Some(Natural::from_owned_limbs_asc(limbs))
} else {
let mut n = Natural::ZERO;
let mut previous_index = 0;
for digit in digits {
if digit.significant_bits() > log_base {
return None;
}
let index = previous_index + log_base;
n.assign_bits(previous_index, index, &digit);
previous_index = index;
}
Some(n)
}
}
/// Converts an iterator of base-$2^k$ digits into a [`Natural`].
///
/// The base-2 logarithm of the base is specified. The input digits are in descending order:
/// most- to least-significant. The type of each digit is [`Natural`].
///
/// If some digit is greater than $2^k$, `None` is returned.
///
/// $$
/// f((d_i)_ {i=0}^{n-1}, k) = \sum_{i=0}^{n-1}2^{k (n-i-1)}d_i.
/// $$
///
/// # Worst-case complexity
/// $T(n, m) = O(nm)$
///
/// $M(n, m) = O(nm)$
///
/// where $T$ is time, $M$ is additional memory, $n$ is `digits.count()`, and $m$ is
/// `log_base`.
///
/// # Panics
/// Panics if `log_base` is zero.
///
/// # Examples
/// ```
/// extern crate malachite_base;
///
/// use malachite_base::num::basic::traits::{One, Two, Zero};
/// use malachite_base::num::conversion::traits::PowerOf2Digits;
/// use malachite_base::strings::ToDebugString;
/// use malachite_nz::natural::Natural;
///
/// let digits = &[Natural::ZERO, Natural::ZERO, Natural::ZERO];
/// assert_eq!(
/// Natural::from_power_of_2_digits_desc(6, digits.iter().cloned()).to_debug_string(),
/// "Some(0)"
/// );
///
/// let digits = &[Natural::ZERO, Natural::TWO];
/// assert_eq!(
/// Natural::from_power_of_2_digits_desc(6, digits.iter().cloned()).to_debug_string(),
/// "Some(2)"
/// );
///
/// let digits = &[Natural::ONE, Natural::from(7u32), Natural::from(3u32)];
/// assert_eq!(
/// Natural::from_power_of_2_digits_desc(3, digits.iter().cloned()).to_debug_string(),
/// "Some(123)"
/// );
///
/// let digits = &[Natural::from(100u32)];
/// assert_eq!(
/// Natural::from_power_of_2_digits_desc(3, digits.iter().cloned()).to_debug_string(),
/// "None"
/// );
/// ```
fn from_power_of_2_digits_desc<I: Iterator<Item = Natural>>(
log_base: u64,
digits: I,
) -> Option<Natural> {
assert_ne!(log_base, 0);
if let Some(log_log_base) = log_base.checked_log_base_2() {
let mut limbs = Vec::new();
match log_log_base.cmp(&Limb::LOG_WIDTH) {
Ordering::Equal => {
for digit in digits {
if digit.significant_bits() > log_base {
return None;
}
limbs.push(Limb::wrapping_from(&digit));
}
limbs.reverse();
}
Ordering::Less => {
let digits = digits.collect_vec();
for chunk in digits.rchunks(usize::wrapping_from(Limb::WIDTH >> log_log_base)) {
let mut limb = 0;
let mut offset = 0;
for digit in chunk.iter().rev() {
if digit.significant_bits() > log_base {
return None;
}
limb |= Limb::wrapping_from(digit) << offset;
offset += log_base;
}
limbs.push(limb);
}
}
Ordering::Greater => {
let digits = digits.collect_vec();
let mut offset = 0;
let chunk_size = usize::wrapping_from(log_base >> Limb::LOG_WIDTH);
for digit in digits.iter().rev() {
if digit.significant_bits() > log_base {
return None;
}
offset += chunk_size;
limbs.extend(digit.limbs());
limbs.resize(offset, 0);
}
}
}
Some(Natural::from_owned_limbs_asc(limbs))
} else {
let digits = digits.collect_vec();
let mut n = Natural::ZERO;
let mut previous_index = 0;
for digit in digits.iter().rev() {
if digit.significant_bits() > log_base {
return None;
}
let index = previous_index + log_base;
n.assign_bits(previous_index, index, digit);
previous_index = index;
}
Some(n)
}
}
}
impl Natural {
pub_test! {to_power_of_2_digits_asc_natural_naive(&self, log_base: u64) -> Vec<Natural> {
assert_ne!(log_base, 0);
let digit_len = self
.significant_bits()
.div_round(log_base, RoundingMode::Ceiling);
let mut digits = Vec::with_capacity(usize::exact_from(digit_len));
let mut previous_index = 0;
for _ in 0..digit_len {
let index = previous_index + log_base;
digits.push(self.get_bits(previous_index, index));
previous_index = index;
}
digits
}}
pub_test! {from_power_of_2_digits_asc_natural_naive<I: Iterator<Item = Natural>>(
log_base: u64,
digits: I,
) -> Option<Natural> {
assert_ne!(log_base, 0);
let mut n = Natural::ZERO;
let mut previous_index = 0;
for digit in digits {
if digit.significant_bits() > log_base {
return None;
}
let index = previous_index + log_base;
n.assign_bits(previous_index, index, &digit);
previous_index = index;
}
Some(n)
}}
}