malachite-nz 0.13.0

The bignum types Natural and Integer, with efficient algorithms partially derived from GMP and FLINT.
Documentation
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
// Copyright © 2026 Mikhail Hogrefe
//
// Uses code adopted from the GNU MP Library.
//
//      Copyright © 1991, 1993, 1994, 1996, 2000-2002 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::InnerNatural::{Large, Small};
use crate::natural::{Natural, bit_to_limb_count_floor};
use crate::platform::Limb;
use alloc::vec::Vec;
use core::ops::{Shl, ShlAssign, Shr, ShrAssign};
use malachite_base::num::arithmetic::traits::{
    ArithmeticCheckedShl, OverflowingAddAssign, OverflowingSubAssign, 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::vecs::vec_pad_left;

// Interpreting a slice of `Limb`s as the limbs (in ascending order) of a `Natural`, returns the
// limbs of the `Natural` left-shifted by a `Limb`.
//
// # 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 `xs.len()`, and $m$ is `bits / Limb::WIDTH`.
//
// This is equivalent to `mpn_lshift` from `mpn/generic/lshift.c`, GMP 6.2.1, where the result is
// returned.
crate_test_fn! {limbs_shl(xs: &[Limb], bits: u64) -> Vec<Limb> {
    let small_bits = bits & Limb::WIDTH_MASK;
    let limb_offset = bit_to_limb_count_floor(bits);
    let xs_len = xs.len();
    // Allocating the full result up front and using the vectorizable kernel is much faster than
    // pushing one limb at a time (which is guaranteed to reallocate mid-shift).
    if small_bits == 0 {
        let mut out = vec![0; limb_offset + xs_len];
        out[limb_offset..].copy_from_slice(xs);
        out
    } else if xs_len == 0 {
        vec![0; limb_offset]
    } else {
        // Writing each limb exactly once via extend avoids vec![0; n]'s zero-init pass; this
        // measured up to 1.9x faster than zero-init-then-overwrite at large sizes (one store pass
        // instead of two).
        let cobits = Limb::WIDTH - small_bits;
        let mut out = Vec::with_capacity(limb_offset + xs_len + 1);
        out.resize(limb_offset, 0);
        out.push(xs[0] << small_bits);
        out.extend(
            xs.windows(2)
                .map(|w| (w[1] << small_bits) | (w[0] >> cobits)),
        );
        let remaining_bits = xs[xs_len - 1] >> cobits;
        if remaining_bits != 0 {
            out.push(remaining_bits);
        }
        out
    }
}}

// Interpreting a slice of `Limb`s as the limbs (in ascending order) of a `Natural`, writes the
// limbs of the `Natural` left-shifted by a `Limb` to an output slice. The output slice must be at
// least as long as the input slice. The `Limb` must be between 1 and `Limb::WIDTH` - 1, inclusive.
// The carry, or the bits that are shifted past the width of the input slice, is returned.
//
// # Worst-case complexity
// $T(n) = O(n)$
//
// $M(n) = O(n)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `xs.len()`.
//
// # Panics
// Panics if `out` is shorter than `xs`, `bits` is 0, or `bits` is greater than or equal to
// `Limb::WIDTH`.
//
// This is equivalent to `mpn_lshift` from `mpn/generic/lshift.c`, GMP 6.2.1.
crate_test_fn! {limbs_shl_to_out(out: &mut [Limb], xs: &[Limb], bits: u64) -> Limb {
    assert_ne!(bits, 0);
    assert!(bits < Limb::WIDTH);
    let len = xs.len();
    if len == 0 {
        return 0;
    }
    let cobits = Limb::WIDTH - bits;
    // Windows form: each output limb depends only on two adjacent input limbs, so iterations are
    // independent (no loop-carried value) and LLVM auto-vectorizes; this measured 2-2.4x faster
    // than the serial remaining_bits formulation.
    out[0] = xs[0] << bits;
    for (o, w) in out[1..len].iter_mut().zip(xs.windows(2)) {
        *o = (w[1] << bits) | (w[0] >> cobits);
    }
    xs[len - 1] >> cobits
}}

// Interpreting a slice of `Limb`s as the limbs (in ascending order) of a `Natural`, writes the
// limbs of the `Natural` left-shifted by a `Limb` to the input slice. The `Limb` must be between 1
// and `Limb::WIDTH` - 1, inclusive. The carry, or the bits that are shifted past the width of the
// input slice, is returned.
//
// # 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 is equivalent to `mpn_lshift` from `mpn/generic/lshift.c`, GMP 6.2.1, where `rp == up`.
crate_test_fn! {limbs_slice_shl_in_place(xs: &mut [Limb], bits: u64) -> Limb {
    assert_ne!(bits, 0);
    assert!(bits < Limb::WIDTH);
    let len = xs.len();
    if len == 0 {
        return 0;
    }
    let cobits = Limb::WIDTH - bits;
    // In-place windows form, descending so that each limb is read before it is overwritten;
    // iterations are independent (no loop-carried value), letting LLVM auto-vectorize.
    let remaining_bits = xs[len - 1] >> cobits;
    for i in (1..len).rev() {
        xs[i] = (xs[i] << bits) | (xs[i - 1] >> cobits);
    }
    xs[0] <<= bits;
    remaining_bits
}}

// Interpreting a nonempty `Vec` of `Limb`s as the limbs (in ascending order) of a `Natural`, writes
// the limbs of the `Natural` left-shifted by a `Limb` to the input `Vec`.
//
// # 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 `xs.len()`, and $m$ is `bits / Limb::WIDTH`.
//
// # Panics
// Panics if `xs` is empty.
//
// This is equivalent to `mpn_lshift` from `mpn/generic/lshift.c`, GMP 6.2.1, where `rp == up` and
// the carry is appended to `rp`.
crate_test_fn! {limbs_vec_shl_in_place(xs: &mut Vec<Limb>, bits: u64) {
    let small_bits = bits & Limb::WIDTH_MASK;
    let limb_offset = bit_to_limb_count_floor(bits);
    if small_bits == 0 {
        vec_pad_left(xs, limb_offset, 0);
        return;
    }
    let old_len = xs.len();
    if old_len == 0 {
        xs.resize(limb_offset, 0);
        return;
    }
    let cobits = Limb::WIDTH - small_bits;
    // A single descending pass both shifts and translates by limb_offset, rather than shifting in
    // place and then making a second full pass to insert the low zero limbs. Descending order
    // ensures every limb is read before being overwritten, and iterations are independent, letting
    // LLVM auto-vectorize.
    xs.resize(old_len + limb_offset + 1, 0);
    let remaining_bits = xs[old_len - 1] >> cobits;
    xs[old_len + limb_offset] = remaining_bits;
    for i in (1..old_len).rev() {
        xs[i + limb_offset] = (xs[i] << small_bits) | (xs[i - 1] >> cobits);
    }
    xs[limb_offset] = xs[0] << small_bits;
    xs[..limb_offset].fill(0);
    if remaining_bits == 0 {
        xs.pop();
    }
}}

// Interpreting a slice of `Limb`s as the limbs (in ascending order) of a `Natural`, writes the
// limbs of the `Natural` left-shifted by a `Limb`, and complemented, to an output slice. The output
// slice must be at least as long as the input slice. The `Limb` must be between 1 and `Limb::WIDTH`
// - 1, inclusive. The carry, or the bits that are shifted past the width of the input slice, is
// returned. The carry is not complemented.
//
// # Worst-case complexity
// $T(n) = O(n)$
//
// $M(n) = O(1)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `xs.len()`.
//
// # Panics
// Panics if `out` is shorter than `xs`, `xs` is empty, `bits` is 0, or `bits` is greater than or
// equal to `Limb::WIDTH`.
//
// This is equivalent to `mpn_lshiftc` from `mpn/generic/lshift.c`, GMP 6.2.1.
crate_test_fn! {limbs_shl_with_complement_to_out(
    out: &mut [Limb],
    xs: &[Limb],
    bits: u64
) -> Limb {
    let n = xs.len();
    assert_ne!(n, 0);
    assert_ne!(bits, 0);
    assert!(bits < Limb::WIDTH);
    let cobits = Limb::WIDTH - bits;
    // Windows form: iterations are independent, letting LLVM auto-vectorize.
    out[0] = !(xs[0] << bits);
    for (o, w) in out[1..n].iter_mut().zip(xs.windows(2)) {
        *o = !((w[1] << bits) | (w[0] >> cobits));
    }
    xs[n - 1] >> cobits
}}

// Interpreting two equal-length slices of `Limb`s as the limbs (in ascending order) of two
// `Natural`s x and y, writes the limbs of 2 ^ `bits` * x + y to the first slice and returns the
// highest limb of the result. `bits` must be between 1 and `Limb::WIDTH` - 1, inclusive.
//
// The shift is in windows form (each shifted limb is assembled from the two adjacent original
// limbs), so the addition's carry is the only loop-carried dependency, and the scratch space and
// second memory pass of a separate shift are saved.
//
// # Worst-case complexity
// $T(n) = O(n)$
//
// $M(n) = O(1)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `xs.len()`.
//
// # Panics
// Panics if `xs` and `ys` have different lengths, if `bits` is 0, or if `bits` is greater than or
// equal to `Limb::WIDTH`.
//
// This is equivalent to `mpn_addlsh_n` from GMP 6.3.0, where `rp == vp`. GMP provides this function
// as native assembly or macro fallbacks rather than as generic C code.
crate_test_fn! {limbs_shl_add_same_length_in_place_left(
    xs: &mut [Limb],
    ys: &[Limb],
    bits: u64
) -> Limb {
    assert_ne!(bits, 0);
    assert!(bits < Limb::WIDTH);
    assert_eq!(xs.len(), ys.len());
    let cobits = Limb::WIDTH - bits;
    let mut prev = 0;
    let mut carry = false;
    for (x, &y) in xs.iter_mut().zip(ys.iter()) {
        let shifted = (*x << bits) | (prev >> cobits);
        prev = *x;
        let (mut sum, carry_1) = shifted.overflowing_add(y);
        let carry_2 = sum.overflowing_add_assign(Limb::from(carry));
        *x = sum;
        carry = carry_1 | carry_2;
    }
    (prev >> cobits) + Limb::from(carry)
}}

// Interpreting two equal-length slices of `Limb`s as the limbs (in ascending order) of two
// `Natural`s x and y, writes the limbs of x + 2 ^ `bits` * y to the first slice and returns the
// highest limb of the result. `bits` must be between 1 and `Limb::WIDTH` - 1, inclusive.
//
// # Worst-case complexity
// $T(n) = O(n)$
//
// $M(n) = O(1)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `xs.len()`.
//
// # Panics
// Panics if `xs` and `ys` have different lengths, if `bits` is 0, or if `bits` is greater than or
// equal to `Limb::WIDTH`.
//
// This is equivalent to `mpn_addlsh_n` from GMP 6.3.0, where `rp == up`, and to `DO_mpn_addlsh_n`
// from `mpn/generic/toom_eval_pm2rexp.c`, GMP 6.2.1, but in a single pass with no scratch space.
crate_test_fn! {limbs_add_shl_same_length_in_place_left(
    xs: &mut [Limb],
    ys: &[Limb],
    bits: u64
) -> Limb {
    assert_ne!(bits, 0);
    assert!(bits < Limb::WIDTH);
    assert_eq!(xs.len(), ys.len());
    let cobits = Limb::WIDTH - bits;
    let mut prev = 0;
    let mut carry = false;
    for (x, &y) in xs.iter_mut().zip(ys.iter()) {
        let shifted = (y << bits) | (prev >> cobits);
        prev = y;
        let (mut sum, carry_1) = x.overflowing_add(shifted);
        let carry_2 = sum.overflowing_add_assign(Limb::from(carry));
        *x = sum;
        carry = carry_1 | carry_2;
    }
    (prev >> cobits) + Limb::from(carry)
}}

// Interpreting two equal-length slices of `Limb`s as the limbs (in ascending order) of two
// `Natural`s x and y, writes the lowest `xs.len()` limbs of 2 ^ `bits` * x + y to `out` and returns
// the highest limb of the result. `bits` must be between 1 and `Limb::WIDTH` - 1, inclusive.
//
// # Worst-case complexity
// $T(n) = O(n)$
//
// $M(n) = O(1)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `xs.len()`.
//
// # Panics
// Panics if `out` is shorter than `xs`, if `xs` and `ys` have different lengths, if `bits` is 0, or
// if `bits` is greater than or equal to `Limb::WIDTH`.
//
// This is equivalent to `mpn_addlsh_n` from GMP 6.3.0. GMP provides this function as native
// assembly or macro fallbacks rather than as generic C code.
crate_test_fn! {limbs_shl_add_same_length_to_out(
    out: &mut [Limb],
    xs: &[Limb],
    ys: &[Limb],
    bits: u64
) -> Limb {
    assert_ne!(bits, 0);
    assert!(bits < Limb::WIDTH);
    assert_eq!(xs.len(), ys.len());
    assert!(out.len() >= xs.len());
    let cobits = Limb::WIDTH - bits;
    let mut prev = 0;
    let mut carry = false;
    for ((o, &x), &y) in out.iter_mut().zip(xs.iter()).zip(ys.iter()) {
        let shifted = (x << bits) | (prev >> cobits);
        prev = x;
        let (mut sum, carry_1) = shifted.overflowing_add(y);
        let carry_2 = sum.overflowing_add_assign(Limb::from(carry));
        *o = sum;
        carry = carry_1 | carry_2;
    }
    (prev >> cobits) + Limb::from(carry)
}}

// Interpreting two equal-length slices of `Limb`s as the limbs (in ascending order) of two
// `Natural`s x and y, writes the lowest `xs.len()` limbs of x - 2 ^ `bits` * y to the first slice
// and returns the highest limb of 2 ^ `bits` * y plus the subtraction's borrow; the caller must
// subtract the returned limb from the part of x above `xs`. `bits` must be between 1 and
// `Limb::WIDTH` - 1, inclusive.
//
// # Worst-case complexity
// $T(n) = O(n)$
//
// $M(n) = O(1)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `xs.len()`.
//
// # Panics
// Panics if `xs` and `ys` have different lengths, if `bits` is 0, or if `bits` is greater than or
// equal to `Limb::WIDTH`.
//
// This is equivalent to `mpn_sublsh_n` from GMP 6.3.0, where `rp == up`, and to `DO_mpn_sublsh_n`
// from `mpn/generic/toom_interpolate_8pts.c`, GMP 6.2.1, but in a single pass with no scratch
// space.
crate_test_fn! {limbs_sub_shl_same_length_in_place_left(
    xs: &mut [Limb],
    ys: &[Limb],
    bits: u64
) -> Limb {
    assert_ne!(bits, 0);
    assert!(bits < Limb::WIDTH);
    assert_eq!(xs.len(), ys.len());
    let cobits = Limb::WIDTH - bits;
    let mut prev = 0;
    let mut borrow = false;
    for (x, &y) in xs.iter_mut().zip(ys.iter()) {
        let shifted = (y << bits) | (prev >> cobits);
        prev = y;
        let (mut diff, borrow_1) = x.overflowing_sub(shifted);
        let borrow_2 = diff.overflowing_sub_assign(Limb::from(borrow));
        *x = diff;
        borrow = borrow_1 | borrow_2;
    }
    (prev >> cobits) + Limb::from(borrow)
}}

// Interpreting two equal-length slices of `Limb`s as the limbs (in ascending order) of two
// `Natural`s x and y, writes the limbs of 2 ^ `bits` * x - y to the first slice and returns the
// highest limb of the result. `bits` must be between 1 and `Limb::WIDTH` - 1, inclusive, and 2 ^
// `bits` * x must be at least y.
//
// # Worst-case complexity
// $T(n) = O(n)$
//
// $M(n) = O(1)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `xs.len()`.
//
// # Panics
// Panics if `xs` and `ys` have different lengths, if `bits` is 0, or if `bits` is greater than or
// equal to `Limb::WIDTH`.
//
// This is equivalent to `mpn_rsblsh_n` from GMP 6.3.0, where `rp == vp`. GMP provides this function
// as native assembly or macro fallbacks rather than as generic C code.
crate_test_fn! {limbs_shl_sub_same_length_in_place_left(
    xs: &mut [Limb],
    ys: &[Limb],
    bits: u64
) -> Limb {
    assert_ne!(bits, 0);
    assert!(bits < Limb::WIDTH);
    assert_eq!(xs.len(), ys.len());
    let cobits = Limb::WIDTH - bits;
    let mut prev = 0;
    let mut borrow = false;
    for (x, &y) in xs.iter_mut().zip(ys.iter()) {
        let shifted = (*x << bits) | (prev >> cobits);
        prev = *x;
        let (mut diff, borrow_1) = shifted.overflowing_sub(y);
        let borrow_2 = diff.overflowing_sub_assign(Limb::from(borrow));
        *x = diff;
        borrow = borrow_1 | borrow_2;
    }
    (prev >> cobits) - Limb::from(borrow)
}}

// Interpreting two equal-length slices of `Limb`s as the limbs (in ascending order) of two
// `Natural`s x and y, writes the limbs of 2 ^ `bits` * x - y to the second slice and returns the
// highest limb of the result. `bits` must be between 1 and `Limb::WIDTH` - 1, inclusive, and 2 ^
// `bits` * x must be at least y.
//
// # Worst-case complexity
// $T(n) = O(n)$
//
// $M(n) = O(1)$
//
// where $T$ is time, $M$ is additional memory, and $n$ is `xs.len()`.
//
// # Panics
// Panics if `xs` and `ys` have different lengths, if `bits` is 0, or if `bits` is greater than or
// equal to `Limb::WIDTH`.
//
// This is equivalent to `mpn_rsblsh_n` from GMP 6.3.0, where `rp == up`. GMP provides this function
// as native assembly or macro fallbacks rather than as generic C code.
crate_test_fn! {limbs_shl_sub_same_length_in_place_right(
    xs: &[Limb],
    ys: &mut [Limb],
    bits: u64
) -> Limb {
    assert_ne!(bits, 0);
    assert!(bits < Limb::WIDTH);
    assert_eq!(xs.len(), ys.len());
    let cobits = Limb::WIDTH - bits;
    let mut prev = 0;
    let mut borrow = false;
    for (y, &x) in ys.iter_mut().zip(xs.iter()) {
        let shifted = (x << bits) | (prev >> cobits);
        prev = x;
        let (mut diff, borrow_1) = shifted.overflowing_sub(*y);
        let borrow_2 = diff.overflowing_sub_assign(Limb::from(borrow));
        *y = diff;
        borrow = borrow_1 | borrow_2;
    }
    (prev >> cobits) - Limb::from(borrow)
}}

fn shl_ref_unsigned<T: PrimitiveUnsigned>(x: &Natural, bits: T) -> Natural
where
    u64: ExactFrom<T>,
    Limb: ArithmeticCheckedShl<T, Output = Limb>,
{
    match (x, bits) {
        (&Natural::ZERO, _) => x.clone(),
        (_, bits) if bits == T::ZERO => x.clone(),
        (Natural(Small(small)), bits) => {
            Natural(if let Some(shifted) = small.arithmetic_checked_shl(bits) {
                Small(shifted)
            } else {
                Large(limbs_shl(&[*small], u64::exact_from(bits)))
            })
        }
        (Natural(Large(limbs)), bits) => Natural(Large(limbs_shl(limbs, u64::exact_from(bits)))),
    }
}

fn shl_assign<T: PrimitiveUnsigned>(x: &mut Natural, bits: T)
where
    u64: ExactFrom<T>,
    Limb: ArithmeticCheckedShl<T, Output = Limb>,
{
    match (&mut *x, bits) {
        (&mut Natural::ZERO, _) => {}
        (_, bits) if bits == T::ZERO => {}
        (Natural(Small(small)), bits) => {
            if let Some(shifted) = small.arithmetic_checked_shl(bits) {
                *small = shifted;
            } else {
                *x = Natural(Large(limbs_shl(&[*small], u64::exact_from(bits))));
            }
        }
        (Natural(Large(limbs)), bits) => {
            limbs_vec_shl_in_place(limbs, u64::exact_from(bits));
        }
    }
}

macro_rules! impl_natural_shl_unsigned {
    ($t:ident) => {
        impl Shl<$t> for Natural {
            type Output = Natural;

            /// Left-shifts a [`Natural`] (multiplies it by a power of 2), taking it by value.
            ///
            /// $f(x, k) = x2^k$.
            ///
            /// # 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 `bits`.
            ///
            /// # Examples
            /// See [here](super::shl#shl).
            #[inline]
            fn shl(mut self, bits: $t) -> Natural {
                self <<= bits;
                self
            }
        }

        impl Shl<$t> for &Natural {
            type Output = Natural;

            /// Left-shifts a [`Natural`] (multiplies it by a power of 2), taking it by reference.
            ///
            /// $f(x, k) = x2^k$.
            ///
            /// # 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 `bits`.
            ///
            /// # Examples
            /// See [here](super::shl#shl).
            #[inline]
            fn shl(self, bits: $t) -> Natural {
                shl_ref_unsigned(self, bits)
            }
        }

        impl ShlAssign<$t> for Natural {
            /// Left-shifts a [`Natural`] (multiplies it by a power of 2), in place.
            ///
            /// $x \gets x2^k$.
            ///
            /// # 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 `bits`.s
            ///
            /// # Examples
            /// See [here](super::shl#shl_assign).
            #[inline]
            fn shl_assign(&mut self, bits: $t) {
                shl_assign(self, bits);
            }
        }
    };
}
apply_to_unsigneds!(impl_natural_shl_unsigned);

fn shl_ref_signed<'a, U, S: PrimitiveSigned + UnsignedAbs<Output = U>>(
    x: &'a Natural,
    bits: S,
) -> Natural
where
    &'a Natural: Shl<U, Output = Natural> + Shr<U, Output = Natural>,
{
    if bits >= S::ZERO {
        x << bits.unsigned_abs()
    } else {
        x >> bits.unsigned_abs()
    }
}

fn shl_assign_signed<U, S: PrimitiveSigned + UnsignedAbs<Output = U>>(x: &mut Natural, bits: S)
where
    Natural: ShlAssign<U> + ShrAssign<U>,
{
    if bits >= S::ZERO {
        *x <<= bits.unsigned_abs();
    } else {
        *x >>= bits.unsigned_abs();
    }
}

macro_rules! impl_natural_shl_signed {
    ($t:ident) => {
        impl Shl<$t> for Natural {
            type Output = Natural;

            /// Left-shifts a [`Natural`] (multiplies it by a power of 2 or divides it by a power of
            /// 2 and takes the floor), taking it by value.
            ///
            /// $$
            /// f(x, k) = \lfloor x2^k \rfloor.
            /// $$
            ///
            /// # 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)`.
            ///
            /// # Examples
            /// See [here](super::shl#shl).
            #[inline]
            fn shl(mut self, bits: $t) -> Natural {
                self <<= bits;
                self
            }
        }

        impl<'a> Shl<$t> for &Natural {
            type Output = Natural;

            /// Left-shifts a [`Natural`] (multiplies it by a power of 2 or divides it by a power of
            /// 2 and takes the floor), taking it by reference.
            ///
            /// $$
            /// f(x, k) = \lfloor x2^k \rfloor.
            /// $$
            ///
            /// # 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)`.
            ///
            /// # Examples
            /// See [here](super::shl#shl).
            #[inline]
            fn shl(self, bits: $t) -> Natural {
                shl_ref_signed(self, bits)
            }
        }

        impl ShlAssign<$t> for Natural {
            /// Left-shifts a [`Natural`] (multiplies it by a power of 2 or divides it by a power of
            /// 2 and takes the floor), in place.
            ///
            /// $$
            /// x \gets \lfloor x2^k \rfloor.
            /// $$
            ///
            /// # 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)`.
            ///
            /// See [here](super::shl#shl_assign).
            #[inline]
            fn shl_assign(&mut self, bits: $t) {
                shl_assign_signed(self, bits);
            }
        }
    };
}
apply_to_signeds!(impl_natural_shl_signed);