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
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
// Copyright © 2018–2020 Trevor Spiteri

// This library is free software: you can redistribute it and/or
// modify it under the terms of either
//
//   * the Apache License, Version 2.0 or
//   * the MIT License
//
// at your option.
//
// You should have recieved copies of the Apache License and the MIT
// License along with the library. If not, see
// <https://www.apache.org/licenses/LICENSE-2.0> and
// <https://opensource.org/licenses/MIT>.

#![allow(clippy::suspicious_op_assign_impl)]

use crate::{
    from_str::ParseFixedError,
    traits::{Fixed, FixedSigned, FixedUnsigned, FromFixed, ToFixed},
    types::extra::{LeEqU128, LeEqU16, LeEqU32, LeEqU64, LeEqU8},
    FixedI128, FixedI16, FixedI32, FixedI64, FixedI8, FixedU128, FixedU16, FixedU32, FixedU64,
    FixedU8,
};
use core::{
    fmt::{Display, Formatter, Result as FmtResult},
    iter::{Product, Sum},
    mem,
    ops::{
        Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div,
        DivAssign, Mul, MulAssign, Neg, Not, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub,
        SubAssign,
    },
    str::FromStr,
};

/// Provides intentionally wrapped arithmetic on fixed-point numbers.
///
/// The underlying value can be retrieved through the `.0` index.
///
/// # Examples
///
/// ```rust
/// use fixed::{types::I16F16, Wrapping};
/// let max = Wrapping(I16F16::MAX);
/// let delta = Wrapping(I16F16::from_bits(1));
/// assert_eq!(I16F16::MIN, (max + delta).0);
/// ```
#[repr(transparent)]
#[derive(Clone, Copy, Default, Hash, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub struct Wrapping<F>(pub F);

impl<F: Fixed> Wrapping<F> {
    /// The smallest value that can be represented.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I16F16, Wrapping};
    /// assert_eq!(Wrapping::<I16F16>::MIN, Wrapping(I16F16::MIN));
    /// ```
    pub const MIN: Wrapping<F> = Wrapping(F::MIN);

    /// The largest value that can be represented.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I16F16, Wrapping};
    /// assert_eq!(Wrapping::<I16F16>::MAX, Wrapping(I16F16::MAX));
    /// ```
    pub const MAX: Wrapping<F> = Wrapping(F::MAX);

    /// The number of integer bits.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I16F16, Wrapping};
    /// assert_eq!(Wrapping::<I16F16>::INT_NBITS, I16F16::INT_NBITS);
    /// ```
    pub const INT_NBITS: u32 = F::INT_NBITS;

    /// The number of fractional bits.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I16F16, Wrapping};
    /// assert_eq!(Wrapping::<I16F16>::FRAC_NBITS, I16F16::FRAC_NBITS);
    /// ```
    pub const FRAC_NBITS: u32 = F::FRAC_NBITS;

    /// Creates a fixed-point number that has a bitwise representation
    /// identical to the given integer.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I16F16, Wrapping};
    /// assert_eq!(Wrapping::<I16F16>::from_bits(0x1C), Wrapping(I16F16::from_bits(0x1C)));
    /// ```
    #[inline]
    pub fn from_bits(bits: F::Bits) -> Wrapping<F> {
        Wrapping(F::from_bits(bits))
    }

    /// Creates an integer that has a bitwise representation identical
    /// to the given fixed-point number.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I16F16, Wrapping};
    /// let w = Wrapping(I16F16::from_bits(0x1C));
    /// assert_eq!(w.to_bits(), 0x1C);
    /// ```
    #[inline]
    pub fn to_bits(self) -> F::Bits {
        self.0.to_bits()
    }

    /// Wrapping conversion from another number.
    ///
    /// The other number can be:
    ///
    ///   * A fixed-point number. Any extra fractional bits are
    ///     discarded, which rounds towards −∞.
    ///   * An integer of type [`i8`], [`i16`], [`i32`], [`i64`], [`i128`],
    ///     [`isize`], [`u8`], [`u16`], [`u32`], [`u64`], [`u128`], or
    ///     [`usize`].
    ///   * A floating-point number of type [`f32`] or [`f64`]. If the
    ///     [`f16` feature] is enabled, it can also be of type [`f16`]
    ///     or [`bf16`]. For this conversion, the method rounds to the
    ///     nearest, with ties rounding to even.
    ///   * Any other number `src` for which [`ToFixed`] is implemented, in
    ///     which case this method returns
    ///     <code>[Wrapping][`Wrapping`]([src.wrapping_to_fixed()][`wrapping_to_fixed`])</code>.
    ///
    /// # Panics
    ///
    /// For floating-point numbers, panics if the value is not [finite].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{
    ///     types::{I4F4, I16F16},
    ///     Wrapping,
    /// };
    ///
    /// // 0x1234.5678 wraps into 0x4.5
    /// let src = I16F16::from_bits(0x1234_5678);
    /// let dst = Wrapping::<I4F4>::from_num(src);
    /// assert_eq!(dst, Wrapping(I4F4::from_bits(0x45)));
    ///
    /// // 0x1234 wraps into 0x4.0
    /// let src_int = 0x1234_i32;
    /// let dst_int = Wrapping::<I4F4>::from_num(src_int);
    /// assert_eq!(dst_int, Wrapping(I4F4::from_bits(0x40)));
    ///
    /// // 129.75 wrapped into 1.75 (binary 1.1100)
    /// let src_float = 129.75;
    /// let dst_float = Wrapping::<I4F4>::from_num(src_float);
    /// assert_eq!(dst_float, Wrapping(I4F4::from_bits(0b11100)));
    /// ```
    ///
    /// [`ToFixed`]: traits/trait.ToFixed.html
    /// [`Wrapping`]: struct.Wrapping.html
    /// [`bf16`]: https://docs.rs/half/^1.2/half/struct.bf16.html
    /// [`f16` feature]: index.html#optional-features
    /// [`f16`]: https://docs.rs/half/^1.2/half/struct.f16.html
    /// [`f32`]: https://doc.rust-lang.org/nightly/std/primitive.f32.html
    /// [`f64`]: https://doc.rust-lang.org/nightly/std/primitive.f64.html
    /// [`i128`]: https://doc.rust-lang.org/nightly/std/primitive.i128.html
    /// [`i16`]: https://doc.rust-lang.org/nightly/std/primitive.i16.html
    /// [`i32`]: https://doc.rust-lang.org/nightly/std/primitive.i32.html
    /// [`i64`]: https://doc.rust-lang.org/nightly/std/primitive.i64.html
    /// [`i8`]: https://doc.rust-lang.org/nightly/std/primitive.i8.html
    /// [`isize`]: https://doc.rust-lang.org/nightly/std/primitive.isize.html
    /// [`wrapping_to_fixed`]: traits/trait.ToFixed.html#tymethod.wrapping_to_fixed
    /// [`u128`]: https://doc.rust-lang.org/nightly/std/primitive.u128.html
    /// [`u16`]: https://doc.rust-lang.org/nightly/std/primitive.u16.html
    /// [`u32`]: https://doc.rust-lang.org/nightly/std/primitive.u32.html
    /// [`u64`]: https://doc.rust-lang.org/nightly/std/primitive.u64.html
    /// [`u8`]: https://doc.rust-lang.org/nightly/std/primitive.u8.html
    /// [`usize`]: https://doc.rust-lang.org/nightly/std/primitive.usize.html
    /// [finite]: https://doc.rust-lang.org/nightly/std/primitive.f64.html#method.is_finite
    #[inline]
    pub fn from_num<Src: ToFixed>(src: Src) -> Wrapping<F> {
        Wrapping(src.wrapping_to_fixed())
    }

    /// Converts a fixed-point number to another number, wrapping the
    /// value on overflow.
    ///
    /// The other number can be:
    ///
    ///   * Another fixed-point number. Any extra fractional bits are
    ///     discarded, which rounds towards −∞.
    ///   * An integer of type [`i8`], [`i16`], [`i32`], [`i64`], [`i128`],
    ///     [`isize`], [`u8`], [`u16`], [`u32`], [`u64`], [`u128`], or
    ///     [`usize`]. Any fractional bits are discarded, which rounds
    ///     towards −∞.
    ///   * A floating-point number of type [`f32`] or [`f64`]. If the
    ///     [`f16` feature] is enabled, it can also be of type [`f16`]
    ///     or [`bf16`]. For this conversion, the method rounds to the
    ///     nearest, with ties rounding to even.
    ///   * Any other type `Dst` for which [`FromFixed`] is implemented, in
    ///     which case this method returns
    ///     [`Dst::wrapping_from_fixed(self.0)`][`wrapping_from_fixed`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{
    ///     types::{I16F16, I2F6, I4F4},
    ///     Wrapping,
    /// };
    ///
    /// // conversion that fits
    /// let src = Wrapping(I4F4::from_num(1.75));
    /// let expected = I16F16::from_num(1.75);
    /// assert_eq!(src.to_num::<I16F16>(), expected);
    ///
    /// // conversion that wraps
    /// let src = Wrapping(I4F4::MAX);
    /// let wrapped = I2F6::from_bits(I2F6::MAX.to_bits() << 2);
    /// assert_eq!(src.to_num::<I2F6>(), wrapped);
    /// ```
    ///
    /// [`FromFixed`]: traits/trait.FromFixed.html
    /// [`bf16`]: https://docs.rs/half/^1.2/half/struct.bf16.html
    /// [`f16` feature]: index.html#optional-features
    /// [`f16`]: https://docs.rs/half/^1.2/half/struct.f16.html
    /// [`f32`]: https://doc.rust-lang.org/nightly/std/primitive.f32.html
    /// [`f64`]: https://doc.rust-lang.org/nightly/std/primitive.f64.html
    /// [`wrapping_from_fixed`]: traits/trait.FromFixed.html#tymethod.wrapping_from_fixed
    /// [`i128`]: https://doc.rust-lang.org/nightly/std/primitive.i128.html
    /// [`i16`]: https://doc.rust-lang.org/nightly/std/primitive.i16.html
    /// [`i32`]: https://doc.rust-lang.org/nightly/std/primitive.i32.html
    /// [`i64`]: https://doc.rust-lang.org/nightly/std/primitive.i64.html
    /// [`i8`]: https://doc.rust-lang.org/nightly/std/primitive.i8.html
    /// [`isize`]: https://doc.rust-lang.org/nightly/std/primitive.isize.html
    /// [`u128`]: https://doc.rust-lang.org/nightly/std/primitive.u128.html
    /// [`u16`]: https://doc.rust-lang.org/nightly/std/primitive.u16.html
    /// [`u32`]: https://doc.rust-lang.org/nightly/std/primitive.u32.html
    /// [`u64`]: https://doc.rust-lang.org/nightly/std/primitive.u64.html
    /// [`u8`]: https://doc.rust-lang.org/nightly/std/primitive.u8.html
    /// [`usize`]: https://doc.rust-lang.org/nightly/std/primitive.usize.html
    #[inline]
    pub fn to_num<Dst: FromFixed>(self) -> Dst {
        Dst::wrapping_from_fixed(self.0)
    }

    /// Parses a string slice containing binary digits to return a fixed-point number.
    ///
    /// Rounding is to the nearest, with ties rounded to even.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I8F8, Wrapping};
    /// let check = Wrapping(I8F8::from_bits(0b1110001 << (8 - 1)));
    /// assert_eq!(Wrapping::<I8F8>::from_str_binary("101100111000.1"), Ok(check));
    /// ```
    #[inline]
    pub fn from_str_binary(src: &str) -> Result<Wrapping<F>, ParseFixedError> {
        F::wrapping_from_str_binary(src).map(Wrapping)
    }

    /// Parses a string slice containing octal digits to return a fixed-point number.
    ///
    /// Rounding is to the nearest, with ties rounded to even.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I8F8, Wrapping};
    /// let check = Wrapping(I8F8::from_bits(0o1654 << (8 - 3)));
    /// assert_eq!(Wrapping::<I8F8>::from_str_octal("7165.4"), Ok(check));
    /// ```
    #[inline]
    pub fn from_str_octal(src: &str) -> Result<Wrapping<F>, ParseFixedError> {
        F::wrapping_from_str_octal(src).map(Wrapping)
    }

    /// Parses a string slice containing hexadecimal digits to return a fixed-point number.
    ///
    /// Rounding is to the nearest, with ties rounded to even.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I8F8, Wrapping};
    /// let check = Wrapping(I8F8::from_bits(0xFFE));
    /// assert_eq!(Wrapping::<I8F8>::from_str_hex("C0F.FE"), Ok(check));
    /// ```
    #[inline]
    pub fn from_str_hex(src: &str) -> Result<Wrapping<F>, ParseFixedError> {
        F::wrapping_from_str_hex(src).map(Wrapping)
    }

    /// Returns the integer part.
    ///
    /// Note that since the numbers are stored in two’s complement,
    /// negative numbers with non-zero fractional parts will be
    /// rounded towards −∞, except in the case where there are no
    /// integer bits, for example for the type
    /// <code>[Wrapping][`Wrapping`]&lt;[I0F16][`I0F16`]&gt;</code>,
    /// where the return value is always zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I16F16, Wrapping};
    /// assert_eq!(Wrapping(I16F16::from_num(12.25)).int(), Wrapping(I16F16::from_num(12)));
    /// assert_eq!(Wrapping(I16F16::from_num(-12.25)).int(), Wrapping(I16F16::from_num(-13)));
    /// ```
    ///
    /// [`I0F16`]: types/type.I0F16.html
    /// [`Wrapping`]: struct.Wrapping.html
    #[inline]
    pub fn int(self) -> Wrapping<F> {
        Wrapping(self.0.int())
    }

    /// Returns the fractional part.
    ///
    /// Note that since the numbers are stored in two’s complement,
    /// the returned fraction will be non-negative for negative
    /// numbers, except in the case where there are no integer bits,
    /// for example for the type
    /// <code>[Wrapping][`Wrapping`]&lt;[I0F16][`I0F16`]&gt;</code>,
    /// where the return value is always equal to `self`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I16F16, Wrapping};
    /// assert_eq!(Wrapping(I16F16::from_num(12.25)).frac(), Wrapping(I16F16::from_num(0.25)));
    /// assert_eq!(Wrapping(I16F16::from_num(-12.25)).frac(), Wrapping(I16F16::from_num(0.75)));
    /// ```
    ///
    /// [`I0F16`]: types/type.I0F16.html
    /// [`Wrapping`]: struct.Wrapping.html
    #[inline]
    pub fn frac(self) -> Wrapping<F> {
        Wrapping(self.0.frac())
    }

    /// Rounds to the next integer towards 0.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I16F16, Wrapping};
    /// let three = Wrapping(I16F16::from_num(3));
    /// assert_eq!(Wrapping(I16F16::from_num(3.9)).round_to_zero(), three);
    /// assert_eq!(Wrapping(I16F16::from_num(-3.9)).round_to_zero(), -three);
    /// ```
    #[inline]
    pub fn round_to_zero(self) -> Wrapping<F> {
        Wrapping(self.0.round_to_zero())
    }

    /// Wrapping ceil. Rounds to the next integer towards +∞, wrapping
    /// on overflow.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I16F16, Wrapping};
    /// let two_half = Wrapping(I16F16::from_num(5) / 2);
    /// assert_eq!(two_half.ceil(), Wrapping(I16F16::from_num(3)));
    /// assert_eq!(Wrapping(I16F16::MAX).ceil(), Wrapping(I16F16::MIN));
    /// ```
    #[inline]
    pub fn ceil(self) -> Wrapping<F> {
        Wrapping(self.0.wrapping_ceil())
    }

    /// Wrapping floor. Rounds to the next integer towards −∞,
    /// wrapping on overflow.
    ///
    /// Overflow can only occur for signed numbers with zero integer
    /// bits.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{
    ///     types::{I0F32, I16F16},
    ///     Wrapping,
    /// };
    /// let two_half = Wrapping(I16F16::from_num(5) / 2);
    /// assert_eq!(two_half.floor(), Wrapping(I16F16::from_num(2)));
    /// assert_eq!(Wrapping(I0F32::MIN).floor(), Wrapping(I0F32::from_num(0)));
    /// ```
    #[inline]
    pub fn floor(self) -> Wrapping<F> {
        Wrapping(self.0.wrapping_floor())
    }

    /// Wrapping round. Rounds to the next integer to the nearest,
    /// with ties rounded away from zero, and wrapping on overflow.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I16F16, Wrapping};
    /// let two_half = Wrapping(I16F16::from_num(5) / 2);
    /// assert_eq!(two_half.round(), Wrapping(I16F16::from_num(3)));
    /// assert_eq!((-two_half).round(), Wrapping(I16F16::from_num(-3)));
    /// assert_eq!(Wrapping(I16F16::MAX).round(), Wrapping(I16F16::MIN));
    /// ```
    #[inline]
    pub fn round(self) -> Wrapping<F> {
        Wrapping(self.0.wrapping_round())
    }

    /// Wrapping round. Rounds to the next integer to the nearest,
    /// with ties rounded to even, and wrapping on overflow.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I16F16, Wrapping};
    /// let two_half = Wrapping(I16F16::from_num(2.5));
    /// assert_eq!(two_half.round_ties_to_even(), Wrapping(I16F16::from_num(2)));
    /// let three_half = Wrapping(I16F16::from_num(3.5));
    /// assert_eq!(three_half.round_ties_to_even(), Wrapping(I16F16::from_num(4)));
    /// let max = Wrapping(I16F16::MAX);
    /// assert_eq!(max.round_ties_to_even(), Wrapping(I16F16::MIN));
    /// ```
    #[inline]
    pub fn round_ties_to_even(self) -> Wrapping<F> {
        Wrapping(self.0.wrapping_round_ties_to_even())
    }

    /// Returns the number of ones in the binary representation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I16F16, Wrapping};
    /// let w = Wrapping(I16F16::from_bits(0x00FF_FF00));
    /// assert_eq!(w.count_ones(), w.0.count_ones());
    /// ```
    #[inline]
    pub fn count_ones(self) -> u32 {
        self.0.count_ones()
    }

    /// Returns the number of zeros in the binary representation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I16F16, Wrapping};
    /// let w = Wrapping(I16F16::from_bits(0x00FF_FF00));
    /// assert_eq!(w.count_zeros(), w.0.count_zeros());
    /// ```
    #[inline]
    pub fn count_zeros(self) -> u32 {
        self.0.count_zeros()
    }

    /// Returns the number of leading ones in the binary representation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::U16F16, Wrapping};
    /// let w = Wrapping(U16F16::from_bits(0xFF00_00FF));
    /// assert_eq!(w.leading_ones(), w.0.leading_ones());
    /// ```
    #[inline]
    pub fn leading_ones(self) -> u32 {
        self.0.leading_ones()
    }

    /// Returns the number of leading zeros in the binary representation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I16F16, Wrapping};
    /// let w = Wrapping(I16F16::from_bits(0x00FF_FF00));
    /// assert_eq!(w.leading_zeros(), w.0.leading_zeros());
    /// ```
    #[inline]
    pub fn leading_zeros(self) -> u32 {
        self.0.leading_zeros()
    }

    /// Returns the number of trailing ones in the binary representation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::U16F16, Wrapping};
    /// let w = Wrapping(U16F16::from_bits(0xFF00_00FF));
    /// assert_eq!(w.trailing_ones(), w.0.trailing_ones());
    /// ```
    #[inline]
    pub fn trailing_ones(self) -> u32 {
        self.0.trailing_ones()
    }

    /// Returns the number of trailing zeros in the binary representation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I16F16, Wrapping};
    /// let w = Wrapping(I16F16::from_bits(0x00FF_FF00));
    /// assert_eq!(w.trailing_zeros(), w.0.trailing_zeros());
    /// ```
    #[inline]
    pub fn trailing_zeros(self) -> u32 {
        self.0.trailing_zeros()
    }

    /// Integer base-2 logarithm, rounded down.
    ///
    /// # Panics
    ///
    /// Panics if the fixed-point number is ≤ 0.
    #[inline]
    pub fn int_log2(self) -> i32 {
        self.0.int_log2()
    }

    /// Integer base-10 logarithm, rounded down.
    ///
    /// # Panics
    ///
    /// Panics if the fixed-point number is ≤ 0.
    #[inline]
    pub fn int_log10(self) -> i32 {
        self.0.int_log10()
    }

    /// Shifts to the left by `n` bits, wrapping the truncated bits to the right end.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I16F16, Wrapping};
    /// let i = I16F16::from_bits(0x00FF_FF00);
    /// assert_eq!(Wrapping(i).rotate_left(12), Wrapping(i.rotate_left(12)));
    /// ```
    #[inline]
    pub fn rotate_left(self, n: u32) -> Wrapping<F> {
        Wrapping(self.0.rotate_left(n))
    }

    /// Shifts to the right by `n` bits, wrapping the truncated bits to the left end.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I16F16, Wrapping};
    /// let i = I16F16::from_bits(0x00FF_FF00);
    /// assert_eq!(Wrapping(i).rotate_right(12), Wrapping(i.rotate_right(12)));
    /// ```
    #[inline]
    pub fn rotate_right(self, n: u32) -> Wrapping<F> {
        Wrapping(self.0.rotate_right(n))
    }

    /// Euclidean division.
    ///
    /// # Panics
    ///
    /// Panics if the divisor is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I16F16, Wrapping};
    /// let num = Wrapping(I16F16::from_num(7.5));
    /// let den = Wrapping(I16F16::from_num(2));
    /// assert_eq!(num.div_euclid(den), Wrapping(I16F16::from_num(3)));
    /// let quarter = Wrapping(I16F16::from_num(0.25));
    /// let check = (Wrapping::MAX * 4i32).round_to_zero();
    /// assert_eq!(Wrapping::MAX.div_euclid(quarter), check);
    /// ```
    #[inline]
    pub fn div_euclid(self, divisor: Wrapping<F>) -> Wrapping<F> {
        Wrapping(self.0.wrapping_div_euclid(divisor.0))
    }

    /// Remainder for Euclidean division.
    ///
    /// # Panics
    ///
    /// Panics if the divisor is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I16F16, Wrapping};
    /// let num = Wrapping(I16F16::from_num(7.5));
    /// let den = Wrapping(I16F16::from_num(2));
    /// assert_eq!(num.rem_euclid(den), Wrapping(I16F16::from_num(1.5)));
    /// assert_eq!((-num).rem_euclid(den), Wrapping(I16F16::from_num(0.5)));
    /// ```
    #[inline]
    pub fn rem_euclid(self, divisor: Wrapping<F>) -> Wrapping<F> {
        Wrapping(self.0.rem_euclid(divisor.0))
    }

    /// Euclidean division by an integer.
    ///
    /// # Panics
    ///
    /// Panics if the divisor is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I16F16, Wrapping};
    /// let num = Wrapping(I16F16::from_num(7.5));
    /// assert_eq!(num.div_euclid_int(2), Wrapping(I16F16::from_num(3)));
    /// let min = Wrapping(I16F16::MIN);
    /// assert_eq!(min.div_euclid_int(-1), min);
    /// ```
    #[inline]
    pub fn div_euclid_int(self, divisor: F::Bits) -> Wrapping<F> {
        Wrapping(self.0.wrapping_div_euclid_int(divisor))
    }

    /// Remainder for Euclidean division.
    ///
    /// # Panics
    ///
    /// Panics if the divisor is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I16F16, Wrapping};
    /// let num = Wrapping(I16F16::from_num(7.5));
    /// assert_eq!(num.rem_euclid_int(2), Wrapping(I16F16::from_num(1.5)));
    /// assert_eq!((-num).rem_euclid_int(2), Wrapping(I16F16::from_num(0.5)));
    /// ```
    #[inline]
    pub fn rem_euclid_int(self, divisor: F::Bits) -> Wrapping<F> {
        Wrapping(self.0.wrapping_rem_euclid_int(divisor))
    }
}

impl<F: FixedSigned> Wrapping<F> {
    /// Returns [`true`] if the number is > 0.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I16F16, Wrapping};
    /// assert!(Wrapping(I16F16::from_num(4.3)).is_positive());
    /// assert!(!Wrapping(I16F16::from_num(0)).is_positive());
    /// assert!(!Wrapping(I16F16::from_num(-4.3)).is_positive());
    /// ```
    ///
    /// [`true`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
    #[inline]
    pub fn is_positive(self) -> bool {
        self.0.is_positive()
    }

    /// Returns [`true`] if the number is < 0.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I16F16, Wrapping};
    /// assert!(!Wrapping(I16F16::from_num(4.3)).is_negative());
    /// assert!(!Wrapping(I16F16::from_num(0)).is_negative());
    /// assert!(Wrapping(I16F16::from_num(-4.3)).is_negative());
    /// ```
    ///
    /// [`true`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
    #[inline]
    pub fn is_negative(self) -> bool {
        self.0.is_negative()
    }

    /// Wrapping absolute value. Returns the absolute value, wrapping
    /// on overflow.
    ///
    /// Overflow can only occur when trying to find the absolute value
    /// of the minimum value.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::I16F16, Wrapping};
    /// assert_eq!(Wrapping(I16F16::from_num(-5)).abs(), Wrapping(I16F16::from_num(5)));
    /// assert_eq!(Wrapping(I16F16::MIN).abs(), Wrapping(I16F16::MIN));
    /// ```
    #[inline]
    pub fn abs(self) -> Wrapping<F> {
        Wrapping(self.0.wrapping_abs())
    }

    /// Returns a number representing the sign of `self`.
    ///
    /// # Warning
    ///
    /// Using this method when 1 and −1 cannot be represented is
    /// almost certainly a bug, however, this is allowed and gives the
    /// following wrapped results.
    ///
    ///   * When there are no integer bits, for example for the type
    ///     <code>[Wrapping][`Wrapping`]&lt;[I0F16][`I0F16`]&gt;</code>,
    ///     the return value is always zero.
    ///   * When there is one integer bit, for example for the type
    ///     <code>[Wrapping][`Wrapping`]&lt;[I1F15][`I1F15`]&gt;</code>,
    ///     the return value is zero when `self` is zero, and −1
    ///     otherwise. This means that for a positive number, −1 is
    ///     returned, because +1 does not fit and is wrapped to −1.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{
    ///     types::{I0F32, I1F31, I16F16},
    ///     Wrapping,
    /// };
    /// assert_eq!(Wrapping(<I16F16>::from_num(-3.9)).signum(), Wrapping(I16F16::from_num(-1)));
    /// assert_eq!(Wrapping(<I16F16>::from_num(0)).signum(), Wrapping(I16F16::from_num(0)));
    /// assert_eq!(Wrapping(<I16F16>::from_num(3.9)).signum(), Wrapping(I16F16::from_num(1)));
    ///
    /// assert_eq!(Wrapping(<I1F31>::from_num(0.5)).signum(), Wrapping(I1F31::from_num(-1)));
    /// assert_eq!(Wrapping(<I0F32>::from_num(0.25)).signum(), Wrapping(I0F32::from_num(0)));
    /// assert_eq!(Wrapping(<I0F32>::from_num(-0.5)).signum(), Wrapping(I0F32::from_num(0)));
    /// ```
    ///
    /// [`I0F16`]: types/type.I0F16.html
    /// [`I1F15`]: types/type.I1F15.html
    /// [`Wrapping`]: struct.Wrapping.html
    #[inline]
    pub fn signum(self) -> Wrapping<F> {
        Wrapping(self.0.wrapping_signum())
    }
}

impl<F: FixedUnsigned> Wrapping<F> {
    /// Returns [`true`] if the fixed-point number is
    /// 2<sup><i>k</i></sup> for some integer <i>k</i>.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::U16F16, Wrapping};
    /// assert!(Wrapping(U16F16::from_num(0.5)).is_power_of_two());
    /// assert!(Wrapping(U16F16::from_num(4)).is_power_of_two());
    /// assert!(!Wrapping(U16F16::from_num(5)).is_power_of_two());
    /// ```
    ///
    /// [`true`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
    #[inline]
    pub fn is_power_of_two(self) -> bool {
        self.0.is_power_of_two()
    }

    /// Returns the smallest power of two that is ≥ `self`.
    ///
    /// If the next power of two is too large to fit, it is wrapped to zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fixed::{types::U16F16, Wrapping};
    /// let half = Wrapping(U16F16::from_num(0.5));
    /// assert_eq!(Wrapping(U16F16::from_num(0.3)).next_power_of_two(), half);
    /// let four = Wrapping(U16F16::from_num(4));
    /// assert_eq!(Wrapping(U16F16::from_num(4)).next_power_of_two(), four);
    /// let zero = Wrapping(U16F16::from_num(0));
    /// assert_eq!(Wrapping(U16F16::MAX).next_power_of_two(), zero);
    /// ```
    #[inline]
    pub fn next_power_of_two(self) -> Wrapping<F> {
        Wrapping(self.0.wrapping_next_power_of_two())
    }
}

impl<F: Fixed> Display for Wrapping<F> {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        Display::fmt(&self.0, f)
    }
}

impl<F: Fixed> From<F> for Wrapping<F> {
    /// Wraps a fixed-point number.
    #[inline]
    fn from(src: F) -> Wrapping<F> {
        Wrapping(src)
    }
}

impl<F: Fixed> FromStr for Wrapping<F> {
    type Err = ParseFixedError;
    /// Parses a string slice containing decimal digits to return a fixed-point number.
    ///
    /// Rounding is to the nearest, with ties rounded to even.
    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        F::wrapping_from_str(s).map(Wrapping)
    }
}

macro_rules! op {
    ($wrapping:ident, $Op:ident $op:ident, $OpAssign:ident $op_assign:ident) => {
        impl<F: Fixed> $Op<Wrapping<F>> for Wrapping<F> {
            type Output = Wrapping<F>;
            #[inline]
            fn $op(self, other: Wrapping<F>) -> Wrapping<F> {
                Wrapping((self.0).$wrapping(other.0))
            }
        }
        impl<'a, F: Fixed> $Op<Wrapping<F>> for &'a Wrapping<F> {
            type Output = Wrapping<F>;
            #[inline]
            fn $op(self, other: Wrapping<F>) -> Wrapping<F> {
                Wrapping((self.0).$wrapping(other.0))
            }
        }
        impl<'a, F: Fixed> $Op<&'a Wrapping<F>> for Wrapping<F> {
            type Output = Wrapping<F>;
            #[inline]
            fn $op(self, other: &Wrapping<F>) -> Wrapping<F> {
                Wrapping((self.0).$wrapping(other.0))
            }
        }
        impl<'a, 'b, F: Fixed> $Op<&'a Wrapping<F>> for &'b Wrapping<F> {
            type Output = Wrapping<F>;
            #[inline]
            fn $op(self, other: &Wrapping<F>) -> Wrapping<F> {
                Wrapping((self.0).$wrapping(other.0))
            }
        }
        impl<F: Fixed> $OpAssign<Wrapping<F>> for Wrapping<F> {
            #[inline]
            fn $op_assign(&mut self, other: Wrapping<F>) {
                self.0 = (self.0).$wrapping(other.0);
            }
        }
        impl<'a, F: Fixed> $OpAssign<&'a Wrapping<F>> for Wrapping<F> {
            #[inline]
            fn $op_assign(&mut self, other: &Wrapping<F>) {
                self.0 = (self.0).$wrapping(other.0);
            }
        }
    };
}

macro_rules! op_bitwise {
    ($Op:ident $op:ident, $OpAssign:ident $op_assign:ident) => {
        impl<F> $Op<Wrapping<F>> for Wrapping<F>
        where
            F: $Op<F, Output = F>,
        {
            type Output = Wrapping<F>;
            #[inline]
            fn $op(self, other: Wrapping<F>) -> Wrapping<F> {
                Wrapping((self.0).$op(other.0))
            }
        }
        impl<'a, F> $Op<Wrapping<F>> for &'a Wrapping<F>
        where
            &'a F: $Op<F, Output = F>,
        {
            type Output = Wrapping<F>;
            #[inline]
            fn $op(self, other: Wrapping<F>) -> Wrapping<F> {
                Wrapping((self.0).$op(other.0))
            }
        }
        impl<'a, F> $Op<&'a Wrapping<F>> for Wrapping<F>
        where
            F: $Op<&'a F, Output = F>,
        {
            type Output = Wrapping<F>;
            #[inline]
            fn $op(self, other: &'a Wrapping<F>) -> Wrapping<F> {
                Wrapping((self.0).$op(&other.0))
            }
        }
        impl<'a, 'b, F> $Op<&'a Wrapping<F>> for &'b Wrapping<F>
        where
            &'b F: $Op<&'a F, Output = F>,
        {
            type Output = Wrapping<F>;
            #[inline]
            fn $op(self, other: &'a Wrapping<F>) -> Wrapping<F> {
                Wrapping((self.0).$op(&other.0))
            }
        }
        impl<F> $OpAssign<Wrapping<F>> for Wrapping<F>
        where
            F: $OpAssign<F>,
        {
            #[inline]
            fn $op_assign(&mut self, other: Wrapping<F>) {
                (self.0).$op_assign(other.0);
            }
        }
        impl<'a, F> $OpAssign<&'a Wrapping<F>> for Wrapping<F>
        where
            F: $OpAssign<&'a F>,
        {
            #[inline]
            fn $op_assign(&mut self, other: &'a Wrapping<F>) {
                (self.0).$op_assign(&other.0);
            }
        }
    };
}

macro_rules! op_shift {
    (
        $Op:ident $op:ident, $OpAssign:ident $op_assign:ident;
        $($Rhs:ident),*
    ) => { $(
        impl<F> $Op<$Rhs> for Wrapping<F>
        where
            F: $Op<u32, Output = F>,
        {
            type Output = Wrapping<F>;
            #[inline]
            fn $op(self, other: $Rhs) -> Wrapping<F> {
                let nbits = mem::size_of::<F>() as u32 * 8;
                Wrapping((self.0).$op(other as u32 % nbits))
            }
        }
        impl<'a, F> $Op<$Rhs> for &'a Wrapping<F>
        where
            &'a F: $Op<u32, Output = F>,
        {
            type Output = Wrapping<F>;
            #[inline]
            fn $op(self, other: $Rhs) -> Wrapping<F> {
                let nbits = mem::size_of::<F>() as u32 * 8;
                Wrapping((self.0).$op(other as u32 % nbits))
            }
        }
        impl<'a, F> $Op<&'a $Rhs> for Wrapping<F>
        where
            F: $Op<u32, Output = F>,
        {
            type Output = Wrapping<F>;
            #[inline]
            fn $op(self, other: &$Rhs) -> Wrapping<F> {
                let nbits = mem::size_of::<F>() as u32 * 8;
                Wrapping((self.0).$op(*other as u32 % nbits))
            }
        }
        impl<'a, 'b, F> $Op<&'a $Rhs> for &'b Wrapping<F>
        where
            &'b F: $Op<u32, Output = F>,
        {
            type Output = Wrapping<F>;
            #[inline]
            fn $op(self, other: &$Rhs) -> Wrapping<F> {
                let nbits = mem::size_of::<F>() as u32 * 8;
                Wrapping((self.0).$op(*other as u32 % nbits))
            }
        }
        impl<F> $OpAssign<$Rhs> for Wrapping<F>
        where
            F: $OpAssign<u32>,
        {
            #[inline]
            fn $op_assign(&mut self, other: $Rhs) {
                let nbits = mem::size_of::<F>() as u32 * 8;
                (self.0).$op_assign(other as u32 % nbits);
            }
        }
        impl<'a, F> $OpAssign<&'a $Rhs> for Wrapping<F>
        where
            F: $OpAssign<u32>,
        {
            #[inline]
            fn $op_assign(&mut self, other: &$Rhs) {
                let nbits = mem::size_of::<F>() as u32 * 8;
                (self.0).$op_assign(*other as u32 % nbits);
            }
        }
    )* };
}

impl<F: Fixed> Neg for Wrapping<F> {
    type Output = Wrapping<F>;
    #[inline]
    fn neg(self) -> Wrapping<F> {
        Wrapping((self.0).wrapping_neg())
    }
}

impl<'a, F: Fixed> Neg for &'a Wrapping<F> {
    type Output = Wrapping<F>;
    #[inline]
    fn neg(self) -> Wrapping<F> {
        Wrapping((self.0).wrapping_neg())
    }
}
op! { wrapping_add, Add add, AddAssign add_assign }
op! { wrapping_sub, Sub sub, SubAssign sub_assign }
op! { wrapping_mul, Mul mul, MulAssign mul_assign }
op! { wrapping_div, Div div, DivAssign div_assign }
op! { rem, Rem rem, RemAssign rem_assign }

impl<F> Not for Wrapping<F>
where
    F: Not<Output = F>,
{
    type Output = Wrapping<F>;
    #[inline]
    fn not(self) -> Wrapping<F> {
        Wrapping((self.0).not())
    }
}
impl<'a, F> Not for &'a Wrapping<F>
where
    &'a F: Not<Output = F>,
{
    type Output = Wrapping<F>;
    #[inline]
    fn not(self) -> Wrapping<F> {
        Wrapping((self.0).not())
    }
}
op_bitwise! { BitAnd bitand, BitAndAssign bitand_assign }
op_bitwise! { BitOr bitor, BitOrAssign bitor_assign }
op_bitwise! { BitXor bitxor, BitXorAssign bitxor_assign }

op_shift! {
    Shl shl, ShlAssign shl_assign;
    i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize
}
op_shift! {
    Shr shr, ShrAssign shr_assign;
    i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize
}

impl<F: Fixed> Sum<Wrapping<F>> for Wrapping<F> {
    fn sum<I>(iter: I) -> Wrapping<F>
    where
        I: Iterator<Item = Wrapping<F>>,
    {
        iter.fold(Wrapping(F::from_num(0)), Add::add)
    }
}

impl<'a, F: 'a + Fixed> Sum<&'a Wrapping<F>> for Wrapping<F> {
    fn sum<I>(iter: I) -> Wrapping<F>
    where
        I: Iterator<Item = &'a Wrapping<F>>,
    {
        iter.fold(Wrapping(F::from_num(0)), Add::add)
    }
}

impl<F: Fixed> Product<Wrapping<F>> for Wrapping<F> {
    fn product<I>(mut iter: I) -> Wrapping<F>
    where
        I: Iterator<Item = Wrapping<F>>,
    {
        match iter.next() {
            None => Wrapping(1.wrapping_to_fixed()),
            Some(first) => iter.fold(first, Mul::mul),
        }
    }
}

impl<'a, F: 'a + Fixed> Product<&'a Wrapping<F>> for Wrapping<F> {
    fn product<I>(mut iter: I) -> Wrapping<F>
    where
        I: Iterator<Item = &'a Wrapping<F>>,
    {
        match iter.next() {
            None => Wrapping(1.wrapping_to_fixed()),
            Some(first) => iter.fold(*first, Mul::mul),
        }
    }
}

// The following cannot be implemented for Wrapping<F> where F: Fixed,
// otherwise there will be a conflicting implementation error. For
// example we cannot implement both these without triggering E0119:
//
//     impl<F: Fixed> Op<F::Bits> for Wrapping<F> { /* ... */ }
//     impl<'a, F: Fixed> Op<&'a F::Bits> for Wrapping<F> { /* ... */ }
//
// To work around this, we provide implementations like this:
//
//     impl<Frac> Op<i8> for Wrapping<FixedI8<Frac>> { /* ... */ }
//     impl<'a, Frac> Op<&'a i8> for Wrapping<FixedI8<Frac>> { /* ... */ }
//     impl<Frac> Op<i16> for Wrapping<FixedI16<Frac>> { /* ... */ }
//     impl<'a, Frac> Op<&'a i16> for Wrapping<FixedI16<Frac>> { /* ... */ }
//     ...

macro_rules! op_bits {
    (
        $Fixed:ident($Bits:ident $(, $LeEqU:ident)*)::$wrapping:ident,
        $Op:ident $op:ident,
        $OpAssign:ident $op_assign:ident
    ) => {
        impl<Frac $(: $LeEqU)*> $Op<$Bits> for Wrapping<$Fixed<Frac>> {
            type Output = Wrapping<$Fixed<Frac>>;
            #[inline]
            fn $op(self, other: $Bits) -> Wrapping<$Fixed<Frac>> {
                Wrapping((self.0).$wrapping(other))
            }
        }
        impl<'a, Frac $(: $LeEqU)*> $Op<$Bits> for &'a Wrapping<$Fixed<Frac>> {
            type Output = Wrapping<$Fixed<Frac>>;
            #[inline]
            fn $op(self, other: $Bits) -> Wrapping<$Fixed<Frac>> {
                Wrapping((self.0).$wrapping(other))
            }
        }
        impl<'a, Frac $(: $LeEqU)*> $Op<&'a $Bits> for Wrapping<$Fixed<Frac>> {
            type Output = Wrapping<$Fixed<Frac>>;
            #[inline]
            fn $op(self, other: &$Bits) -> Wrapping<$Fixed<Frac>> {
                Wrapping((self.0).$wrapping(*other))
            }
        }
        impl<'a, 'b, Frac $(: $LeEqU)*> $Op<&'a $Bits> for &'b Wrapping<$Fixed<Frac>> {
            type Output = Wrapping<$Fixed<Frac>>;
            #[inline]
            fn $op(self, other: &$Bits) -> Wrapping<$Fixed<Frac>> {
                Wrapping((self.0).$wrapping(*other))
            }
        }
        impl<Frac $(: $LeEqU)*> $OpAssign<$Bits> for Wrapping<$Fixed<Frac>> {
            #[inline]
            fn $op_assign(&mut self, other: $Bits) {
                self.0 = (self.0).$wrapping(other);
            }
        }
        impl<'a, Frac $(: $LeEqU)*> $OpAssign<&'a $Bits> for Wrapping<$Fixed<Frac>> {
            #[inline]
            fn $op_assign(&mut self, other: &$Bits) {
                self.0 = (self.0).$wrapping(*other);
            }
        }
    };
}

macro_rules! ops {
    ($Fixed:ident($Bits:ident, $LeEqU:ident)) => {
        op_bits! { $Fixed($Bits)::wrapping_mul_int, Mul mul, MulAssign mul_assign }
        op_bits! { $Fixed($Bits)::wrapping_div_int, Div div, DivAssign div_assign }
        op_bits! { $Fixed($Bits, $LeEqU)::rem, Rem rem, RemAssign rem_assign }
    };
}
ops! { FixedI8(i8, LeEqU8) }
ops! { FixedI16(i16, LeEqU16) }
ops! { FixedI32(i32, LeEqU32) }
ops! { FixedI64(i64, LeEqU64) }
ops! { FixedI128(i128, LeEqU128) }
ops! { FixedU8(u8, LeEqU8) }
ops! { FixedU16(u16, LeEqU16) }
ops! { FixedU32(u32, LeEqU32) }
ops! { FixedU64(u64, LeEqU64) }
ops! { FixedU128(u128, LeEqU128) }