malachite_nz/natural/arithmetic/shr_round.rs
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 726
// Copyright © 2025 Mikhail Hogrefe
//
// Uses code adopted from the GNU MP Library.
//
// Copyright © 1991, 1993, 1994, 1996, 1998, 1999, 2001, 2002, 2004, 2012, 2015 Free Software
// Foundation, Inc.
//
// 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::arithmetic::add::limbs_vec_add_limb_in_place;
use crate::natural::arithmetic::divisible_by_power_of_2::limbs_divisible_by_power_of_2;
use crate::natural::arithmetic::shr::{
limbs_shr, limbs_slice_shr_in_place, limbs_vec_shr_in_place,
};
use crate::natural::logic::bit_access::limbs_get_bit;
use crate::natural::InnerNatural::{Large, Small};
use crate::natural::Natural;
use crate::platform::Limb;
use alloc::vec::Vec;
use core::cmp::Ordering::{self, *};
use core::ops::{Shl, ShlAssign};
use malachite_base::num::arithmetic::traits::{Parity, ShrRound, ShrRoundAssign, UnsignedAbs};
use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::basic::signeds::PrimitiveSigned;
use malachite_base::num::basic::traits::Zero;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base::num::conversion::traits::ExactFrom;
use malachite_base::rounding_modes::RoundingMode::{self, *};
use malachite_base::slices::slice_test_zero;
use malachite_base::vecs::vec_delete_left;
// Interpreting a slice of `Limb`s as the limbs (in ascending order) of a `Natural`, returns the
// limbs of the `Natural` right-shifted by a `Limb`, rounding up. The limbs should not all be zero.
//
// # Worst-case complexity
// $T(n) = O(n)$
//
// $M(n) = O(n)$
//
// where $T$ is time, $M$ is additional memory and $n$ is `max(1, xs.len() - bits / Limb::WIDTH)`.
//
// This is equivalent to `cfdiv_q_2exp` from `mpz/cfdiv_q_2exp.c`, GMP 6.2.1, where `u` is
// non-negative, `dir == 1`, and the result is returned.
pub_test! {limbs_shr_round_up(xs: &[Limb], bits: u64) -> (Vec<Limb>, Ordering) {
let delete_count = usize::exact_from(bits >> Limb::LOG_WIDTH);
if delete_count >= xs.len() {
(vec![1], Greater)
} else {
let (xs_lo, xs_hi) = xs.split_at(delete_count);
let mut exact = slice_test_zero(xs_lo);
let mut out = xs_hi.to_vec();
let small_bits = bits & Limb::WIDTH_MASK;
if small_bits != 0 {
exact &= limbs_slice_shr_in_place(&mut out, small_bits) == 0;
}
if !exact {
limbs_vec_add_limb_in_place(&mut out, 1);
}
(
out,
if exact {
Equal
} else {
Greater
},
)
}
}}
// # Worst-case complexity
// $T(n) = O(n)$
//
// $M(n) = O(n)$
//
// where $T$ is time, $M$ is additional memory and $n$ is `max(1, xs.len() - bits / Limb::WIDTH)`.
fn limbs_shr_round_half_integer_to_even(xs: &[Limb], bits: u64) -> (Vec<Limb>, Ordering) {
let delete_count = usize::exact_from(bits >> Limb::LOG_WIDTH);
if delete_count >= xs.len() {
(Vec::new(), if slice_test_zero(xs) { Equal } else { Less })
} else {
let small_bits = bits & Limb::WIDTH_MASK;
let (xs_lo, xs_hi) = xs.split_at(delete_count);
let mut exact = slice_test_zero(xs_lo);
let mut out = xs_hi.to_vec();
if small_bits != 0 {
exact &= limbs_slice_shr_in_place(&mut out, small_bits) == 0;
}
if !out.is_empty() && out[0].odd() {
limbs_vec_add_limb_in_place(&mut out, 1);
(out, Greater)
} else {
(out, if exact { Equal } else { Less })
}
}
}
// Interpreting a slice of `Limb`s as the limbs (in ascending order) of a `Natural`, returns the
// limbs of the `Natural` right-shifted by a `Limb`, rounding to the `Natural` nearest to the actual
// value of `self` divided by `2 ^ bits`. If the actual value is exactly between two integers, it is
// rounded to the even one.
//
// # Worst-case complexity
// $T(n) = O(n)$
//
// $M(m) = O(m)$
//
// where $T$ is time, $M$ is additional memory, $n$ is `xs.len()`, and $m$ is `max(1, xs.len() -
// bits / Limb::WIDTH)`.
pub_test! {limbs_shr_round_nearest(xs: &[Limb], bits: u64) -> (Vec<Limb>, Ordering) {
if bits == 0 {
(xs.to_vec(), Equal)
} else {
let d = slice_test_zero(xs) || limbs_divisible_by_power_of_2(xs, bits - 1);
if !limbs_get_bit(xs, bits - 1) {
(
limbs_shr(xs, bits),
if d { Equal } else { Less },
)
} else if d {
limbs_shr_round_half_integer_to_even(xs, bits)
} else {
limbs_shr_round_up(xs, bits)
}
}
}}
// Interpreting a slice of `Limb`s as the limbs (in ascending order) of a `Natural`, returns the
// limbs of the `Natural` right-shifted by a `Limb`, if the shift is exact (doesn't remove any
// `true` bits). If the shift is inexact, `None` is returned. The limbs should not all be zero.
//
// # Worst-case complexity
// $T(n) = O(n)$
//
// $M(n) = O(m)$
//
// where $T$ is time, $M$ is additional memory, $n$ is `xs.len()`, and $m$ is `max(1, xs.len() -
// bits / Limb::WIDTH)`.
pub_test! {limbs_shr_exact(xs: &[Limb], bits: u64) -> Option<Vec<Limb>> {
if limbs_divisible_by_power_of_2(xs, bits) {
Some(limbs_shr(xs, bits))
} else {
None
}
}}
// Interpreting a slice of `Limb`s as the limbs (in ascending order) of a `Natural`, returns the
// limbs of the `Natural` right-shifted by a `Limb`, rounded using a specified rounding format. The
// limbs should not all be zero.
//
// # Worst-case complexity
// $T(n) = O(n)$
//
// $M(m) = O(m)$
//
// where $T$ is time, $M$ is additional memory, $n$ is `xs.len()`, and $m$ is `max(1, xs.len() -
// bits / Limb::WIDTH)`.
pub_test! {
limbs_shr_round(xs: &[Limb], bits: u64, rm: RoundingMode) -> Option<(Vec<Limb>, Ordering)> {
match rm {
Down | Floor => Some((
limbs_shr(xs, bits),
if limbs_divisible_by_power_of_2(xs, bits) {
Equal
} else {
Less
},
)),
Up | Ceiling => Some(limbs_shr_round_up(xs, bits)),
Nearest => Some(limbs_shr_round_nearest(xs, bits)),
Exact => limbs_shr_exact(xs, bits).map(|ss| (ss, Equal)),
}
}}
// Interpreting a `Vec` of `Limb`s as the limbs (in ascending order) of a `Natural`, writes the
// limbs of the `Natural` right-shifted by a `Limb`, rounding up, to the input `Vec`. The limbs
// should not all be zero.
//
// # Worst-case complexity
// $T(n) = O(n)$
//
// $M(n) = O(1)$
//
// where $T$ is time, $M$ is additional memory and $n$ is `max(1, xs.len() - bits / Limb::WIDTH)`.
//
// This is equivalent to `cfdiv_q_2exp` from `mpz/cfdiv_q_2exp.c`, GMP 6.2.1, where `u` is
// non-negative, `dir == 1`, and `w == u`.
pub_test! {limbs_vec_shr_round_up_in_place(xs: &mut Vec<Limb>, bits: u64) -> Ordering {
let delete_count = usize::exact_from(bits >> Limb::LOG_WIDTH);
if delete_count >= xs.len() {
xs.truncate(1);
xs[0] = 1;
Greater
} else {
let mut exact = slice_test_zero(&xs[..delete_count]);
let small_bits = bits & Limb::WIDTH_MASK;
vec_delete_left(xs, delete_count);
if small_bits != 0 {
exact &= limbs_slice_shr_in_place(xs, small_bits) == 0;
}
if !exact {
limbs_vec_add_limb_in_place(xs, 1);
}
if exact {
Equal
} else {
Greater
}
}
}}
// # Worst-case complexity
// $T(n) = O(n)$
//
// $M(n) = O(1)$
//
// where $T$ is time, $M$ is additional memory and $n$ is `max(1, xs.len() - bits / Limb::WIDTH)`.
fn limbs_vec_shr_round_half_integer_to_even_in_place(xs: &mut Vec<Limb>, bits: u64) -> Ordering {
let delete_count = usize::exact_from(bits >> Limb::LOG_WIDTH);
if delete_count >= xs.len() {
let o = if slice_test_zero(xs) { Equal } else { Less };
xs.clear();
o
} else {
let small_bits = bits & Limb::WIDTH_MASK;
let mut exact = slice_test_zero(&xs[..delete_count]);
vec_delete_left(xs, delete_count);
if small_bits != 0 {
exact &= limbs_slice_shr_in_place(xs, small_bits) == 0;
}
if !xs.is_empty() && xs[0].odd() {
limbs_vec_add_limb_in_place(xs, 1);
Greater
} else if exact {
Equal
} else {
Less
}
}
}
// Interpreting a `Vec` of `Limb`s as the limbs (in ascending order) of a `Natural`, writes the
// limbs of the `Natural` right-shifted by a `Limb` to the input `Vec`, rounding to the `Natural`
// nearest to the actual value of `self` divided by `2 ^ bits`. If the actual value is exactly
// between two integers, it is rounded to the even one.
//
// # Worst-case complexity
// $T(n) = O(n)$
//
// $M(n) = O(1)$
//
// where $T$ is time, $M$ is additional memory and $n$ is `xs.len()`.
pub_test! {limbs_vec_shr_round_nearest_in_place(xs: &mut Vec<Limb>, bits: u64) -> Ordering {
if bits == 0 {
Equal
} else {
let d = slice_test_zero(xs) || limbs_divisible_by_power_of_2(xs, bits - 1);
if !limbs_get_bit(xs, bits - 1) {
limbs_vec_shr_in_place(xs, bits);
if d {
Equal
} else {
Less
}
} else if d {
limbs_vec_shr_round_half_integer_to_even_in_place(xs, bits)
} else {
limbs_vec_shr_round_up_in_place(xs, bits)
}
}
}}
// Interpreting a `Vec` of `Limb`s as the limbs (in ascending order) of a `Natural`, writes the
// limbs of the `Natural` right-shifted by a `Limb` to the input `Vec`, if the shift is exact
// (doesn't remove any `true` bits). Returns whether the shift was exact. The limbs should not all
// be 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()`.
pub_test! {limbs_vec_shr_exact_in_place(xs: &mut Vec<Limb>, bits: u64) -> bool {
if limbs_divisible_by_power_of_2(xs, bits) {
limbs_vec_shr_in_place(xs, bits);
true
} else {
false
}
}}
// Interpreting a slice of `Limb`s as the limbs (in ascending order) of a `Natural`, writes the
// limbs of the `Natural` right-shifted by a `Limb` to the input `Vec`, rounded using a specified
// rounding format. If the shift is inexact (removes some `true` bits) and the `RoundingMode` is
// `Exact`, the value of `xs` becomes unspecified and `false` is returned. Otherwise, `true` is
// returned. The limbs should not all be 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()`.
pub_test! {limbs_vec_shr_round_in_place(
xs: &mut Vec<Limb>,
bits: u64,
rm: RoundingMode,
) -> (bool, Ordering) {
match rm {
Down | Floor => {
let exact = limbs_divisible_by_power_of_2(xs, bits);
limbs_vec_shr_in_place(xs, bits);
(
true,
if exact {
Equal
} else {
Less
},
)
}
Up | Ceiling => {
(true, limbs_vec_shr_round_up_in_place(xs, bits))
}
Nearest => (true, limbs_vec_shr_round_nearest_in_place(xs, bits)),
Exact => (limbs_vec_shr_exact_in_place(xs, bits), Equal),
}
}}
fn shr_round_unsigned_ref_n<T: PrimitiveUnsigned>(
x: &Natural,
bits: T,
rm: RoundingMode,
) -> (Natural, Ordering)
where
u64: ExactFrom<T>,
Limb: ShrRound<T, Output = Limb>,
{
match (x, bits) {
(&Natural::ZERO, _) => (x.clone(), Equal),
(_, bits) if bits == T::ZERO => (x.clone(), Equal),
(Natural(Small(ref small)), bits) => {
let (s, o) = small.shr_round(bits, rm);
(Natural(Small(s)), o)
}
(Natural(Large(ref limbs)), bits) => {
if let Some((out, o)) = limbs_shr_round(limbs, u64::exact_from(bits), rm) {
(Natural::from_owned_limbs_asc(out), o)
} else {
panic!("Right shift is not exact: {x} >> {bits}");
}
}
}
}
fn shr_round_assign_unsigned_n<T: PrimitiveUnsigned>(
x: &mut Natural,
bits: T,
rm: RoundingMode,
) -> Ordering
where
u64: ExactFrom<T>,
Limb: ShrRoundAssign<T>,
{
match (&mut *x, bits) {
(&mut Natural::ZERO, _) => Equal,
(_, bits) if bits == T::ZERO => Equal,
(Natural(Small(ref mut small)), bits) => small.shr_round_assign(bits, rm),
(Natural(Large(ref mut limbs)), bits) => {
let (b, o) = limbs_vec_shr_round_in_place(limbs, u64::exact_from(bits), rm);
assert!(b, "Right shift is not exact.");
x.trim();
o
}
}
}
macro_rules! impl_natural_shr_round_unsigned {
($t:ident) => {
impl ShrRound<$t> for Natural {
type Output = Natural;
/// Shifts a [`Natural`] right (divides it by a power of 2), taking it by value, and
/// rounds according to the specified rounding mode. An [`Ordering`] is also returned,
/// indicating whether the returned value is less than, equal to, or greater than the
/// exact value.
///
/// Passing `Floor` or `Down` is equivalent to using `>>`. To test whether `Exact` can
/// be passed, use `self.divisible_by_power_of_2(bits)`.
///
/// Let $q = \frac{x}{2^k}$, and let $g$ be the function that just returns the first
/// element of the pair, without the [`Ordering`]:
///
/// $f(x, k, \mathrm{Down}) = f(x, y, \mathrm{Floor}) = \lfloor q \rfloor.$
///
/// $f(x, k, \mathrm{Up}) = f(x, y, \mathrm{Ceiling}) = \lceil q \rceil.$
///
/// $$
/// f(x, k, \mathrm{Nearest}) = \begin{cases}
/// \lfloor q \rfloor & \text{if}
/// \\quad q - \lfloor q \rfloor < \frac{1}{2}, \\\\
/// \lceil q \rceil & \text{if}
/// \\quad q - \lfloor q \rfloor > \frac{1}{2}, \\\\
/// \lfloor q \rfloor & \text{if} \\quad q - \lfloor q \rfloor =
/// \frac{1}{2} \\ \text{and} \\ \lfloor q \rfloor
/// \\ \text{is even}, \\\\
/// \lceil q \rceil &
/// \text{if} \\quad q - \lfloor q \rfloor = \frac{1}{2} \\ \text{and}
/// \\ \lfloor q \rfloor \\ \text{is odd}.
/// \end{cases}
/// $$
///
/// $f(x, k, \mathrm{Exact}) = q$, but panics if $q \notin \N$.
///
/// Then
///
/// $f(x, k, r) = (g(x, k, r), \operatorname{cmp}(g(x, k, r), q))$.
///
/// # 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()`.
///
/// # Panics
/// Let $k$ be `bits`. Panics if `rm` is `Exact` but `self` is not divisible by $2^k$.
///
/// # Examples
/// See [here](super::shr_round#shr_round).
#[inline]
fn shr_round(mut self, bits: $t, rm: RoundingMode) -> (Natural, Ordering) {
let o = self.shr_round_assign(bits, rm);
(self, o)
}
}
impl<'a> ShrRound<$t> for &Natural {
type Output = Natural;
/// Shifts a [`Natural`] right (divides it by a power of 2), taking it by reference, and
/// rounds according to the specified rounding mode. An [`Ordering`] is also returned,
/// indicating whether the returned value is less than, equal to, or greater than the
/// exact value.
///
/// Passing `Floor` or `Down` is equivalent to using `>>`. To test whether `Exact` can
/// be passed, use `self.divisible_by_power_of_2(bits)`.
///
/// Let $q = \frac{x}{2^k}$, and let $g$ be the function that just returns the first
/// element of the pair, without the [`Ordering`]:
///
/// $f(x, k, \mathrm{Down}) = f(x, y, \mathrm{Floor}) = \lfloor q \rfloor.$
///
/// $f(x, k, \mathrm{Up}) = f(x, y, \mathrm{Ceiling}) = \lceil q \rceil.$
///
/// $$
/// f(x, k, \mathrm{Nearest}) = \begin{cases}
/// \lfloor q \rfloor & \text{if}
/// \\quad q - \lfloor q \rfloor < \frac{1}{2}, \\\\
/// \lceil q \rceil & \text{if}
/// \\quad q - \lfloor q \rfloor > \frac{1}{2}, \\\\
/// \lfloor q \rfloor & \text{if} \\quad q - \lfloor q \rfloor =
/// \frac{1}{2} \\ \text{and} \\ \lfloor q \rfloor
/// \\ \text{is even}, \\\\
/// \lceil q \rceil &
/// \text{if} \\quad q - \lfloor q \rfloor = \frac{1}{2} \\ \text{and}
/// \\ \lfloor q \rfloor \\ \text{is odd}.
/// \end{cases}
/// $$
///
/// $f(x, k, \mathrm{Exact}) = q$, but panics if $q \notin \N$.
///
/// Then
///
/// $f(x, k, r) = (g(x, k, r), \operatorname{cmp}(g(x, k, r), q))$.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(m) = O(m)$
///
/// where $T$ is time, $M$ is additional memory, $n$ is `self.significant_bits()`, and
/// $m$ is `max(1, self.significant_bits() - bits)`.
///
/// # Panics
/// Let $k$ be `bits`. Panics if `rm` is `Exact` but `self` is not divisible by $2^k$.
///
/// # Examples
/// See [here](super::shr_round#shr_round).
#[inline]
fn shr_round(self, bits: $t, rm: RoundingMode) -> (Natural, Ordering) {
shr_round_unsigned_ref_n(self, bits, rm)
}
}
impl ShrRoundAssign<$t> for Natural {
/// Shifts a [`Natural`] right (divides it by a power of 2) and rounds according to the
/// specified rounding mode, in place. An [`Ordering`] is returned, indicating whether
/// the assigned value is less than, equal to, or greater than the exact value.
///
/// Passing `Floor` or `Down` is equivalent to using `>>=`. To test whether `Exact` can
/// be passed, use `self.divisible_by_power_of_2(bits)`.
///
/// See the [`ShrRound`] documentation for details.
///
/// # 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()`.
///
/// # Panics
/// Let $k$ be `bits`. Panics if `rm` is `Exact` but `self` is not divisible by $2^k$.
///
/// # Examples
/// See [here](super::shr_round#shr_round_assign).
#[inline]
fn shr_round_assign(&mut self, bits: $t, rm: RoundingMode) -> Ordering {
shr_round_assign_unsigned_n(self, bits, rm)
}
}
};
}
apply_to_unsigneds!(impl_natural_shr_round_unsigned);
fn shr_round_signed_ref_n<'a, U, S: PrimitiveSigned + UnsignedAbs<Output = U>>(
x: &'a Natural,
bits: S,
rm: RoundingMode,
) -> (Natural, Ordering)
where
&'a Natural: Shl<U, Output = Natural> + ShrRound<U, Output = Natural>,
{
if bits >= S::ZERO {
x.shr_round(bits.unsigned_abs(), rm)
} else {
(x << bits.unsigned_abs(), Equal)
}
}
fn shr_round_assign_signed_n<U, S: PrimitiveSigned + UnsignedAbs<Output = U>>(
x: &mut Natural,
bits: S,
rm: RoundingMode,
) -> Ordering
where
Natural: ShlAssign<U> + ShrRoundAssign<U>,
{
if bits >= S::ZERO {
x.shr_round_assign(bits.unsigned_abs(), rm)
} else {
*x <<= bits.unsigned_abs();
Equal
}
}
macro_rules! impl_natural_shr_round_signed {
($t:ident) => {
impl ShrRound<$t> for Natural {
type Output = Natural;
/// Shifts a [`Natural`] right (divides or multiplies it by a power of 2), taking it by
/// value, and rounds according to the specified rounding mode. An [`Ordering`] is also
/// returned, indicating whether the returned value is less than, equal to, or greater
/// than the exact value. If `bits` is negative, then the returned [`Ordering`] is
/// always `Equal`, even if the higher bits of the result are lost.
///
/// Passing `Floor` or `Down` is equivalent to using `>>`. To test whether `Exact` can
/// be passed, use `self.divisible_by_power_of_2(bits)`.
///
/// Let $q = \frac{x}{2^k}$, and let $g$ be the function that just returns the first
/// element of the pair, without the [`Ordering`]:
///
/// $f(x, k, \mathrm{Down}) = f(x, y, \mathrm{Floor}) = \lfloor q \rfloor.$
///
/// $f(x, k, \mathrm{Up}) = f(x, y, \mathrm{Ceiling}) = \lceil q \rceil.$
///
/// $$
/// f(x, k, \mathrm{Nearest}) = \begin{cases}
/// \lfloor q \rfloor & \text{if}
/// \\quad q - \lfloor q \rfloor < \frac{1}{2}, \\\\
/// \lceil q \rceil & \text{if}
/// \\quad q - \lfloor q \rfloor > \frac{1}{2}, \\\\
/// \lfloor q \rfloor & \text{if} \\quad q - \lfloor q \rfloor =
/// \frac{1}{2} \\ \text{and} \\ \lfloor q \rfloor
/// \\ \text{is even}, \\\\
/// \lceil q \rceil &
/// \text{if} \\quad q - \lfloor q \rfloor = \frac{1}{2} \\ \text{and}
/// \\ \lfloor q \rfloor \\ \text{is odd}.
/// \end{cases}
/// $$
///
/// $f(x, k, \mathrm{Exact}) = q$, but panics if $q \notin \N$.
///
/// Then
///
/// $f(x, k, r) = (g(x, k, r), \operatorname{cmp}(g(x, k, r), q))$.
///
/// # Worst-case complexity
/// $T(n, m) = O(n + m)$
///
/// $M(n, m) = O(n + m)$
///
/// where $T$ is time, $M$ is additional memory, $n$ is `self.significant_bits()`, and
/// $m$ is `max(-bits, 0)`.
///
/// # Panics
/// Let $k$ be `bits`. Panics if $k$ is positive and `rm` is `Exact` but `self` is not
/// divisible by $2^k$.
///
/// # Examples
/// See [here](super::shr_round#shr_round).
#[inline]
fn shr_round(mut self, bits: $t, rm: RoundingMode) -> (Natural, Ordering) {
let o = self.shr_round_assign(bits, rm);
(self, o)
}
}
impl<'a> ShrRound<$t> for &Natural {
type Output = Natural;
/// Shifts a [`Natural`] right (divides or multiplies it by a power of 2), taking it by
/// reference, and rounds according to the specified rounding mode. An [`Ordering`] is
/// also returned, indicating whether the returned value is less than, equal to, or
/// greater than the exact value. If `bits` is negative, then the returned [`Ordering`]
/// is always `Equal`, even if the higher bits of the result are lost.
///
/// Passing `Floor` or `Down` is equivalent to using `>>`. To test whether `Exact` can
/// be passed, use `self.divisible_by_power_of_2(bits)`.
///
/// Let $q = \frac{x}{2^k}$, and let $g$ be the function that just returns the first
/// element of the pair, without the [`Ordering`]:
///
/// $f(x, k, \mathrm{Down}) = f(x, y, \mathrm{Floor}) = \lfloor q \rfloor.$
///
/// $f(x, k, \mathrm{Up}) = f(x, y, \mathrm{Ceiling}) = \lceil q \rceil.$
///
/// $$
/// f(x, k, \mathrm{Nearest}) = \begin{cases}
/// \lfloor q \rfloor & \text{if}
/// \\quad q - \lfloor q \rfloor < \frac{1}{2}, \\\\
/// \lceil q \rceil & \text{if}
/// \\quad q - \lfloor q \rfloor > \frac{1}{2}, \\\\
/// \lfloor q \rfloor & \text{if} \\quad q - \lfloor q \rfloor =
/// \frac{1}{2} \\ \text{and} \\ \lfloor q \rfloor
/// \\ \text{is even}, \\\\
/// \lceil q \rceil &
/// \text{if} \\quad q - \lfloor q \rfloor = \frac{1}{2} \\ \text{and}
/// \\ \lfloor q \rfloor \\ \text{is odd}.
/// \end{cases}
/// $$
///
/// $f(x, k, \mathrm{Exact}) = q$, but panics if $q \notin \N$.
///
/// Then
///
/// $f(x, k, r) = (g(x, k, r), \operatorname{cmp}(g(x, k, r), q))$.
///
/// # Worst-case complexity
/// $T(n, m) = O(n + m)$
///
/// $M(n, m) = O(n + m)$
///
/// where $T$ is time, $M$ is additional memory, $n$ is `self.significant_bits()`, and
/// $m$ is `max(-bits, 0)`.
///
/// # Worst-case complexity
/// $T(n, m) = O(n + m)$
///
/// $M(n, m) = O(n + m)$
///
/// where $T$ is time, $M$ is additional memory, $n$ is `self.significant_bits()`, and
/// $m$ is `max(-bits, 0)`.
///
/// # Panics
/// Let $k$ be `bits`. Panics if $k$ is positive and `rm` is `Exact` but `self` is not
/// divisible by $2^k$.
///
/// # Examples
/// See [here](super::shr_round#shr_round).
#[inline]
fn shr_round(self, bits: $t, rm: RoundingMode) -> (Natural, Ordering) {
shr_round_signed_ref_n(self, bits, rm)
}
}
impl ShrRoundAssign<$t> for Natural {
/// Shifts a [`Natural`] right (divides or multiplies it by a power of 2) and rounds
/// according to the specified rounding mode, in place. An [`Ordering`] is returned,
/// indicating whether the assigned value is less than, equal to, or greater than the
/// exact value. If `bits` is negative, then the returned [`Ordering`] is always
/// `Equal`, even if the higher bits of the result are lost.
///
/// Passing `Floor` or `Down` is equivalent to using `>>`. To test whether `Exact` can
/// be passed, use `self.divisible_by_power_of_2(bits)`.
///
/// See the [`ShrRound`] documentation for details.
///
/// # Worst-case complexity
/// $T(n, m) = O(n + m)$
///
/// $M(n, m) = O(n + m)$
///
/// where $T$ is time, $M$ is additional memory, $n$ is `self.significant_bits()`, and
/// $m$ is `max(-bits, 0)`.
///
/// # Panics
/// Let $k$ be `bits`. Panics if $k$ is positive and `rm` is `Exact` but `self` is not
/// divisible by $2^k$.
///
/// # Examples
/// See [here](super::shr_round#shr_round_assign).
#[inline]
fn shr_round_assign(&mut self, bits: $t, rm: RoundingMode) -> Ordering {
shr_round_assign_signed_n(self, bits, rm)
}
}
};
}
apply_to_signeds!(impl_natural_shr_round_signed);