diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 14:29:10 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 14:29:10 +0000 |
commit | 2aa4a82499d4becd2284cdb482213d541b8804dd (patch) | |
tree | b80bf8bf13c3766139fbacc530efd0dd9d54394c /third_party/rust/num-bigint | |
parent | Initial commit. (diff) | |
download | firefox-2aa4a82499d4becd2284cdb482213d541b8804dd.tar.xz firefox-2aa4a82499d4becd2284cdb482213d541b8804dd.zip |
Adding upstream version 86.0.1.upstream/86.0.1upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'third_party/rust/num-bigint')
35 files changed, 13938 insertions, 0 deletions
diff --git a/third_party/rust/num-bigint/.cargo-checksum.json b/third_party/rust/num-bigint/.cargo-checksum.json new file mode 100644 index 0000000000..288114fb2c --- /dev/null +++ b/third_party/rust/num-bigint/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"ba1041ccca008388ab7d7432ae63b811d8e744c8fa9e50f371bfbeb78acd1995","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"25f684f15b0ed6ea216c3831e567a9b5dc02b78ff7e579e0d7323305db75218c","RELEASES.md":"5a3045437dc1850ae4e39acd14f2660ed7bace9b0c4d7dae3950f049dbfd4d65","benches/bigint.rs":"252c0dc1f220a6fbdc151e729069260c2f5909516467ceb873e412e5691d7042","benches/factorial.rs":"d536f5584987847f10321b94175a0d8fd2beb14b7c814ec28eef1f96ca081fbe","benches/gcd.rs":"7ec5ce7174e1d31bd08ccc5670f5a32a5c084f258d7980cd6d02e0a8bb5562c4","benches/roots.rs":"3f87db894c379122aee5cd8520c7c759c26d8a9649ac47f45d1bf4d560e1cb07","benches/shootout-pidigits.rs":"985b76d6dba05c396efe4da136c6a0bb2c02bcf5b05cbb346f0f802a891629bb","bors.toml":"1c81ede536a37edd30fe4e622ff0531b25372403ac9475a5d6c50f14156565a2","build.rs":"56d4fbb7a55750e61d2074df2735a31995c1decbd988c0e722926235e0fed487","ci/rustup.sh":"c976bb2756da3876363b01fdbf06c13de20df421e5add45e4017c4df42ed06a6","ci/test_full.sh":"a0ac26b85809eb43edd813c9dc88f34a1a8227b7618f4bede89c8f2ac9a4c05a","src/algorithms.rs":"8827c46df051214d1d0e7670680ca9f4834eae678ed340c86b5ea32fddbc7c3c","src/bigint.rs":"7f113fdc034c566bc8475ff0a7d136aa8250cae047b4356084e6797a15f968e1","src/bigrand.rs":"d2f72b8833f367dd8990b4b026f302d838144c5a4de942135d39a3a9932f137d","src/biguint.rs":"b95bfcf84e3f831fb07982aa4b058cd16a524eaa493946eed8e8c5fb8d65797a","src/lib.rs":"d5cc50306f73f07555e7d3413edd2ca5c7d54cbc80a2e83844d77fb8750ae314","src/macros.rs":"2e763517922d960c06e3ac4d319b1d81e66dffadfde8fdf300ff8b8bb95bd8cd","src/monty.rs":"6a867846b7f6af9115add2fd59fccd0651c71dd7f2316e8fb9c812ff3c27da12","tests/bigint.rs":"f7df454f085a862ad5a98e3a802303a3fdf06275a7a1b92074b40b76a715bed2","tests/bigint_bitwise.rs":"dc9436c8f200f2b0ac08cefb23bb8e39c4e688e9026a506a678416c3d573128b","tests/bigint_scalar.rs":"aa176ed102cafd425a215a93460806914d8f3ac288c98ec3e56772fa17379838","tests/biguint.rs":"9ae79f96d1a3beca5be95dffe9d79dc3436f886edc6cae51faf4203c3e0c4681","tests/biguint_scalar.rs":"9cc6f2bf2fe77f34b09eb2266c23aded3b27a60dc1859eb60d3013164292467e","tests/consts/mod.rs":"f9ea5f40733e2f5f432803d830be9db929d91e5e5efd8510b07c6ced2fe554be","tests/macros/mod.rs":"2789b680dd14a770d5ceef430018be0ada85098d69e218c61c17214084c4f763","tests/modpow.rs":"f14cdea11e355a371b314cc866dfa13281a3226706ab2cf01c1485273afde300","tests/quickcheck.rs":"6d6c1ec244b2384a8b34e989870aef8bcedccf6cc46e2626b29a032703bef03c","tests/rand.rs":"08370135bd78432660cfcd708a9ea852022d555bc92c1f3c482fabd17faa64a0","tests/roots.rs":"9ec1bdb0cd1c72402a41e5470325a5276af75979b7fc0f0b63e7bbbb9f3505b2","tests/serde.rs":"79d7a0347207b3a3666af67d2ed97fa34f2922732121a3cb8f5b9f990846acfa","tests/torture.rs":"9fe4897580c0ebe2b7062f5b0b890b4b03510daa45c9236f0edba7144f9eb6f8"},"package":"f9c3f34cdd24f334cb265d9bf8bfa8a241920d026916785747a92f0e55541a1a"}
\ No newline at end of file diff --git a/third_party/rust/num-bigint/Cargo.toml b/third_party/rust/num-bigint/Cargo.toml new file mode 100644 index 0000000000..d8403a5659 --- /dev/null +++ b/third_party/rust/num-bigint/Cargo.toml @@ -0,0 +1,81 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "num-bigint" +version = "0.2.3" +authors = ["The Rust Project Developers"] +build = "build.rs" +description = "Big integer implementation for Rust" +homepage = "https://github.com/rust-num/num-bigint" +documentation = "https://docs.rs/num-bigint" +readme = "README.md" +keywords = ["mathematics", "numerics", "bignum"] +categories = ["algorithms", "data-structures", "science"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-num/num-bigint" +[package.metadata.docs.rs] +features = ["std", "serde", "rand", "quickcheck"] + +[[bench]] +name = "bigint" + +[[bench]] +name = "factorial" + +[[bench]] +name = "gcd" + +[[bench]] +name = "roots" + +[[bench]] +name = "shootout-pidigits" +harness = false +[dependencies.num-integer] +version = "0.1.39" +default-features = false + +[dependencies.num-traits] +version = "0.2.7" +default-features = false + +[dependencies.quickcheck] +version = "0.8" +optional = true +default-features = false + +[dependencies.quickcheck_macros] +version = "0.8" +optional = true +default-features = false + +[dependencies.rand] +version = "0.5" +features = ["std"] +optional = true +default-features = false + +[dependencies.serde] +version = "1.0" +features = ["std"] +optional = true +default-features = false +[dev-dependencies.serde_test] +version = "1.0" +[build-dependencies.autocfg] +version = "0.1.2" + +[features] +default = ["std"] +i128 = ["num-integer/i128", "num-traits/i128"] +std = ["num-integer/std", "num-traits/std"] diff --git a/third_party/rust/num-bigint/LICENSE-APACHE b/third_party/rust/num-bigint/LICENSE-APACHE new file mode 100644 index 0000000000..16fe87b06e --- /dev/null +++ b/third_party/rust/num-bigint/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/third_party/rust/num-bigint/LICENSE-MIT b/third_party/rust/num-bigint/LICENSE-MIT new file mode 100644 index 0000000000..39d4bdb5ac --- /dev/null +++ b/third_party/rust/num-bigint/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/third_party/rust/num-bigint/README.md b/third_party/rust/num-bigint/README.md new file mode 100644 index 0000000000..f7eefed87e --- /dev/null +++ b/third_party/rust/num-bigint/README.md @@ -0,0 +1,63 @@ +# num-bigint + +[![crate](https://img.shields.io/crates/v/num-bigint.svg)](https://crates.io/crates/num-bigint) +[![documentation](https://docs.rs/num-bigint/badge.svg)](https://docs.rs/num-bigint) +![minimum rustc 1.15](https://img.shields.io/badge/rustc-1.15+-red.svg) +[![Travis status](https://travis-ci.org/rust-num/num-bigint.svg?branch=master)](https://travis-ci.org/rust-num/num-bigint) + +Big integer types for Rust, `BigInt` and `BigUint`. + +## Usage + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +num-bigint = "0.2" +``` + +and this to your crate root: + +```rust +extern crate num_bigint; +``` + +## Features + +The `std` crate feature is mandatory and enabled by default. If you depend on +`num-bigint` with `default-features = false`, you must manually enable the +`std` feature yourself. In the future, we hope to support `#![no_std]` with +the `alloc` crate when `std` is not enabled. + +Implementations for `i128` and `u128` are only available with Rust 1.26 and +later. The build script automatically detects this, but you can make it +mandatory by enabling the `i128` crate feature. + +## Releases + +Release notes are available in [RELEASES.md](RELEASES.md). + +## Compatibility + +The `num-bigint` crate is tested for rustc 1.15 and greater. + +## Alternatives + +While `num-bigint` strives for good performance in pure Rust code, other +crates may offer better performance with different trade-offs. The following +table offers a brief comparison to a few alternatives. + +| Crate | License | Min rustc | Implementation | +| :--------------- | :------------- | :-------- | :------------- | +| **`num-bigint`** | MIT/Apache-2.0 | 1.15 | pure rust | +| [`ramp`] | Apache-2.0 | nightly | rust and inline assembly | +| [`rug`] | LGPL-3.0+ | 1.31 | bundles [GMP] via [`gmp-mpfr-sys`] | +| [`rust-gmp`] | MIT | stable? | links to [GMP] | +| [`apint`] | MIT/Apache-2.0 | 1.26 | pure rust (unfinished) | + +[GMP]: https://gmplib.org/ +[`gmp-mpfr-sys`]: https://crates.io/crates/gmp-mpfr-sys +[`rug`]: https://crates.io/crates/rug +[`rust-gmp`]: https://crates.io/crates/rust-gmp +[`ramp`]: https://crates.io/crates/ramp +[`apint`]: https://crates.io/crates/apint diff --git a/third_party/rust/num-bigint/RELEASES.md b/third_party/rust/num-bigint/RELEASES.md new file mode 100644 index 0000000000..911dd7835f --- /dev/null +++ b/third_party/rust/num-bigint/RELEASES.md @@ -0,0 +1,134 @@ +# Release 0.2.3 (2019-09-03) + +- [`Pow` is now implemented for `BigUint` exponents][77]. +- [The optional `quickcheck` feature enables implementations of `Arbitrary`][99]. +- See the [full comparison][compare-0.2.3] for performance enhancements and more! + +[77]: https://github.com/rust-num/num-bigint/pull/77 +[99]: https://github.com/rust-num/num-bigint/pull/99 +[compare-0.2.3]: https://github.com/rust-num/num-bigint/compare/num-bigint-0.2.2...num-bigint-0.2.3 + +**Contributors**: @cuviper, @lcnr, @maxbla, @mikelodder7, @mikong, +@TheLetterTheta, @tspiteri, @XAMPPRocky, @youknowone + +# Release 0.2.2 (2018-12-14) + +- [The `Roots` implementations now use better initial guesses][71]. +- [Fixed `to_signed_bytes_*` for some positive numbers][72], where the + most-significant byte is `0x80` and the rest are `0`. + +[71]: https://github.com/rust-num/num-bigint/pull/71 +[72]: https://github.com/rust-num/num-bigint/pull/72 + +**Contributors**: @cuviper, @leodasvacas + +# Release 0.2.1 (2018-11-02) + +- [`RandBigInt` now uses `Rng::fill_bytes`][53] to improve performance, instead + of repeated `gen::<u32>` calls. The also affects the implementations of the + other `rand` traits. This may potentially change the values produced by some + seeded RNGs on previous versions, but the values were tested to be stable + with `ChaChaRng`, `IsaacRng`, and `XorShiftRng`. +- [`BigInt` and `BigUint` now implement `num_integer::Roots`][56]. +- [`BigInt` and `BigUint` now implement `num_traits::Pow`][54]. +- [`BigInt` and `BigUint` now implement operators with 128-bit integers][64]. + +**Contributors**: @cuviper, @dignifiedquire, @mancabizjak, @Robbepop, +@TheIronBorn, @thomwiggers + +[53]: https://github.com/rust-num/num-bigint/pull/53 +[54]: https://github.com/rust-num/num-bigint/pull/54 +[56]: https://github.com/rust-num/num-bigint/pull/56 +[64]: https://github.com/rust-num/num-bigint/pull/64 + +# Release 0.2.0 (2018-05-25) + +### Enhancements + +- [`BigInt` and `BigUint` now implement `Product` and `Sum`][22] for iterators + of any item that we can `Mul` and `Add`, respectively. For example, a + factorial can now be simply: `let f: BigUint = (1u32..1000).product();` +- [`BigInt` now supports two's-complement logic operations][26], namely + `BitAnd`, `BitOr`, `BitXor`, and `Not`. These act conceptually as if each + number had an infinite prefix of `0` or `1` bits for positive or negative. +- [`BigInt` now supports assignment operators][41] like `AddAssign`. +- [`BigInt` and `BigUint` now support conversions with `i128` and `u128`][44], + if sufficient compiler support is detected. +- [`BigInt` and `BigUint` now implement rand's `SampleUniform` trait][48], and + [a custom `RandomBits` distribution samples by bit size][49]. +- The release also includes other miscellaneous improvements to performance. + +### Breaking Changes + +- [`num-bigint` now requires rustc 1.15 or greater][23]. +- [The crate now has a `std` feature, and won't build without it][46]. This is + in preparation for someday supporting `#![no_std]` with `alloc`. +- [The `serde` dependency has been updated to 1.0][24], still disabled by + default. The `rustc-serialize` crate is no longer supported by `num-bigint`. +- [The `rand` dependency has been updated to 0.5][48], now disabled by default. + This requires rustc 1.22 or greater for `rand`'s own requirement. +- [`Shr for BigInt` now rounds down][8] rather than toward zero, matching the + behavior of the primitive integers for negative values. +- [`ParseBigIntError` is now an opaque type][37]. +- [The `big_digit` module is no longer public][38], nor are the `BigDigit` and + `DoubleBigDigit` types and `ZERO_BIG_DIGIT` constant that were re-exported in + the crate root. Public APIs which deal in digits, like `BigUint::from_slice`, + will now always be base-`u32`. + +**Contributors**: @clarcharr, @cuviper, @dodomorandi, @tiehuis, @tspiteri + +[8]: https://github.com/rust-num/num-bigint/pull/8 +[22]: https://github.com/rust-num/num-bigint/pull/22 +[23]: https://github.com/rust-num/num-bigint/pull/23 +[24]: https://github.com/rust-num/num-bigint/pull/24 +[26]: https://github.com/rust-num/num-bigint/pull/26 +[37]: https://github.com/rust-num/num-bigint/pull/37 +[38]: https://github.com/rust-num/num-bigint/pull/38 +[41]: https://github.com/rust-num/num-bigint/pull/41 +[44]: https://github.com/rust-num/num-bigint/pull/44 +[46]: https://github.com/rust-num/num-bigint/pull/46 +[48]: https://github.com/rust-num/num-bigint/pull/48 +[49]: https://github.com/rust-num/num-bigint/pull/49 + +# Release 0.1.44 (2018-05-14) + +- [Division with single-digit divisors is now much faster.][42] +- The README now compares [`ramp`, `rug`, `rust-gmp`][20], and [`apint`][21]. + +**Contributors**: @cuviper, @Robbepop + +[20]: https://github.com/rust-num/num-bigint/pull/20 +[21]: https://github.com/rust-num/num-bigint/pull/21 +[42]: https://github.com/rust-num/num-bigint/pull/42 + +# Release 0.1.43 (2018-02-08) + +- [The new `BigInt::modpow`][18] performs signed modular exponentiation, using + the existing `BigUint::modpow` and rounding negatives similar to `mod_floor`. + +**Contributors**: @cuviper + +[18]: https://github.com/rust-num/num-bigint/pull/18 + + +# Release 0.1.42 (2018-02-07) + +- [num-bigint now has its own source repository][num-356] at [rust-num/num-bigint][home]. +- [`lcm` now avoids creating a large intermediate product][num-350]. +- [`gcd` now uses Stein's algorithm][15] with faster shifts instead of division. +- [`rand` support is now extended to 0.4][11] (while still allowing 0.3). + +**Contributors**: @cuviper, @Emerentius, @ignatenkobrain, @mhogrefe + +[home]: https://github.com/rust-num/num-bigint +[num-350]: https://github.com/rust-num/num/pull/350 +[num-356]: https://github.com/rust-num/num/pull/356 +[11]: https://github.com/rust-num/num-bigint/pull/11 +[15]: https://github.com/rust-num/num-bigint/pull/15 + + +# Prior releases + +No prior release notes were kept. Thanks all the same to the many +contributors that have made this crate what it is! + diff --git a/third_party/rust/num-bigint/benches/bigint.rs b/third_party/rust/num-bigint/benches/bigint.rs new file mode 100644 index 0000000000..bc0875d8f6 --- /dev/null +++ b/third_party/rust/num-bigint/benches/bigint.rs @@ -0,0 +1,368 @@ +#![feature(test)] +#![cfg(feature = "rand")] + +extern crate num_bigint; +extern crate num_integer; +extern crate num_traits; +extern crate rand; +extern crate test; + +use num_bigint::{BigInt, BigUint, RandBigInt}; +use num_traits::{FromPrimitive, Num, One, Pow, Zero}; +use rand::{SeedableRng, StdRng}; +use std::mem::replace; +use test::Bencher; + +fn get_rng() -> StdRng { + let mut seed = [0; 32]; + for i in 1..32 { + seed[usize::from(i)] = i; + } + SeedableRng::from_seed(seed) +} + +fn multiply_bench(b: &mut Bencher, xbits: usize, ybits: usize) { + let mut rng = get_rng(); + let x = rng.gen_bigint(xbits); + let y = rng.gen_bigint(ybits); + + b.iter(|| &x * &y); +} + +fn divide_bench(b: &mut Bencher, xbits: usize, ybits: usize) { + let mut rng = get_rng(); + let x = rng.gen_bigint(xbits); + let y = rng.gen_bigint(ybits); + + b.iter(|| &x / &y); +} + +fn remainder_bench(b: &mut Bencher, xbits: usize, ybits: usize) { + let mut rng = get_rng(); + let x = rng.gen_bigint(xbits); + let y = rng.gen_bigint(ybits); + + b.iter(|| &x % &y); +} + +fn factorial(n: usize) -> BigUint { + let mut f: BigUint = One::one(); + for i in 1..(n + 1) { + let bu: BigUint = FromPrimitive::from_usize(i).unwrap(); + f = f * bu; + } + f +} + +/// Compute Fibonacci numbers +fn fib(n: usize) -> BigUint { + let mut f0: BigUint = Zero::zero(); + let mut f1: BigUint = One::one(); + for _ in 0..n { + let f2 = f0 + &f1; + f0 = replace(&mut f1, f2); + } + f0 +} + +/// Compute Fibonacci numbers with two ops per iteration +/// (add and subtract, like issue #200) +fn fib2(n: usize) -> BigUint { + let mut f0: BigUint = Zero::zero(); + let mut f1: BigUint = One::one(); + for _ in 0..n { + f1 = f1 + &f0; + f0 = &f1 - f0; + } + f0 +} + +#[bench] +fn multiply_0(b: &mut Bencher) { + multiply_bench(b, 1 << 8, 1 << 8); +} + +#[bench] +fn multiply_1(b: &mut Bencher) { + multiply_bench(b, 1 << 8, 1 << 16); +} + +#[bench] +fn multiply_2(b: &mut Bencher) { + multiply_bench(b, 1 << 16, 1 << 16); +} + +#[bench] +fn multiply_3(b: &mut Bencher) { + multiply_bench(b, 1 << 16, 1 << 17); +} + +#[bench] +fn divide_0(b: &mut Bencher) { + divide_bench(b, 1 << 8, 1 << 6); +} + +#[bench] +fn divide_1(b: &mut Bencher) { + divide_bench(b, 1 << 12, 1 << 8); +} + +#[bench] +fn divide_2(b: &mut Bencher) { + divide_bench(b, 1 << 16, 1 << 12); +} + +#[bench] +fn remainder_0(b: &mut Bencher) { + remainder_bench(b, 1 << 8, 1 << 6); +} + +#[bench] +fn remainder_1(b: &mut Bencher) { + remainder_bench(b, 1 << 12, 1 << 8); +} + +#[bench] +fn remainder_2(b: &mut Bencher) { + remainder_bench(b, 1 << 16, 1 << 12); +} + +#[bench] +fn factorial_100(b: &mut Bencher) { + b.iter(|| factorial(100)); +} + +#[bench] +fn fib_100(b: &mut Bencher) { + b.iter(|| fib(100)); +} + +#[bench] +fn fib_1000(b: &mut Bencher) { + b.iter(|| fib(1000)); +} + +#[bench] +fn fib_10000(b: &mut Bencher) { + b.iter(|| fib(10000)); +} + +#[bench] +fn fib2_100(b: &mut Bencher) { + b.iter(|| fib2(100)); +} + +#[bench] +fn fib2_1000(b: &mut Bencher) { + b.iter(|| fib2(1000)); +} + +#[bench] +fn fib2_10000(b: &mut Bencher) { + b.iter(|| fib2(10000)); +} + +#[bench] +fn fac_to_string(b: &mut Bencher) { + let fac = factorial(100); + b.iter(|| fac.to_string()); +} + +#[bench] +fn fib_to_string(b: &mut Bencher) { + let fib = fib(100); + b.iter(|| fib.to_string()); +} + +fn to_str_radix_bench(b: &mut Bencher, radix: u32) { + let mut rng = get_rng(); + let x = rng.gen_bigint(1009); + b.iter(|| x.to_str_radix(radix)); +} + +#[bench] +fn to_str_radix_02(b: &mut Bencher) { + to_str_radix_bench(b, 2); +} + +#[bench] +fn to_str_radix_08(b: &mut Bencher) { + to_str_radix_bench(b, 8); +} + +#[bench] +fn to_str_radix_10(b: &mut Bencher) { + to_str_radix_bench(b, 10); +} + +#[bench] +fn to_str_radix_16(b: &mut Bencher) { + to_str_radix_bench(b, 16); +} + +#[bench] +fn to_str_radix_36(b: &mut Bencher) { + to_str_radix_bench(b, 36); +} + +fn from_str_radix_bench(b: &mut Bencher, radix: u32) { + let mut rng = get_rng(); + let x = rng.gen_bigint(1009); + let s = x.to_str_radix(radix); + assert_eq!(x, BigInt::from_str_radix(&s, radix).unwrap()); + b.iter(|| BigInt::from_str_radix(&s, radix)); +} + +#[bench] +fn from_str_radix_02(b: &mut Bencher) { + from_str_radix_bench(b, 2); +} + +#[bench] +fn from_str_radix_08(b: &mut Bencher) { + from_str_radix_bench(b, 8); +} + +#[bench] +fn from_str_radix_10(b: &mut Bencher) { + from_str_radix_bench(b, 10); +} + +#[bench] +fn from_str_radix_16(b: &mut Bencher) { + from_str_radix_bench(b, 16); +} + +#[bench] +fn from_str_radix_36(b: &mut Bencher) { + from_str_radix_bench(b, 36); +} + +fn rand_bench(b: &mut Bencher, bits: usize) { + let mut rng = get_rng(); + + b.iter(|| rng.gen_bigint(bits)); +} + +#[bench] +fn rand_64(b: &mut Bencher) { + rand_bench(b, 1 << 6); +} + +#[bench] +fn rand_256(b: &mut Bencher) { + rand_bench(b, 1 << 8); +} + +#[bench] +fn rand_1009(b: &mut Bencher) { + rand_bench(b, 1009); +} + +#[bench] +fn rand_2048(b: &mut Bencher) { + rand_bench(b, 1 << 11); +} + +#[bench] +fn rand_4096(b: &mut Bencher) { + rand_bench(b, 1 << 12); +} + +#[bench] +fn rand_8192(b: &mut Bencher) { + rand_bench(b, 1 << 13); +} + +#[bench] +fn rand_65536(b: &mut Bencher) { + rand_bench(b, 1 << 16); +} + +#[bench] +fn rand_131072(b: &mut Bencher) { + rand_bench(b, 1 << 17); +} + +#[bench] +fn shl(b: &mut Bencher) { + let n = BigUint::one() << 1000; + b.iter(|| { + let mut m = n.clone(); + for i in 0..50 { + m = m << i; + } + }) +} + +#[bench] +fn shr(b: &mut Bencher) { + let n = BigUint::one() << 2000; + b.iter(|| { + let mut m = n.clone(); + for i in 0..50 { + m = m >> i; + } + }) +} + +#[bench] +fn hash(b: &mut Bencher) { + use std::collections::HashSet; + let mut rng = get_rng(); + let v: Vec<BigInt> = (1000..2000).map(|bits| rng.gen_bigint(bits)).collect(); + b.iter(|| { + let h: HashSet<&BigInt> = v.iter().collect(); + assert_eq!(h.len(), v.len()); + }); +} + +#[bench] +fn pow_bench(b: &mut Bencher) { + b.iter(|| { + let upper = 100_usize; + for i in 2..upper + 1 { + for j in 2..upper + 1 { + let i_big = BigUint::from_usize(i).unwrap(); + i_big.pow(j); + } + } + }); +} + +/// This modulus is the prime from the 2048-bit MODP DH group: +/// https://tools.ietf.org/html/rfc3526#section-3 +const RFC3526_2048BIT_MODP_GROUP: &'static str = + "\ + FFFFFFFF_FFFFFFFF_C90FDAA2_2168C234_C4C6628B_80DC1CD1\ + 29024E08_8A67CC74_020BBEA6_3B139B22_514A0879_8E3404DD\ + EF9519B3_CD3A431B_302B0A6D_F25F1437_4FE1356D_6D51C245\ + E485B576_625E7EC6_F44C42E9_A637ED6B_0BFF5CB6_F406B7ED\ + EE386BFB_5A899FA5_AE9F2411_7C4B1FE6_49286651_ECE45B3D\ + C2007CB8_A163BF05_98DA4836_1C55D39A_69163FA8_FD24CF5F\ + 83655D23_DCA3AD96_1C62F356_208552BB_9ED52907_7096966D\ + 670C354E_4ABC9804_F1746C08_CA18217C_32905E46_2E36CE3B\ + E39E772C_180E8603_9B2783A2_EC07A28F_B5C55DF0_6F4C52C9\ + DE2BCBF6_95581718_3995497C_EA956AE5_15D22618_98FA0510\ + 15728E5A_8AACAA68_FFFFFFFF_FFFFFFFF"; + +#[bench] +fn modpow(b: &mut Bencher) { + let mut rng = get_rng(); + let base = rng.gen_biguint(2048); + let e = rng.gen_biguint(2048); + let m = BigUint::from_str_radix(RFC3526_2048BIT_MODP_GROUP, 16).unwrap(); + + b.iter(|| base.modpow(&e, &m)); +} + +#[bench] +fn modpow_even(b: &mut Bencher) { + let mut rng = get_rng(); + let base = rng.gen_biguint(2048); + let e = rng.gen_biguint(2048); + // Make the modulus even, so monty (base-2^32) doesn't apply. + let m = BigUint::from_str_radix(RFC3526_2048BIT_MODP_GROUP, 16).unwrap() - 1u32; + + b.iter(|| base.modpow(&e, &m)); +} diff --git a/third_party/rust/num-bigint/benches/factorial.rs b/third_party/rust/num-bigint/benches/factorial.rs new file mode 100644 index 0000000000..4392df8319 --- /dev/null +++ b/third_party/rust/num-bigint/benches/factorial.rs @@ -0,0 +1,44 @@ +#![feature(test)] + +extern crate num_bigint; +extern crate num_traits; +extern crate test; + +use num_bigint::BigUint; +use num_traits::One; +use std::ops::{Div, Mul}; +use test::Bencher; + +#[bench] +fn factorial_mul_biguint(b: &mut Bencher) { + b.iter(|| { + (1u32..1000) + .map(BigUint::from) + .fold(BigUint::one(), Mul::mul) + }); +} + +#[bench] +fn factorial_mul_u32(b: &mut Bencher) { + b.iter(|| (1u32..1000).fold(BigUint::one(), Mul::mul)); +} + +// The division test is inspired by this blog comparison: +// <https://tiehuis.github.io/big-integers-in-zig#division-test-single-limb> + +#[bench] +fn factorial_div_biguint(b: &mut Bencher) { + let n: BigUint = (1u32..1000).fold(BigUint::one(), Mul::mul); + b.iter(|| { + (1u32..1000) + .rev() + .map(BigUint::from) + .fold(n.clone(), Div::div) + }); +} + +#[bench] +fn factorial_div_u32(b: &mut Bencher) { + let n: BigUint = (1u32..1000).fold(BigUint::one(), Mul::mul); + b.iter(|| (1u32..1000).rev().fold(n.clone(), Div::div)); +} diff --git a/third_party/rust/num-bigint/benches/gcd.rs b/third_party/rust/num-bigint/benches/gcd.rs new file mode 100644 index 0000000000..5fe5260ddf --- /dev/null +++ b/third_party/rust/num-bigint/benches/gcd.rs @@ -0,0 +1,86 @@ +#![feature(test)] +#![cfg(feature = "rand")] + +extern crate num_bigint; +extern crate num_integer; +extern crate num_traits; +extern crate rand; +extern crate test; + +use num_bigint::{BigUint, RandBigInt}; +use num_integer::Integer; +use num_traits::Zero; +use rand::{SeedableRng, StdRng}; +use test::Bencher; + +fn get_rng() -> StdRng { + let mut seed = [0; 32]; + for i in 1..32 { + seed[usize::from(i)] = i; + } + SeedableRng::from_seed(seed) +} + +fn bench(b: &mut Bencher, bits: usize, gcd: fn(&BigUint, &BigUint) -> BigUint) { + let mut rng = get_rng(); + let x = rng.gen_biguint(bits); + let y = rng.gen_biguint(bits); + + assert_eq!(euclid(&x, &y), x.gcd(&y)); + + b.iter(|| gcd(&x, &y)); +} + +fn euclid(x: &BigUint, y: &BigUint) -> BigUint { + // Use Euclid's algorithm + let mut m = x.clone(); + let mut n = y.clone(); + while !m.is_zero() { + let temp = m; + m = n % &temp; + n = temp; + } + return n; +} + +#[bench] +fn gcd_euclid_0064(b: &mut Bencher) { + bench(b, 64, euclid); +} + +#[bench] +fn gcd_euclid_0256(b: &mut Bencher) { + bench(b, 256, euclid); +} + +#[bench] +fn gcd_euclid_1024(b: &mut Bencher) { + bench(b, 1024, euclid); +} + +#[bench] +fn gcd_euclid_4096(b: &mut Bencher) { + bench(b, 4096, euclid); +} + +// Integer for BigUint now uses Stein for gcd + +#[bench] +fn gcd_stein_0064(b: &mut Bencher) { + bench(b, 64, BigUint::gcd); +} + +#[bench] +fn gcd_stein_0256(b: &mut Bencher) { + bench(b, 256, BigUint::gcd); +} + +#[bench] +fn gcd_stein_1024(b: &mut Bencher) { + bench(b, 1024, BigUint::gcd); +} + +#[bench] +fn gcd_stein_4096(b: &mut Bencher) { + bench(b, 4096, BigUint::gcd); +} diff --git a/third_party/rust/num-bigint/benches/roots.rs b/third_party/rust/num-bigint/benches/roots.rs new file mode 100644 index 0000000000..51e67d9f3d --- /dev/null +++ b/third_party/rust/num-bigint/benches/roots.rs @@ -0,0 +1,176 @@ +#![feature(test)] +#![cfg(feature = "rand")] + +extern crate num_bigint; +extern crate num_traits; +extern crate rand; +extern crate test; + +use num_bigint::{BigUint, RandBigInt}; +use num_traits::Pow; +use rand::{SeedableRng, StdRng}; +use test::Bencher; + +// The `big64` cases demonstrate the speed of cases where the value +// can be converted to a `u64` primitive for faster calculation. +// +// The `big1k` cases demonstrate those that can convert to `f64` for +// a better initial guess of the actual value. +// +// The `big2k` and `big4k` cases are too big for `f64`, and use a simpler guess. + +fn get_rng() -> StdRng { + let mut seed = [0; 32]; + for i in 1..32 { + seed[usize::from(i)] = i; + } + SeedableRng::from_seed(seed) +} + +fn check(x: &BigUint, n: u32) { + let root = x.nth_root(n); + if n == 2 { + assert_eq!(root, x.sqrt()) + } else if n == 3 { + assert_eq!(root, x.cbrt()) + } + + let lo = root.pow(n); + assert!(lo <= *x); + assert_eq!(lo.nth_root(n), root); + assert_eq!((&lo - 1u32).nth_root(n), &root - 1u32); + + let hi = (&root + 1u32).pow(n); + assert!(hi > *x); + assert_eq!(hi.nth_root(n), &root + 1u32); + assert_eq!((&hi - 1u32).nth_root(n), root); +} + +fn bench_sqrt(b: &mut Bencher, bits: usize) { + let x = get_rng().gen_biguint(bits); + eprintln!("bench_sqrt({})", x); + + check(&x, 2); + b.iter(|| x.sqrt()); +} + +#[bench] +fn big64_sqrt(b: &mut Bencher) { + bench_sqrt(b, 64); +} + +#[bench] +fn big1k_sqrt(b: &mut Bencher) { + bench_sqrt(b, 1024); +} + +#[bench] +fn big2k_sqrt(b: &mut Bencher) { + bench_sqrt(b, 2048); +} + +#[bench] +fn big4k_sqrt(b: &mut Bencher) { + bench_sqrt(b, 4096); +} + +fn bench_cbrt(b: &mut Bencher, bits: usize) { + let x = get_rng().gen_biguint(bits); + eprintln!("bench_cbrt({})", x); + + check(&x, 3); + b.iter(|| x.cbrt()); +} + +#[bench] +fn big64_cbrt(b: &mut Bencher) { + bench_cbrt(b, 64); +} + +#[bench] +fn big1k_cbrt(b: &mut Bencher) { + bench_cbrt(b, 1024); +} + +#[bench] +fn big2k_cbrt(b: &mut Bencher) { + bench_cbrt(b, 2048); +} + +#[bench] +fn big4k_cbrt(b: &mut Bencher) { + bench_cbrt(b, 4096); +} + +fn bench_nth_root(b: &mut Bencher, bits: usize, n: u32) { + let x = get_rng().gen_biguint(bits); + eprintln!("bench_{}th_root({})", n, x); + + check(&x, n); + b.iter(|| x.nth_root(n)); +} + +#[bench] +fn big64_nth_10(b: &mut Bencher) { + bench_nth_root(b, 64, 10); +} + +#[bench] +fn big1k_nth_10(b: &mut Bencher) { + bench_nth_root(b, 1024, 10); +} + +#[bench] +fn big1k_nth_100(b: &mut Bencher) { + bench_nth_root(b, 1024, 100); +} + +#[bench] +fn big1k_nth_1000(b: &mut Bencher) { + bench_nth_root(b, 1024, 1000); +} + +#[bench] +fn big1k_nth_10000(b: &mut Bencher) { + bench_nth_root(b, 1024, 10000); +} + +#[bench] +fn big2k_nth_10(b: &mut Bencher) { + bench_nth_root(b, 2048, 10); +} + +#[bench] +fn big2k_nth_100(b: &mut Bencher) { + bench_nth_root(b, 2048, 100); +} + +#[bench] +fn big2k_nth_1000(b: &mut Bencher) { + bench_nth_root(b, 2048, 1000); +} + +#[bench] +fn big2k_nth_10000(b: &mut Bencher) { + bench_nth_root(b, 2048, 10000); +} + +#[bench] +fn big4k_nth_10(b: &mut Bencher) { + bench_nth_root(b, 4096, 10); +} + +#[bench] +fn big4k_nth_100(b: &mut Bencher) { + bench_nth_root(b, 4096, 100); +} + +#[bench] +fn big4k_nth_1000(b: &mut Bencher) { + bench_nth_root(b, 4096, 1000); +} + +#[bench] +fn big4k_nth_10000(b: &mut Bencher) { + bench_nth_root(b, 4096, 10000); +} diff --git a/third_party/rust/num-bigint/benches/shootout-pidigits.rs b/third_party/rust/num-bigint/benches/shootout-pidigits.rs new file mode 100644 index 0000000000..f90a697357 --- /dev/null +++ b/third_party/rust/num-bigint/benches/shootout-pidigits.rs @@ -0,0 +1,142 @@ +// The Computer Language Benchmarks Game +// http://benchmarksgame.alioth.debian.org/ +// +// contributed by the Rust Project Developers + +// Copyright (c) 2013-2014 The Rust Project Developers +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// +// - Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// - Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in +// the documentation and/or other materials provided with the +// distribution. +// +// - Neither the name of "The Computer Language Benchmarks Game" nor +// the name of "The Computer Language Shootout Benchmarks" nor the +// names of its contributors may be used to endorse or promote +// products derived from this software without specific prior +// written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED +// OF THE POSSIBILITY OF SUCH DAMAGE. + +extern crate num_bigint; +extern crate num_integer; +extern crate num_traits; + +use std::io; +use std::str::FromStr; + +use num_bigint::BigInt; +use num_integer::Integer; +use num_traits::{FromPrimitive, One, ToPrimitive, Zero}; + +struct Context { + numer: BigInt, + accum: BigInt, + denom: BigInt, +} + +impl Context { + fn new() -> Context { + Context { + numer: One::one(), + accum: Zero::zero(), + denom: One::one(), + } + } + + fn from_i32(i: i32) -> BigInt { + FromPrimitive::from_i32(i).unwrap() + } + + fn extract_digit(&self) -> i32 { + if self.numer > self.accum { + return -1; + } + let (q, r) = (&self.numer * Context::from_i32(3) + &self.accum).div_rem(&self.denom); + if r + &self.numer >= self.denom { + return -1; + } + q.to_i32().unwrap() + } + + fn next_term(&mut self, k: i32) { + let y2 = Context::from_i32(k * 2 + 1); + self.accum = (&self.accum + (&self.numer << 1)) * &y2; + self.numer = &self.numer * Context::from_i32(k); + self.denom = &self.denom * y2; + } + + fn eliminate_digit(&mut self, d: i32) { + let d = Context::from_i32(d); + let ten = Context::from_i32(10); + self.accum = (&self.accum - &self.denom * d) * &ten; + self.numer = &self.numer * ten; + } +} + +fn pidigits(n: isize, out: &mut dyn io::Write) -> io::Result<()> { + let mut k = 0; + let mut context = Context::new(); + + for i in 1..(n + 1) { + let mut d; + loop { + k += 1; + context.next_term(k); + d = context.extract_digit(); + if d != -1 { + break; + } + } + + write!(out, "{}", d)?; + if i % 10 == 0 { + write!(out, "\t:{}\n", i)?; + } + + context.eliminate_digit(d); + } + + let m = n % 10; + if m != 0 { + for _ in m..10 { + write!(out, " ")?; + } + write!(out, "\t:{}\n", n)?; + } + Ok(()) +} + +const DEFAULT_DIGITS: isize = 512; + +fn main() { + let args = std::env::args().collect::<Vec<_>>(); + let n = if args.len() < 2 { + DEFAULT_DIGITS + } else if args[1] == "--bench" { + return pidigits(DEFAULT_DIGITS, &mut std::io::sink()).unwrap(); + } else { + FromStr::from_str(&args[1]).unwrap() + }; + pidigits(n, &mut std::io::stdout()).unwrap(); +} diff --git a/third_party/rust/num-bigint/bors.toml b/third_party/rust/num-bigint/bors.toml new file mode 100644 index 0000000000..ca08e818bf --- /dev/null +++ b/third_party/rust/num-bigint/bors.toml @@ -0,0 +1,3 @@ +status = [ + "continuous-integration/travis-ci/push", +] diff --git a/third_party/rust/num-bigint/build.rs b/third_party/rust/num-bigint/build.rs new file mode 100644 index 0000000000..15590bbc12 --- /dev/null +++ b/third_party/rust/num-bigint/build.rs @@ -0,0 +1,14 @@ +extern crate autocfg; + +use std::env; + +fn main() { + let ac = autocfg::new(); + if ac.probe_type("i128") { + println!("cargo:rustc-cfg=has_i128"); + } else if env::var_os("CARGO_FEATURE_I128").is_some() { + panic!("i128 support was not detected!"); + } + + autocfg::rerun_path(file!()); +} diff --git a/third_party/rust/num-bigint/ci/rustup.sh b/third_party/rust/num-bigint/ci/rustup.sh new file mode 100755 index 0000000000..c5aea794b5 --- /dev/null +++ b/third_party/rust/num-bigint/ci/rustup.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# Use rustup to locally run the same suite of tests as .travis.yml. +# (You should first install/update all versions listed below.) + +set -ex + +export TRAVIS_RUST_VERSION +for TRAVIS_RUST_VERSION in 1.15.0 1.22.0 1.26.0 stable beta nightly; do + run="rustup run $TRAVIS_RUST_VERSION" + $run cargo build --verbose + $run $PWD/ci/test_full.sh +done diff --git a/third_party/rust/num-bigint/ci/test_full.sh b/third_party/rust/num-bigint/ci/test_full.sh new file mode 100755 index 0000000000..4e1b60e98a --- /dev/null +++ b/third_party/rust/num-bigint/ci/test_full.sh @@ -0,0 +1,39 @@ +#!/bin/bash + +set -ex + +echo Testing num-bigint on rustc ${TRAVIS_RUST_VERSION} + +FEATURES="serde" +if [[ "$TRAVIS_RUST_VERSION" =~ ^(nightly|beta|stable|1.31.0|1.26.0|1.22.0)$ ]]; then + FEATURES="$FEATURES rand" +fi +if [[ "$TRAVIS_RUST_VERSION" =~ ^(nightly|beta|stable|1.31.0|1.26.0)$ ]]; then + FEATURES="$FEATURES i128" +fi +if [[ "$TRAVIS_RUST_VERSION" =~ ^(nightly|beta|stable|1.31.0)$ ]]; then + FEATURES="$FEATURES quickcheck quickcheck_macros" +fi + +# num-bigint should build and test everywhere. +cargo build --verbose +cargo test --verbose + +# It should build with minimal features too. +cargo build --no-default-features --features="std" +cargo test --no-default-features --features="std" + +# Each isolated feature should also work everywhere. +for feature in $FEATURES; do + cargo build --verbose --no-default-features --features="std $feature" + cargo test --verbose --no-default-features --features="std $feature" +done + +# test all supported features together +cargo build --features="std $FEATURES" +cargo test --features="std $FEATURES" + +# make sure benchmarks can be built +if [[ "$TRAVIS_RUST_VERSION" == "nightly" ]]; then + cargo bench --all-features --no-run +fi diff --git a/third_party/rust/num-bigint/src/algorithms.rs b/third_party/rust/num-bigint/src/algorithms.rs new file mode 100644 index 0000000000..26f29b8154 --- /dev/null +++ b/third_party/rust/num-bigint/src/algorithms.rs @@ -0,0 +1,789 @@ +use std::borrow::Cow; +use std::cmp; +use std::cmp::Ordering::{self, Equal, Greater, Less}; +use std::iter::repeat; +use std::mem; +use traits; +use traits::{One, Zero}; + +use biguint::BigUint; + +use bigint::BigInt; +use bigint::Sign; +use bigint::Sign::{Minus, NoSign, Plus}; + +use big_digit::{self, BigDigit, DoubleBigDigit, SignedDoubleBigDigit}; + +// Generic functions for add/subtract/multiply with carry/borrow: + +// Add with carry: +#[inline] +fn adc(a: BigDigit, b: BigDigit, acc: &mut DoubleBigDigit) -> BigDigit { + *acc += DoubleBigDigit::from(a); + *acc += DoubleBigDigit::from(b); + let lo = *acc as BigDigit; + *acc >>= big_digit::BITS; + lo +} + +// Subtract with borrow: +#[inline] +fn sbb(a: BigDigit, b: BigDigit, acc: &mut SignedDoubleBigDigit) -> BigDigit { + *acc += SignedDoubleBigDigit::from(a); + *acc -= SignedDoubleBigDigit::from(b); + let lo = *acc as BigDigit; + *acc >>= big_digit::BITS; + lo +} + +#[inline] +pub fn mac_with_carry(a: BigDigit, b: BigDigit, c: BigDigit, acc: &mut DoubleBigDigit) -> BigDigit { + *acc += DoubleBigDigit::from(a); + *acc += DoubleBigDigit::from(b) * DoubleBigDigit::from(c); + let lo = *acc as BigDigit; + *acc >>= big_digit::BITS; + lo +} + +#[inline] +pub fn mul_with_carry(a: BigDigit, b: BigDigit, acc: &mut DoubleBigDigit) -> BigDigit { + *acc += DoubleBigDigit::from(a) * DoubleBigDigit::from(b); + let lo = *acc as BigDigit; + *acc >>= big_digit::BITS; + lo +} + +/// Divide a two digit numerator by a one digit divisor, returns quotient and remainder: +/// +/// Note: the caller must ensure that both the quotient and remainder will fit into a single digit. +/// This is _not_ true for an arbitrary numerator/denominator. +/// +/// (This function also matches what the x86 divide instruction does). +#[inline] +fn div_wide(hi: BigDigit, lo: BigDigit, divisor: BigDigit) -> (BigDigit, BigDigit) { + debug_assert!(hi < divisor); + + let lhs = big_digit::to_doublebigdigit(hi, lo); + let rhs = DoubleBigDigit::from(divisor); + ((lhs / rhs) as BigDigit, (lhs % rhs) as BigDigit) +} + +pub fn div_rem_digit(mut a: BigUint, b: BigDigit) -> (BigUint, BigDigit) { + let mut rem = 0; + + for d in a.data.iter_mut().rev() { + let (q, r) = div_wide(rem, *d, b); + *d = q; + rem = r; + } + + (a.normalized(), rem) +} + +pub fn rem_digit(a: &BigUint, b: BigDigit) -> BigDigit { + let mut rem: DoubleBigDigit = 0; + for &digit in a.data.iter().rev() { + rem = (rem << big_digit::BITS) + DoubleBigDigit::from(digit); + rem %= DoubleBigDigit::from(b); + } + + rem as BigDigit +} + +// Only for the Add impl: +#[inline] +pub fn __add2(a: &mut [BigDigit], b: &[BigDigit]) -> BigDigit { + debug_assert!(a.len() >= b.len()); + + let mut carry = 0; + let (a_lo, a_hi) = a.split_at_mut(b.len()); + + for (a, b) in a_lo.iter_mut().zip(b) { + *a = adc(*a, *b, &mut carry); + } + + if carry != 0 { + for a in a_hi { + *a = adc(*a, 0, &mut carry); + if carry == 0 { + break; + } + } + } + + carry as BigDigit +} + +/// Two argument addition of raw slices: +/// a += b +/// +/// The caller _must_ ensure that a is big enough to store the result - typically this means +/// resizing a to max(a.len(), b.len()) + 1, to fit a possible carry. +pub fn add2(a: &mut [BigDigit], b: &[BigDigit]) { + let carry = __add2(a, b); + + debug_assert!(carry == 0); +} + +pub fn sub2(a: &mut [BigDigit], b: &[BigDigit]) { + let mut borrow = 0; + + let len = cmp::min(a.len(), b.len()); + let (a_lo, a_hi) = a.split_at_mut(len); + let (b_lo, b_hi) = b.split_at(len); + + for (a, b) in a_lo.iter_mut().zip(b_lo) { + *a = sbb(*a, *b, &mut borrow); + } + + if borrow != 0 { + for a in a_hi { + *a = sbb(*a, 0, &mut borrow); + if borrow == 0 { + break; + } + } + } + + // note: we're _required_ to fail on underflow + assert!( + borrow == 0 && b_hi.iter().all(|x| *x == 0), + "Cannot subtract b from a because b is larger than a." + ); +} + +// Only for the Sub impl. `a` and `b` must have same length. +#[inline] +pub fn __sub2rev(a: &[BigDigit], b: &mut [BigDigit]) -> BigDigit { + debug_assert!(b.len() == a.len()); + + let mut borrow = 0; + + for (ai, bi) in a.iter().zip(b) { + *bi = sbb(*ai, *bi, &mut borrow); + } + + borrow as BigDigit +} + +pub fn sub2rev(a: &[BigDigit], b: &mut [BigDigit]) { + debug_assert!(b.len() >= a.len()); + + let len = cmp::min(a.len(), b.len()); + let (a_lo, a_hi) = a.split_at(len); + let (b_lo, b_hi) = b.split_at_mut(len); + + let borrow = __sub2rev(a_lo, b_lo); + + assert!(a_hi.is_empty()); + + // note: we're _required_ to fail on underflow + assert!( + borrow == 0 && b_hi.iter().all(|x| *x == 0), + "Cannot subtract b from a because b is larger than a." + ); +} + +pub fn sub_sign(a: &[BigDigit], b: &[BigDigit]) -> (Sign, BigUint) { + // Normalize: + let a = &a[..a.iter().rposition(|&x| x != 0).map_or(0, |i| i + 1)]; + let b = &b[..b.iter().rposition(|&x| x != 0).map_or(0, |i| i + 1)]; + + match cmp_slice(a, b) { + Greater => { + let mut a = a.to_vec(); + sub2(&mut a, b); + (Plus, BigUint::new(a)) + } + Less => { + let mut b = b.to_vec(); + sub2(&mut b, a); + (Minus, BigUint::new(b)) + } + _ => (NoSign, Zero::zero()), + } +} + +/// Three argument multiply accumulate: +/// acc += b * c +pub fn mac_digit(acc: &mut [BigDigit], b: &[BigDigit], c: BigDigit) { + if c == 0 { + return; + } + + let mut carry = 0; + let (a_lo, a_hi) = acc.split_at_mut(b.len()); + + for (a, &b) in a_lo.iter_mut().zip(b) { + *a = mac_with_carry(*a, b, c, &mut carry); + } + + let mut a = a_hi.iter_mut(); + while carry != 0 { + let a = a.next().expect("carry overflow during multiplication!"); + *a = adc(*a, 0, &mut carry); + } +} + +/// Three argument multiply accumulate: +/// acc += b * c +fn mac3(acc: &mut [BigDigit], b: &[BigDigit], c: &[BigDigit]) { + let (x, y) = if b.len() < c.len() { (b, c) } else { (c, b) }; + + // We use three algorithms for different input sizes. + // + // - For small inputs, long multiplication is fastest. + // - Next we use Karatsuba multiplication (Toom-2), which we have optimized + // to avoid unnecessary allocations for intermediate values. + // - For the largest inputs we use Toom-3, which better optimizes the + // number of operations, but uses more temporary allocations. + // + // The thresholds are somewhat arbitrary, chosen by evaluating the results + // of `cargo bench --bench bigint multiply`. + + if x.len() <= 32 { + // Long multiplication: + for (i, xi) in x.iter().enumerate() { + mac_digit(&mut acc[i..], y, *xi); + } + } else if x.len() <= 256 { + /* + * Karatsuba multiplication: + * + * The idea is that we break x and y up into two smaller numbers that each have about half + * as many digits, like so (note that multiplying by b is just a shift): + * + * x = x0 + x1 * b + * y = y0 + y1 * b + * + * With some algebra, we can compute x * y with three smaller products, where the inputs to + * each of the smaller products have only about half as many digits as x and y: + * + * x * y = (x0 + x1 * b) * (y0 + y1 * b) + * + * x * y = x0 * y0 + * + x0 * y1 * b + * + x1 * y0 * b + * + x1 * y1 * b^2 + * + * Let p0 = x0 * y0 and p2 = x1 * y1: + * + * x * y = p0 + * + (x0 * y1 + x1 * y0) * b + * + p2 * b^2 + * + * The real trick is that middle term: + * + * x0 * y1 + x1 * y0 + * + * = x0 * y1 + x1 * y0 - p0 + p0 - p2 + p2 + * + * = x0 * y1 + x1 * y0 - x0 * y0 - x1 * y1 + p0 + p2 + * + * Now we complete the square: + * + * = -(x0 * y0 - x0 * y1 - x1 * y0 + x1 * y1) + p0 + p2 + * + * = -((x1 - x0) * (y1 - y0)) + p0 + p2 + * + * Let p1 = (x1 - x0) * (y1 - y0), and substitute back into our original formula: + * + * x * y = p0 + * + (p0 + p2 - p1) * b + * + p2 * b^2 + * + * Where the three intermediate products are: + * + * p0 = x0 * y0 + * p1 = (x1 - x0) * (y1 - y0) + * p2 = x1 * y1 + * + * In doing the computation, we take great care to avoid unnecessary temporary variables + * (since creating a BigUint requires a heap allocation): thus, we rearrange the formula a + * bit so we can use the same temporary variable for all the intermediate products: + * + * x * y = p2 * b^2 + p2 * b + * + p0 * b + p0 + * - p1 * b + * + * The other trick we use is instead of doing explicit shifts, we slice acc at the + * appropriate offset when doing the add. + */ + + /* + * When x is smaller than y, it's significantly faster to pick b such that x is split in + * half, not y: + */ + let b = x.len() / 2; + let (x0, x1) = x.split_at(b); + let (y0, y1) = y.split_at(b); + + /* + * We reuse the same BigUint for all the intermediate multiplies and have to size p + * appropriately here: x1.len() >= x0.len and y1.len() >= y0.len(): + */ + let len = x1.len() + y1.len() + 1; + let mut p = BigUint { data: vec![0; len] }; + + // p2 = x1 * y1 + mac3(&mut p.data[..], x1, y1); + + // Not required, but the adds go faster if we drop any unneeded 0s from the end: + p.normalize(); + + add2(&mut acc[b..], &p.data[..]); + add2(&mut acc[b * 2..], &p.data[..]); + + // Zero out p before the next multiply: + p.data.truncate(0); + p.data.extend(repeat(0).take(len)); + + // p0 = x0 * y0 + mac3(&mut p.data[..], x0, y0); + p.normalize(); + + add2(&mut acc[..], &p.data[..]); + add2(&mut acc[b..], &p.data[..]); + + // p1 = (x1 - x0) * (y1 - y0) + // We do this one last, since it may be negative and acc can't ever be negative: + let (j0_sign, j0) = sub_sign(x1, x0); + let (j1_sign, j1) = sub_sign(y1, y0); + + match j0_sign * j1_sign { + Plus => { + p.data.truncate(0); + p.data.extend(repeat(0).take(len)); + + mac3(&mut p.data[..], &j0.data[..], &j1.data[..]); + p.normalize(); + + sub2(&mut acc[b..], &p.data[..]); + } + Minus => { + mac3(&mut acc[b..], &j0.data[..], &j1.data[..]); + } + NoSign => (), + } + } else { + // Toom-3 multiplication: + // + // Toom-3 is like Karatsuba above, but dividing the inputs into three parts. + // Both are instances of Toom-Cook, using `k=3` and `k=2` respectively. + // + // The general idea is to treat the large integers digits as + // polynomials of a certain degree and determine the coefficients/digits + // of the product of the two via interpolation of the polynomial product. + let i = y.len() / 3 + 1; + + let x0_len = cmp::min(x.len(), i); + let x1_len = cmp::min(x.len() - x0_len, i); + + let y0_len = i; + let y1_len = cmp::min(y.len() - y0_len, i); + + // Break x and y into three parts, representating an order two polynomial. + // t is chosen to be the size of a digit so we can use faster shifts + // in place of multiplications. + // + // x(t) = x2*t^2 + x1*t + x0 + let x0 = BigInt::from_slice(Plus, &x[..x0_len]); + let x1 = BigInt::from_slice(Plus, &x[x0_len..x0_len + x1_len]); + let x2 = BigInt::from_slice(Plus, &x[x0_len + x1_len..]); + + // y(t) = y2*t^2 + y1*t + y0 + let y0 = BigInt::from_slice(Plus, &y[..y0_len]); + let y1 = BigInt::from_slice(Plus, &y[y0_len..y0_len + y1_len]); + let y2 = BigInt::from_slice(Plus, &y[y0_len + y1_len..]); + + // Let w(t) = x(t) * y(t) + // + // This gives us the following order-4 polynomial. + // + // w(t) = w4*t^4 + w3*t^3 + w2*t^2 + w1*t + w0 + // + // We need to find the coefficients w4, w3, w2, w1 and w0. Instead + // of simply multiplying the x and y in total, we can evaluate w + // at 5 points. An n-degree polynomial is uniquely identified by (n + 1) + // points. + // + // It is arbitrary as to what points we evaluate w at but we use the + // following. + // + // w(t) at t = 0, 1, -1, -2 and inf + // + // The values for w(t) in terms of x(t)*y(t) at these points are: + // + // let a = w(0) = x0 * y0 + // let b = w(1) = (x2 + x1 + x0) * (y2 + y1 + y0) + // let c = w(-1) = (x2 - x1 + x0) * (y2 - y1 + y0) + // let d = w(-2) = (4*x2 - 2*x1 + x0) * (4*y2 - 2*y1 + y0) + // let e = w(inf) = x2 * y2 as t -> inf + + // x0 + x2, avoiding temporaries + let p = &x0 + &x2; + + // y0 + y2, avoiding temporaries + let q = &y0 + &y2; + + // x2 - x1 + x0, avoiding temporaries + let p2 = &p - &x1; + + // y2 - y1 + y0, avoiding temporaries + let q2 = &q - &y1; + + // w(0) + let r0 = &x0 * &y0; + + // w(inf) + let r4 = &x2 * &y2; + + // w(1) + let r1 = (p + x1) * (q + y1); + + // w(-1) + let r2 = &p2 * &q2; + + // w(-2) + let r3 = ((p2 + x2) * 2 - x0) * ((q2 + y2) * 2 - y0); + + // Evaluating these points gives us the following system of linear equations. + // + // 0 0 0 0 1 | a + // 1 1 1 1 1 | b + // 1 -1 1 -1 1 | c + // 16 -8 4 -2 1 | d + // 1 0 0 0 0 | e + // + // The solved equation (after gaussian elimination or similar) + // in terms of its coefficients: + // + // w0 = w(0) + // w1 = w(0)/2 + w(1)/3 - w(-1) + w(2)/6 - 2*w(inf) + // w2 = -w(0) + w(1)/2 + w(-1)/2 - w(inf) + // w3 = -w(0)/2 + w(1)/6 + w(-1)/2 - w(1)/6 + // w4 = w(inf) + // + // This particular sequence is given by Bodrato and is an interpolation + // of the above equations. + let mut comp3: BigInt = (r3 - &r1) / 3; + let mut comp1: BigInt = (r1 - &r2) / 2; + let mut comp2: BigInt = r2 - &r0; + comp3 = (&comp2 - comp3) / 2 + &r4 * 2; + comp2 = comp2 + &comp1 - &r4; + comp1 = comp1 - &comp3; + + // Recomposition. The coefficients of the polynomial are now known. + // + // Evaluate at w(t) where t is our given base to get the result. + let result = r0 + + (comp1 << 32 * i) + + (comp2 << 2 * 32 * i) + + (comp3 << 3 * 32 * i) + + (r4 << 4 * 32 * i); + let result_pos = result.to_biguint().unwrap(); + add2(&mut acc[..], &result_pos.data); + } +} + +pub fn mul3(x: &[BigDigit], y: &[BigDigit]) -> BigUint { + let len = x.len() + y.len() + 1; + let mut prod = BigUint { data: vec![0; len] }; + + mac3(&mut prod.data[..], x, y); + prod.normalized() +} + +pub fn scalar_mul(a: &mut [BigDigit], b: BigDigit) -> BigDigit { + let mut carry = 0; + for a in a.iter_mut() { + *a = mul_with_carry(*a, b, &mut carry); + } + carry as BigDigit +} + +pub fn div_rem(mut u: BigUint, mut d: BigUint) -> (BigUint, BigUint) { + if d.is_zero() { + panic!() + } + if u.is_zero() { + return (Zero::zero(), Zero::zero()); + } + + if d.data.len() == 1 { + if d.data == [1] { + return (u, Zero::zero()); + } + let (div, rem) = div_rem_digit(u, d.data[0]); + // reuse d + d.data.clear(); + d += rem; + return (div, d); + } + + // Required or the q_len calculation below can underflow: + match u.cmp(&d) { + Less => return (Zero::zero(), u), + Equal => { + u.set_one(); + return (u, Zero::zero()); + } + Greater => {} // Do nothing + } + + // This algorithm is from Knuth, TAOCP vol 2 section 4.3, algorithm D: + // + // First, normalize the arguments so the highest bit in the highest digit of the divisor is + // set: the main loop uses the highest digit of the divisor for generating guesses, so we + // want it to be the largest number we can efficiently divide by. + // + let shift = d.data.last().unwrap().leading_zeros() as usize; + let (q, r) = if shift == 0 { + // no need to clone d + div_rem_core(u, &d) + } else { + div_rem_core(u << shift, &(d << shift)) + }; + // renormalize the remainder + (q, r >> shift) +} + +pub fn div_rem_ref(u: &BigUint, d: &BigUint) -> (BigUint, BigUint) { + if d.is_zero() { + panic!() + } + if u.is_zero() { + return (Zero::zero(), Zero::zero()); + } + + if d.data.len() == 1 { + if d.data == [1] { + return (u.clone(), Zero::zero()); + } + + let (div, rem) = div_rem_digit(u.clone(), d.data[0]); + return (div, rem.into()); + } + + // Required or the q_len calculation below can underflow: + match u.cmp(d) { + Less => return (Zero::zero(), u.clone()), + Equal => return (One::one(), Zero::zero()), + Greater => {} // Do nothing + } + + // This algorithm is from Knuth, TAOCP vol 2 section 4.3, algorithm D: + // + // First, normalize the arguments so the highest bit in the highest digit of the divisor is + // set: the main loop uses the highest digit of the divisor for generating guesses, so we + // want it to be the largest number we can efficiently divide by. + // + let shift = d.data.last().unwrap().leading_zeros() as usize; + + let (q, r) = if shift == 0 { + // no need to clone d + div_rem_core(u.clone(), d) + } else { + div_rem_core(u << shift, &(d << shift)) + }; + // renormalize the remainder + (q, r >> shift) +} + +/// an implementation of Knuth, TAOCP vol 2 section 4.3, algorithm D +/// +/// # Correctness +/// +/// This function requires the following conditions to run correctly and/or effectively +/// +/// - `a > b` +/// - `d.data.len() > 1` +/// - `d.data.last().unwrap().leading_zeros() == 0` +fn div_rem_core(mut a: BigUint, b: &BigUint) -> (BigUint, BigUint) { + // The algorithm works by incrementally calculating "guesses", q0, for part of the + // remainder. Once we have any number q0 such that q0 * b <= a, we can set + // + // q += q0 + // a -= q0 * b + // + // and then iterate until a < b. Then, (q, a) will be our desired quotient and remainder. + // + // q0, our guess, is calculated by dividing the last few digits of a by the last digit of b + // - this should give us a guess that is "close" to the actual quotient, but is possibly + // greater than the actual quotient. If q0 * b > a, we simply use iterated subtraction + // until we have a guess such that q0 * b <= a. + // + + let bn = *b.data.last().unwrap(); + let q_len = a.data.len() - b.data.len() + 1; + let mut q = BigUint { + data: vec![0; q_len], + }; + + // We reuse the same temporary to avoid hitting the allocator in our inner loop - this is + // sized to hold a0 (in the common case; if a particular digit of the quotient is zero a0 + // can be bigger). + // + let mut tmp = BigUint { + data: Vec::with_capacity(2), + }; + + for j in (0..q_len).rev() { + /* + * When calculating our next guess q0, we don't need to consider the digits below j + * + b.data.len() - 1: we're guessing digit j of the quotient (i.e. q0 << j) from + * digit bn of the divisor (i.e. bn << (b.data.len() - 1) - so the product of those + * two numbers will be zero in all digits up to (j + b.data.len() - 1). + */ + let offset = j + b.data.len() - 1; + if offset >= a.data.len() { + continue; + } + + /* just avoiding a heap allocation: */ + let mut a0 = tmp; + a0.data.truncate(0); + a0.data.extend(a.data[offset..].iter().cloned()); + + /* + * q0 << j * big_digit::BITS is our actual quotient estimate - we do the shifts + * implicitly at the end, when adding and subtracting to a and q. Not only do we + * save the cost of the shifts, the rest of the arithmetic gets to work with + * smaller numbers. + */ + let (mut q0, _) = div_rem_digit(a0, bn); + let mut prod = b * &q0; + + while cmp_slice(&prod.data[..], &a.data[j..]) == Greater { + let one: BigUint = One::one(); + q0 = q0 - one; + prod = prod - b; + } + + add2(&mut q.data[j..], &q0.data[..]); + sub2(&mut a.data[j..], &prod.data[..]); + a.normalize(); + + tmp = q0; + } + + debug_assert!(&a < b); + + (q.normalized(), a) +} + +/// Find last set bit +/// fls(0) == 0, fls(u32::MAX) == 32 +pub fn fls<T: traits::PrimInt>(v: T) -> usize { + mem::size_of::<T>() * 8 - v.leading_zeros() as usize +} + +pub fn ilog2<T: traits::PrimInt>(v: T) -> usize { + fls(v) - 1 +} + +#[inline] +pub fn biguint_shl(n: Cow<BigUint>, bits: usize) -> BigUint { + let n_unit = bits / big_digit::BITS; + let mut data = match n_unit { + 0 => n.into_owned().data, + _ => { + let len = n_unit + n.data.len() + 1; + let mut data = Vec::with_capacity(len); + data.extend(repeat(0).take(n_unit)); + data.extend(n.data.iter().cloned()); + data + } + }; + + let n_bits = bits % big_digit::BITS; + if n_bits > 0 { + let mut carry = 0; + for elem in data[n_unit..].iter_mut() { + let new_carry = *elem >> (big_digit::BITS - n_bits); + *elem = (*elem << n_bits) | carry; + carry = new_carry; + } + if carry != 0 { + data.push(carry); + } + } + + BigUint::new(data) +} + +#[inline] +pub fn biguint_shr(n: Cow<BigUint>, bits: usize) -> BigUint { + let n_unit = bits / big_digit::BITS; + if n_unit >= n.data.len() { + return Zero::zero(); + } + let mut data = match n { + Cow::Borrowed(n) => n.data[n_unit..].to_vec(), + Cow::Owned(mut n) => { + n.data.drain(..n_unit); + n.data + } + }; + + let n_bits = bits % big_digit::BITS; + if n_bits > 0 { + let mut borrow = 0; + for elem in data.iter_mut().rev() { + let new_borrow = *elem << (big_digit::BITS - n_bits); + *elem = (*elem >> n_bits) | borrow; + borrow = new_borrow; + } + } + + BigUint::new(data) +} + +pub fn cmp_slice(a: &[BigDigit], b: &[BigDigit]) -> Ordering { + debug_assert!(a.last() != Some(&0)); + debug_assert!(b.last() != Some(&0)); + + let (a_len, b_len) = (a.len(), b.len()); + if a_len < b_len { + return Less; + } + if a_len > b_len { + return Greater; + } + + for (&ai, &bi) in a.iter().rev().zip(b.iter().rev()) { + if ai < bi { + return Less; + } + if ai > bi { + return Greater; + } + } + return Equal; +} + +#[cfg(test)] +mod algorithm_tests { + use big_digit::BigDigit; + use traits::Num; + use Sign::Plus; + use {BigInt, BigUint}; + + #[test] + fn test_sub_sign() { + use super::sub_sign; + + fn sub_sign_i(a: &[BigDigit], b: &[BigDigit]) -> BigInt { + let (sign, val) = sub_sign(a, b); + BigInt::from_biguint(sign, val) + } + + let a = BigUint::from_str_radix("265252859812191058636308480000000", 10).unwrap(); + let b = BigUint::from_str_radix("26525285981219105863630848000000", 10).unwrap(); + let a_i = BigInt::from_biguint(Plus, a.clone()); + let b_i = BigInt::from_biguint(Plus, b.clone()); + + assert_eq!(sub_sign_i(&a.data[..], &b.data[..]), &a_i - &b_i); + assert_eq!(sub_sign_i(&b.data[..], &a.data[..]), &b_i - &a_i); + } +} diff --git a/third_party/rust/num-bigint/src/bigint.rs b/third_party/rust/num-bigint/src/bigint.rs new file mode 100644 index 0000000000..93c72be6af --- /dev/null +++ b/third_party/rust/num-bigint/src/bigint.rs @@ -0,0 +1,3084 @@ +#[allow(deprecated, unused_imports)] +use std::ascii::AsciiExt; +use std::cmp::Ordering::{self, Equal, Greater, Less}; +use std::default::Default; +use std::fmt; +use std::iter::{Product, Sum}; +use std::mem; +use std::ops::{ + Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign, + Mul, MulAssign, Neg, Not, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign, +}; +use std::str::{self, FromStr}; +#[cfg(has_i128)] +use std::{i128, u128}; +use std::{i64, u64}; + +#[cfg(feature = "serde")] +use serde; + +use integer::{Integer, Roots}; +use traits::{ + CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, FromPrimitive, Num, One, Pow, Signed, + ToPrimitive, Zero, +}; + +use self::Sign::{Minus, NoSign, Plus}; + +use super::ParseBigIntError; +use big_digit::{self, BigDigit, DoubleBigDigit}; +use biguint; +use biguint::to_str_radix_reversed; +use biguint::{BigUint, IntDigits}; + +use IsizePromotion; +use UsizePromotion; + +#[cfg(feature = "quickcheck")] +use quickcheck::{Arbitrary, Gen}; + +/// A Sign is a `BigInt`'s composing element. +#[derive(PartialEq, PartialOrd, Eq, Ord, Copy, Clone, Debug, Hash)] +pub enum Sign { + Minus, + NoSign, + Plus, +} + +impl Neg for Sign { + type Output = Sign; + + /// Negate Sign value. + #[inline] + fn neg(self) -> Sign { + match self { + Minus => Plus, + NoSign => NoSign, + Plus => Minus, + } + } +} + +impl Mul<Sign> for Sign { + type Output = Sign; + + #[inline] + fn mul(self, other: Sign) -> Sign { + match (self, other) { + (NoSign, _) | (_, NoSign) => NoSign, + (Plus, Plus) | (Minus, Minus) => Plus, + (Plus, Minus) | (Minus, Plus) => Minus, + } + } +} + +#[cfg(feature = "serde")] +impl serde::Serialize for Sign { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: serde::Serializer, + { + // Note: do not change the serialization format, or it may break + // forward and backward compatibility of serialized data! + match *self { + Sign::Minus => (-1i8).serialize(serializer), + Sign::NoSign => 0i8.serialize(serializer), + Sign::Plus => 1i8.serialize(serializer), + } + } +} + +#[cfg(feature = "serde")] +impl<'de> serde::Deserialize<'de> for Sign { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: serde::Deserializer<'de>, + { + use serde::de::Error; + use serde::de::Unexpected; + + let sign: i8 = serde::Deserialize::deserialize(deserializer)?; + match sign { + -1 => Ok(Sign::Minus), + 0 => Ok(Sign::NoSign), + 1 => Ok(Sign::Plus), + _ => Err(D::Error::invalid_value( + Unexpected::Signed(sign.into()), + &"a sign of -1, 0, or 1", + )), + } + } +} + +/// A big signed integer type. +#[derive(Clone, Debug, Hash)] +pub struct BigInt { + sign: Sign, + data: BigUint, +} + +#[cfg(feature = "quickcheck")] +impl Arbitrary for BigInt { + fn arbitrary<G: Gen>(g: &mut G) -> Self { + let positive = bool::arbitrary(g); + let sign = if positive { Sign::Plus } else { Sign::Minus }; + Self::from_biguint(sign, BigUint::arbitrary(g)) + } + + #[allow(bare_trait_objects)] // `dyn` needs Rust 1.27 to parse, even when cfg-disabled + fn shrink(&self) -> Box<Iterator<Item = Self>> { + let sign = self.sign(); + let unsigned_shrink = self.data.shrink(); + Box::new(unsigned_shrink.map(move |x| BigInt::from_biguint(sign, x))) + } +} + +/// Return the magnitude of a `BigInt`. +/// +/// This is in a private module, pseudo pub(crate) +#[cfg(feature = "rand")] +pub fn magnitude(i: &BigInt) -> &BigUint { + &i.data +} + +/// Return the owned magnitude of a `BigInt`. +/// +/// This is in a private module, pseudo pub(crate) +#[cfg(feature = "rand")] +pub fn into_magnitude(i: BigInt) -> BigUint { + i.data +} + +impl PartialEq for BigInt { + #[inline] + fn eq(&self, other: &BigInt) -> bool { + self.cmp(other) == Equal + } +} + +impl Eq for BigInt {} + +impl PartialOrd for BigInt { + #[inline] + fn partial_cmp(&self, other: &BigInt) -> Option<Ordering> { + Some(self.cmp(other)) + } +} + +impl Ord for BigInt { + #[inline] + fn cmp(&self, other: &BigInt) -> Ordering { + let scmp = self.sign.cmp(&other.sign); + if scmp != Equal { + return scmp; + } + + match self.sign { + NoSign => Equal, + Plus => self.data.cmp(&other.data), + Minus => other.data.cmp(&self.data), + } + } +} + +impl Default for BigInt { + #[inline] + fn default() -> BigInt { + Zero::zero() + } +} + +impl fmt::Display for BigInt { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad_integral(!self.is_negative(), "", &self.data.to_str_radix(10)) + } +} + +impl fmt::Binary for BigInt { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad_integral(!self.is_negative(), "0b", &self.data.to_str_radix(2)) + } +} + +impl fmt::Octal for BigInt { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad_integral(!self.is_negative(), "0o", &self.data.to_str_radix(8)) + } +} + +impl fmt::LowerHex for BigInt { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad_integral(!self.is_negative(), "0x", &self.data.to_str_radix(16)) + } +} + +impl fmt::UpperHex for BigInt { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut s = self.data.to_str_radix(16); + s.make_ascii_uppercase(); + f.pad_integral(!self.is_negative(), "0x", &s) + } +} + +// Negation in two's complement. +// acc must be initialized as 1 for least-significant digit. +// +// When negating, a carry (acc == 1) means that all the digits +// considered to this point were zero. This means that if all the +// digits of a negative BigInt have been considered, carry must be +// zero as we cannot have negative zero. +// +// 01 -> ...f ff +// ff -> ...f 01 +// 01 00 -> ...f ff 00 +// 01 01 -> ...f fe ff +// 01 ff -> ...f fe 01 +// ff 00 -> ...f 01 00 +// ff 01 -> ...f 00 ff +// ff ff -> ...f 00 01 +#[inline] +fn negate_carry(a: BigDigit, acc: &mut DoubleBigDigit) -> BigDigit { + *acc += DoubleBigDigit::from(!a); + let lo = *acc as BigDigit; + *acc >>= big_digit::BITS; + lo +} + +// !-2 = !...f fe = ...0 01 = +1 +// !-1 = !...f ff = ...0 00 = 0 +// ! 0 = !...0 00 = ...f ff = -1 +// !+1 = !...0 01 = ...f fe = -2 +impl Not for BigInt { + type Output = BigInt; + + fn not(mut self) -> BigInt { + match self.sign { + NoSign | Plus => { + self.data += 1u32; + self.sign = Minus; + } + Minus => { + self.data -= 1u32; + self.sign = if self.data.is_zero() { NoSign } else { Plus }; + } + } + self + } +} + +impl<'a> Not for &'a BigInt { + type Output = BigInt; + + fn not(self) -> BigInt { + match self.sign { + NoSign | Plus => BigInt::from_biguint(Minus, &self.data + 1u32), + Minus => BigInt::from_biguint(Plus, &self.data - 1u32), + } + } +} + +// + 1 & -ff = ...0 01 & ...f 01 = ...0 01 = + 1 +// +ff & - 1 = ...0 ff & ...f ff = ...0 ff = +ff +// answer is pos, has length of a +fn bitand_pos_neg(a: &mut Vec<BigDigit>, b: &[BigDigit]) { + let mut carry_b = 1; + for (ai, &bi) in a.iter_mut().zip(b.iter()) { + let twos_b = negate_carry(bi, &mut carry_b); + *ai &= twos_b; + } + debug_assert!(b.len() > a.len() || carry_b == 0); +} + +// - 1 & +ff = ...f ff & ...0 ff = ...0 ff = +ff +// -ff & + 1 = ...f 01 & ...0 01 = ...0 01 = + 1 +// answer is pos, has length of b +fn bitand_neg_pos(a: &mut Vec<BigDigit>, b: &[BigDigit]) { + let mut carry_a = 1; + for (ai, &bi) in a.iter_mut().zip(b.iter()) { + let twos_a = negate_carry(*ai, &mut carry_a); + *ai = twos_a & bi; + } + debug_assert!(a.len() > b.len() || carry_a == 0); + if a.len() > b.len() { + a.truncate(b.len()); + } else if b.len() > a.len() { + let extra = &b[a.len()..]; + a.extend(extra.iter().cloned()); + } +} + +// - 1 & -ff = ...f ff & ...f 01 = ...f 01 = - ff +// -ff & - 1 = ...f 01 & ...f ff = ...f 01 = - ff +// -ff & -fe = ...f 01 & ...f 02 = ...f 00 = -100 +// answer is neg, has length of longest with a possible carry +fn bitand_neg_neg(a: &mut Vec<BigDigit>, b: &[BigDigit]) { + let mut carry_a = 1; + let mut carry_b = 1; + let mut carry_and = 1; + for (ai, &bi) in a.iter_mut().zip(b.iter()) { + let twos_a = negate_carry(*ai, &mut carry_a); + let twos_b = negate_carry(bi, &mut carry_b); + *ai = negate_carry(twos_a & twos_b, &mut carry_and); + } + debug_assert!(a.len() > b.len() || carry_a == 0); + debug_assert!(b.len() > a.len() || carry_b == 0); + if a.len() > b.len() { + for ai in a[b.len()..].iter_mut() { + let twos_a = negate_carry(*ai, &mut carry_a); + *ai = negate_carry(twos_a, &mut carry_and); + } + debug_assert!(carry_a == 0); + } else if b.len() > a.len() { + let extra = &b[a.len()..]; + a.extend(extra.iter().map(|&bi| { + let twos_b = negate_carry(bi, &mut carry_b); + negate_carry(twos_b, &mut carry_and) + })); + debug_assert!(carry_b == 0); + } + if carry_and != 0 { + a.push(1); + } +} + +forward_val_val_binop!(impl BitAnd for BigInt, bitand); +forward_ref_val_binop!(impl BitAnd for BigInt, bitand); + +// do not use forward_ref_ref_binop_commutative! for bitand so that we can +// clone as needed, avoiding over-allocation +impl<'a, 'b> BitAnd<&'b BigInt> for &'a BigInt { + type Output = BigInt; + + #[inline] + fn bitand(self, other: &BigInt) -> BigInt { + match (self.sign, other.sign) { + (NoSign, _) | (_, NoSign) => BigInt::from_slice(NoSign, &[]), + (Plus, Plus) => BigInt::from_biguint(Plus, &self.data & &other.data), + (Plus, Minus) => self.clone() & other, + (Minus, Plus) => other.clone() & self, + (Minus, Minus) => { + // forward to val-ref, choosing the larger to clone + if self.len() >= other.len() { + self.clone() & other + } else { + other.clone() & self + } + } + } + } +} + +impl<'a> BitAnd<&'a BigInt> for BigInt { + type Output = BigInt; + + #[inline] + fn bitand(mut self, other: &BigInt) -> BigInt { + self &= other; + self + } +} + +forward_val_assign!(impl BitAndAssign for BigInt, bitand_assign); + +impl<'a> BitAndAssign<&'a BigInt> for BigInt { + fn bitand_assign(&mut self, other: &BigInt) { + match (self.sign, other.sign) { + (NoSign, _) => {} + (_, NoSign) => self.assign_from_slice(NoSign, &[]), + (Plus, Plus) => { + self.data &= &other.data; + if self.data.is_zero() { + self.sign = NoSign; + } + } + (Plus, Minus) => { + bitand_pos_neg(self.digits_mut(), other.digits()); + self.normalize(); + } + (Minus, Plus) => { + bitand_neg_pos(self.digits_mut(), other.digits()); + self.sign = Plus; + self.normalize(); + } + (Minus, Minus) => { + bitand_neg_neg(self.digits_mut(), other.digits()); + self.normalize(); + } + } + } +} + +// + 1 | -ff = ...0 01 | ...f 01 = ...f 01 = -ff +// +ff | - 1 = ...0 ff | ...f ff = ...f ff = - 1 +// answer is neg, has length of b +fn bitor_pos_neg(a: &mut Vec<BigDigit>, b: &[BigDigit]) { + let mut carry_b = 1; + let mut carry_or = 1; + for (ai, &bi) in a.iter_mut().zip(b.iter()) { + let twos_b = negate_carry(bi, &mut carry_b); + *ai = negate_carry(*ai | twos_b, &mut carry_or); + } + debug_assert!(b.len() > a.len() || carry_b == 0); + if a.len() > b.len() { + a.truncate(b.len()); + } else if b.len() > a.len() { + let extra = &b[a.len()..]; + a.extend(extra.iter().map(|&bi| { + let twos_b = negate_carry(bi, &mut carry_b); + negate_carry(twos_b, &mut carry_or) + })); + debug_assert!(carry_b == 0); + } + // for carry_or to be non-zero, we would need twos_b == 0 + debug_assert!(carry_or == 0); +} + +// - 1 | +ff = ...f ff | ...0 ff = ...f ff = - 1 +// -ff | + 1 = ...f 01 | ...0 01 = ...f 01 = -ff +// answer is neg, has length of a +fn bitor_neg_pos(a: &mut Vec<BigDigit>, b: &[BigDigit]) { + let mut carry_a = 1; + let mut carry_or = 1; + for (ai, &bi) in a.iter_mut().zip(b.iter()) { + let twos_a = negate_carry(*ai, &mut carry_a); + *ai = negate_carry(twos_a | bi, &mut carry_or); + } + debug_assert!(a.len() > b.len() || carry_a == 0); + if a.len() > b.len() { + for ai in a[b.len()..].iter_mut() { + let twos_a = negate_carry(*ai, &mut carry_a); + *ai = negate_carry(twos_a, &mut carry_or); + } + debug_assert!(carry_a == 0); + } + // for carry_or to be non-zero, we would need twos_a == 0 + debug_assert!(carry_or == 0); +} + +// - 1 | -ff = ...f ff | ...f 01 = ...f ff = -1 +// -ff | - 1 = ...f 01 | ...f ff = ...f ff = -1 +// answer is neg, has length of shortest +fn bitor_neg_neg(a: &mut Vec<BigDigit>, b: &[BigDigit]) { + let mut carry_a = 1; + let mut carry_b = 1; + let mut carry_or = 1; + for (ai, &bi) in a.iter_mut().zip(b.iter()) { + let twos_a = negate_carry(*ai, &mut carry_a); + let twos_b = negate_carry(bi, &mut carry_b); + *ai = negate_carry(twos_a | twos_b, &mut carry_or); + } + debug_assert!(a.len() > b.len() || carry_a == 0); + debug_assert!(b.len() > a.len() || carry_b == 0); + if a.len() > b.len() { + a.truncate(b.len()); + } + // for carry_or to be non-zero, we would need twos_a == 0 or twos_b == 0 + debug_assert!(carry_or == 0); +} + +forward_val_val_binop!(impl BitOr for BigInt, bitor); +forward_ref_val_binop!(impl BitOr for BigInt, bitor); + +// do not use forward_ref_ref_binop_commutative! for bitor so that we can +// clone as needed, avoiding over-allocation +impl<'a, 'b> BitOr<&'b BigInt> for &'a BigInt { + type Output = BigInt; + + #[inline] + fn bitor(self, other: &BigInt) -> BigInt { + match (self.sign, other.sign) { + (NoSign, _) => other.clone(), + (_, NoSign) => self.clone(), + (Plus, Plus) => BigInt::from_biguint(Plus, &self.data | &other.data), + (Plus, Minus) => other.clone() | self, + (Minus, Plus) => self.clone() | other, + (Minus, Minus) => { + // forward to val-ref, choosing the smaller to clone + if self.len() <= other.len() { + self.clone() | other + } else { + other.clone() | self + } + } + } + } +} + +impl<'a> BitOr<&'a BigInt> for BigInt { + type Output = BigInt; + + #[inline] + fn bitor(mut self, other: &BigInt) -> BigInt { + self |= other; + self + } +} + +forward_val_assign!(impl BitOrAssign for BigInt, bitor_assign); + +impl<'a> BitOrAssign<&'a BigInt> for BigInt { + fn bitor_assign(&mut self, other: &BigInt) { + match (self.sign, other.sign) { + (_, NoSign) => {} + (NoSign, _) => self.assign_from_slice(other.sign, other.digits()), + (Plus, Plus) => self.data |= &other.data, + (Plus, Minus) => { + bitor_pos_neg(self.digits_mut(), other.digits()); + self.sign = Minus; + self.normalize(); + } + (Minus, Plus) => { + bitor_neg_pos(self.digits_mut(), other.digits()); + self.normalize(); + } + (Minus, Minus) => { + bitor_neg_neg(self.digits_mut(), other.digits()); + self.normalize(); + } + } + } +} + +// + 1 ^ -ff = ...0 01 ^ ...f 01 = ...f 00 = -100 +// +ff ^ - 1 = ...0 ff ^ ...f ff = ...f 00 = -100 +// answer is neg, has length of longest with a possible carry +fn bitxor_pos_neg(a: &mut Vec<BigDigit>, b: &[BigDigit]) { + let mut carry_b = 1; + let mut carry_xor = 1; + for (ai, &bi) in a.iter_mut().zip(b.iter()) { + let twos_b = negate_carry(bi, &mut carry_b); + *ai = negate_carry(*ai ^ twos_b, &mut carry_xor); + } + debug_assert!(b.len() > a.len() || carry_b == 0); + if a.len() > b.len() { + for ai in a[b.len()..].iter_mut() { + let twos_b = !0; + *ai = negate_carry(*ai ^ twos_b, &mut carry_xor); + } + } else if b.len() > a.len() { + let extra = &b[a.len()..]; + a.extend(extra.iter().map(|&bi| { + let twos_b = negate_carry(bi, &mut carry_b); + negate_carry(twos_b, &mut carry_xor) + })); + debug_assert!(carry_b == 0); + } + if carry_xor != 0 { + a.push(1); + } +} + +// - 1 ^ +ff = ...f ff ^ ...0 ff = ...f 00 = -100 +// -ff ^ + 1 = ...f 01 ^ ...0 01 = ...f 00 = -100 +// answer is neg, has length of longest with a possible carry +fn bitxor_neg_pos(a: &mut Vec<BigDigit>, b: &[BigDigit]) { + let mut carry_a = 1; + let mut carry_xor = 1; + for (ai, &bi) in a.iter_mut().zip(b.iter()) { + let twos_a = negate_carry(*ai, &mut carry_a); + *ai = negate_carry(twos_a ^ bi, &mut carry_xor); + } + debug_assert!(a.len() > b.len() || carry_a == 0); + if a.len() > b.len() { + for ai in a[b.len()..].iter_mut() { + let twos_a = negate_carry(*ai, &mut carry_a); + *ai = negate_carry(twos_a, &mut carry_xor); + } + debug_assert!(carry_a == 0); + } else if b.len() > a.len() { + let extra = &b[a.len()..]; + a.extend(extra.iter().map(|&bi| { + let twos_a = !0; + negate_carry(twos_a ^ bi, &mut carry_xor) + })); + } + if carry_xor != 0 { + a.push(1); + } +} + +// - 1 ^ -ff = ...f ff ^ ...f 01 = ...0 fe = +fe +// -ff & - 1 = ...f 01 ^ ...f ff = ...0 fe = +fe +// answer is pos, has length of longest +fn bitxor_neg_neg(a: &mut Vec<BigDigit>, b: &[BigDigit]) { + let mut carry_a = 1; + let mut carry_b = 1; + for (ai, &bi) in a.iter_mut().zip(b.iter()) { + let twos_a = negate_carry(*ai, &mut carry_a); + let twos_b = negate_carry(bi, &mut carry_b); + *ai = twos_a ^ twos_b; + } + debug_assert!(a.len() > b.len() || carry_a == 0); + debug_assert!(b.len() > a.len() || carry_b == 0); + if a.len() > b.len() { + for ai in a[b.len()..].iter_mut() { + let twos_a = negate_carry(*ai, &mut carry_a); + let twos_b = !0; + *ai = twos_a ^ twos_b; + } + debug_assert!(carry_a == 0); + } else if b.len() > a.len() { + let extra = &b[a.len()..]; + a.extend(extra.iter().map(|&bi| { + let twos_a = !0; + let twos_b = negate_carry(bi, &mut carry_b); + twos_a ^ twos_b + })); + debug_assert!(carry_b == 0); + } +} + +forward_all_binop_to_val_ref_commutative!(impl BitXor for BigInt, bitxor); + +impl<'a> BitXor<&'a BigInt> for BigInt { + type Output = BigInt; + + #[inline] + fn bitxor(mut self, other: &BigInt) -> BigInt { + self ^= other; + self + } +} + +forward_val_assign!(impl BitXorAssign for BigInt, bitxor_assign); + +impl<'a> BitXorAssign<&'a BigInt> for BigInt { + fn bitxor_assign(&mut self, other: &BigInt) { + match (self.sign, other.sign) { + (_, NoSign) => {} + (NoSign, _) => self.assign_from_slice(other.sign, other.digits()), + (Plus, Plus) => { + self.data ^= &other.data; + if self.data.is_zero() { + self.sign = NoSign; + } + } + (Plus, Minus) => { + bitxor_pos_neg(self.digits_mut(), other.digits()); + self.sign = Minus; + self.normalize(); + } + (Minus, Plus) => { + bitxor_neg_pos(self.digits_mut(), other.digits()); + self.normalize(); + } + (Minus, Minus) => { + bitxor_neg_neg(self.digits_mut(), other.digits()); + self.sign = Plus; + self.normalize(); + } + } + } +} + +impl FromStr for BigInt { + type Err = ParseBigIntError; + + #[inline] + fn from_str(s: &str) -> Result<BigInt, ParseBigIntError> { + BigInt::from_str_radix(s, 10) + } +} + +impl Num for BigInt { + type FromStrRadixErr = ParseBigIntError; + + /// Creates and initializes a BigInt. + #[inline] + fn from_str_radix(mut s: &str, radix: u32) -> Result<BigInt, ParseBigIntError> { + let sign = if s.starts_with('-') { + let tail = &s[1..]; + if !tail.starts_with('+') { + s = tail + } + Minus + } else { + Plus + }; + let bu = BigUint::from_str_radix(s, radix)?; + Ok(BigInt::from_biguint(sign, bu)) + } +} + +impl Shl<usize> for BigInt { + type Output = BigInt; + + #[inline] + fn shl(mut self, rhs: usize) -> BigInt { + self <<= rhs; + self + } +} + +impl<'a> Shl<usize> for &'a BigInt { + type Output = BigInt; + + #[inline] + fn shl(self, rhs: usize) -> BigInt { + BigInt::from_biguint(self.sign, &self.data << rhs) + } +} + +impl ShlAssign<usize> for BigInt { + #[inline] + fn shl_assign(&mut self, rhs: usize) { + self.data <<= rhs; + } +} + +// Negative values need a rounding adjustment if there are any ones in the +// bits that are getting shifted out. +fn shr_round_down(i: &BigInt, rhs: usize) -> bool { + i.is_negative() + && biguint::trailing_zeros(&i.data) + .map(|n| n < rhs) + .unwrap_or(false) +} + +impl Shr<usize> for BigInt { + type Output = BigInt; + + #[inline] + fn shr(mut self, rhs: usize) -> BigInt { + self >>= rhs; + self + } +} + +impl<'a> Shr<usize> for &'a BigInt { + type Output = BigInt; + + #[inline] + fn shr(self, rhs: usize) -> BigInt { + let round_down = shr_round_down(self, rhs); + let data = &self.data >> rhs; + BigInt::from_biguint(self.sign, if round_down { data + 1u8 } else { data }) + } +} + +impl ShrAssign<usize> for BigInt { + #[inline] + fn shr_assign(&mut self, rhs: usize) { + let round_down = shr_round_down(self, rhs); + self.data >>= rhs; + if round_down { + self.data += 1u8; + } else if self.data.is_zero() { + self.sign = NoSign; + } + } +} + +impl Zero for BigInt { + #[inline] + fn zero() -> BigInt { + BigInt::from_biguint(NoSign, Zero::zero()) + } + + #[inline] + fn set_zero(&mut self) { + self.data.set_zero(); + self.sign = NoSign; + } + + #[inline] + fn is_zero(&self) -> bool { + self.sign == NoSign + } +} + +impl One for BigInt { + #[inline] + fn one() -> BigInt { + BigInt::from_biguint(Plus, One::one()) + } + + #[inline] + fn set_one(&mut self) { + self.data.set_one(); + self.sign = Plus; + } + + #[inline] + fn is_one(&self) -> bool { + self.sign == Plus && self.data.is_one() + } +} + +impl Signed for BigInt { + #[inline] + fn abs(&self) -> BigInt { + match self.sign { + Plus | NoSign => self.clone(), + Minus => BigInt::from_biguint(Plus, self.data.clone()), + } + } + + #[inline] + fn abs_sub(&self, other: &BigInt) -> BigInt { + if *self <= *other { + Zero::zero() + } else { + self - other + } + } + + #[inline] + fn signum(&self) -> BigInt { + match self.sign { + Plus => BigInt::from_biguint(Plus, One::one()), + Minus => BigInt::from_biguint(Minus, One::one()), + NoSign => Zero::zero(), + } + } + + #[inline] + fn is_positive(&self) -> bool { + self.sign == Plus + } + + #[inline] + fn is_negative(&self) -> bool { + self.sign == Minus + } +} + +/// Help function for pow +/// +/// Computes the effect of the exponent on the sign. +#[inline] +fn powsign<T: Integer>(sign: Sign, other: &T) -> Sign { + if other.is_zero() { + Plus + } else if sign != Minus { + sign + } else if other.is_odd() { + sign + } else { + -sign + } +} + +macro_rules! pow_impl { + ($T:ty) => { + impl<'a> Pow<$T> for &'a BigInt { + type Output = BigInt; + + #[inline] + fn pow(self, rhs: $T) -> BigInt { + BigInt::from_biguint(powsign(self.sign, &rhs), (&self.data).pow(rhs)) + } + } + + impl<'a, 'b> Pow<&'b $T> for &'a BigInt { + type Output = BigInt; + + #[inline] + fn pow(self, rhs: &$T) -> BigInt { + BigInt::from_biguint(powsign(self.sign, rhs), (&self.data).pow(rhs)) + } + } + }; +} + +pow_impl!(u8); +pow_impl!(u16); +pow_impl!(u32); +pow_impl!(u64); +pow_impl!(usize); +#[cfg(has_i128)] +pow_impl!(u128); +pow_impl!(BigUint); + +// A convenience method for getting the absolute value of an i32 in a u32. +#[inline] +fn i32_abs_as_u32(a: i32) -> u32 { + if a == i32::min_value() { + a as u32 + } else { + a.abs() as u32 + } +} + +// A convenience method for getting the absolute value of an i64 in a u64. +#[inline] +fn i64_abs_as_u64(a: i64) -> u64 { + if a == i64::min_value() { + a as u64 + } else { + a.abs() as u64 + } +} + +// A convenience method for getting the absolute value of an i128 in a u128. +#[cfg(has_i128)] +#[inline] +fn i128_abs_as_u128(a: i128) -> u128 { + if a == i128::min_value() { + a as u128 + } else { + a.abs() as u128 + } +} + +// We want to forward to BigUint::add, but it's not clear how that will go until +// we compare both sign and magnitude. So we duplicate this body for every +// val/ref combination, deferring that decision to BigUint's own forwarding. +macro_rules! bigint_add { + ($a:expr, $a_owned:expr, $a_data:expr, $b:expr, $b_owned:expr, $b_data:expr) => { + match ($a.sign, $b.sign) { + (_, NoSign) => $a_owned, + (NoSign, _) => $b_owned, + // same sign => keep the sign with the sum of magnitudes + (Plus, Plus) | (Minus, Minus) => BigInt::from_biguint($a.sign, $a_data + $b_data), + // opposite signs => keep the sign of the larger with the difference of magnitudes + (Plus, Minus) | (Minus, Plus) => match $a.data.cmp(&$b.data) { + Less => BigInt::from_biguint($b.sign, $b_data - $a_data), + Greater => BigInt::from_biguint($a.sign, $a_data - $b_data), + Equal => Zero::zero(), + }, + } + }; +} + +impl<'a, 'b> Add<&'b BigInt> for &'a BigInt { + type Output = BigInt; + + #[inline] + fn add(self, other: &BigInt) -> BigInt { + bigint_add!( + self, + self.clone(), + &self.data, + other, + other.clone(), + &other.data + ) + } +} + +impl<'a> Add<BigInt> for &'a BigInt { + type Output = BigInt; + + #[inline] + fn add(self, other: BigInt) -> BigInt { + bigint_add!(self, self.clone(), &self.data, other, other, other.data) + } +} + +impl<'a> Add<&'a BigInt> for BigInt { + type Output = BigInt; + + #[inline] + fn add(self, other: &BigInt) -> BigInt { + bigint_add!(self, self, self.data, other, other.clone(), &other.data) + } +} + +impl Add<BigInt> for BigInt { + type Output = BigInt; + + #[inline] + fn add(self, other: BigInt) -> BigInt { + bigint_add!(self, self, self.data, other, other, other.data) + } +} + +impl<'a> AddAssign<&'a BigInt> for BigInt { + #[inline] + fn add_assign(&mut self, other: &BigInt) { + let n = mem::replace(self, BigInt::zero()); + *self = n + other; + } +} +forward_val_assign!(impl AddAssign for BigInt, add_assign); + +promote_all_scalars!(impl Add for BigInt, add); +promote_all_scalars_assign!(impl AddAssign for BigInt, add_assign); +forward_all_scalar_binop_to_val_val_commutative!(impl Add<u32> for BigInt, add); +forward_all_scalar_binop_to_val_val_commutative!(impl Add<u64> for BigInt, add); +#[cfg(has_i128)] +forward_all_scalar_binop_to_val_val_commutative!(impl Add<u128> for BigInt, add); + +impl Add<u32> for BigInt { + type Output = BigInt; + + #[inline] + fn add(self, other: u32) -> BigInt { + match self.sign { + NoSign => From::from(other), + Plus => BigInt::from_biguint(Plus, self.data + other), + Minus => match self.data.cmp(&From::from(other)) { + Equal => Zero::zero(), + Less => BigInt::from_biguint(Plus, other - self.data), + Greater => BigInt::from_biguint(Minus, self.data - other), + }, + } + } +} +impl AddAssign<u32> for BigInt { + #[inline] + fn add_assign(&mut self, other: u32) { + let n = mem::replace(self, BigInt::zero()); + *self = n + other; + } +} + +impl Add<u64> for BigInt { + type Output = BigInt; + + #[inline] + fn add(self, other: u64) -> BigInt { + match self.sign { + NoSign => From::from(other), + Plus => BigInt::from_biguint(Plus, self.data + other), + Minus => match self.data.cmp(&From::from(other)) { + Equal => Zero::zero(), + Less => BigInt::from_biguint(Plus, other - self.data), + Greater => BigInt::from_biguint(Minus, self.data - other), + }, + } + } +} +impl AddAssign<u64> for BigInt { + #[inline] + fn add_assign(&mut self, other: u64) { + let n = mem::replace(self, BigInt::zero()); + *self = n + other; + } +} + +#[cfg(has_i128)] +impl Add<u128> for BigInt { + type Output = BigInt; + + #[inline] + fn add(self, other: u128) -> BigInt { + match self.sign { + NoSign => From::from(other), + Plus => BigInt::from_biguint(Plus, self.data + other), + Minus => match self.data.cmp(&From::from(other)) { + Equal => Zero::zero(), + Less => BigInt::from_biguint(Plus, other - self.data), + Greater => BigInt::from_biguint(Minus, self.data - other), + }, + } + } +} +#[cfg(has_i128)] +impl AddAssign<u128> for BigInt { + #[inline] + fn add_assign(&mut self, other: u128) { + let n = mem::replace(self, BigInt::zero()); + *self = n + other; + } +} + +forward_all_scalar_binop_to_val_val_commutative!(impl Add<i32> for BigInt, add); +forward_all_scalar_binop_to_val_val_commutative!(impl Add<i64> for BigInt, add); +#[cfg(has_i128)] +forward_all_scalar_binop_to_val_val_commutative!(impl Add<i128> for BigInt, add); + +impl Add<i32> for BigInt { + type Output = BigInt; + + #[inline] + fn add(self, other: i32) -> BigInt { + if other >= 0 { + self + other as u32 + } else { + self - i32_abs_as_u32(other) + } + } +} +impl AddAssign<i32> for BigInt { + #[inline] + fn add_assign(&mut self, other: i32) { + if other >= 0 { + *self += other as u32; + } else { + *self -= i32_abs_as_u32(other); + } + } +} + +impl Add<i64> for BigInt { + type Output = BigInt; + + #[inline] + fn add(self, other: i64) -> BigInt { + if other >= 0 { + self + other as u64 + } else { + self - i64_abs_as_u64(other) + } + } +} +impl AddAssign<i64> for BigInt { + #[inline] + fn add_assign(&mut self, other: i64) { + if other >= 0 { + *self += other as u64; + } else { + *self -= i64_abs_as_u64(other); + } + } +} + +#[cfg(has_i128)] +impl Add<i128> for BigInt { + type Output = BigInt; + + #[inline] + fn add(self, other: i128) -> BigInt { + if other >= 0 { + self + other as u128 + } else { + self - i128_abs_as_u128(other) + } + } +} +#[cfg(has_i128)] +impl AddAssign<i128> for BigInt { + #[inline] + fn add_assign(&mut self, other: i128) { + if other >= 0 { + *self += other as u128; + } else { + *self -= i128_abs_as_u128(other); + } + } +} + +// We want to forward to BigUint::sub, but it's not clear how that will go until +// we compare both sign and magnitude. So we duplicate this body for every +// val/ref combination, deferring that decision to BigUint's own forwarding. +macro_rules! bigint_sub { + ($a:expr, $a_owned:expr, $a_data:expr, $b:expr, $b_owned:expr, $b_data:expr) => { + match ($a.sign, $b.sign) { + (_, NoSign) => $a_owned, + (NoSign, _) => -$b_owned, + // opposite signs => keep the sign of the left with the sum of magnitudes + (Plus, Minus) | (Minus, Plus) => BigInt::from_biguint($a.sign, $a_data + $b_data), + // same sign => keep or toggle the sign of the left with the difference of magnitudes + (Plus, Plus) | (Minus, Minus) => match $a.data.cmp(&$b.data) { + Less => BigInt::from_biguint(-$a.sign, $b_data - $a_data), + Greater => BigInt::from_biguint($a.sign, $a_data - $b_data), + Equal => Zero::zero(), + }, + } + }; +} + +impl<'a, 'b> Sub<&'b BigInt> for &'a BigInt { + type Output = BigInt; + + #[inline] + fn sub(self, other: &BigInt) -> BigInt { + bigint_sub!( + self, + self.clone(), + &self.data, + other, + other.clone(), + &other.data + ) + } +} + +impl<'a> Sub<BigInt> for &'a BigInt { + type Output = BigInt; + + #[inline] + fn sub(self, other: BigInt) -> BigInt { + bigint_sub!(self, self.clone(), &self.data, other, other, other.data) + } +} + +impl<'a> Sub<&'a BigInt> for BigInt { + type Output = BigInt; + + #[inline] + fn sub(self, other: &BigInt) -> BigInt { + bigint_sub!(self, self, self.data, other, other.clone(), &other.data) + } +} + +impl Sub<BigInt> for BigInt { + type Output = BigInt; + + #[inline] + fn sub(self, other: BigInt) -> BigInt { + bigint_sub!(self, self, self.data, other, other, other.data) + } +} + +impl<'a> SubAssign<&'a BigInt> for BigInt { + #[inline] + fn sub_assign(&mut self, other: &BigInt) { + let n = mem::replace(self, BigInt::zero()); + *self = n - other; + } +} +forward_val_assign!(impl SubAssign for BigInt, sub_assign); + +promote_all_scalars!(impl Sub for BigInt, sub); +promote_all_scalars_assign!(impl SubAssign for BigInt, sub_assign); +forward_all_scalar_binop_to_val_val!(impl Sub<u32> for BigInt, sub); +forward_all_scalar_binop_to_val_val!(impl Sub<u64> for BigInt, sub); +#[cfg(has_i128)] +forward_all_scalar_binop_to_val_val!(impl Sub<u128> for BigInt, sub); + +impl Sub<u32> for BigInt { + type Output = BigInt; + + #[inline] + fn sub(self, other: u32) -> BigInt { + match self.sign { + NoSign => BigInt::from_biguint(Minus, From::from(other)), + Minus => BigInt::from_biguint(Minus, self.data + other), + Plus => match self.data.cmp(&From::from(other)) { + Equal => Zero::zero(), + Greater => BigInt::from_biguint(Plus, self.data - other), + Less => BigInt::from_biguint(Minus, other - self.data), + }, + } + } +} +impl SubAssign<u32> for BigInt { + #[inline] + fn sub_assign(&mut self, other: u32) { + let n = mem::replace(self, BigInt::zero()); + *self = n - other; + } +} + +impl Sub<BigInt> for u32 { + type Output = BigInt; + + #[inline] + fn sub(self, other: BigInt) -> BigInt { + -(other - self) + } +} + +impl Sub<BigInt> for u64 { + type Output = BigInt; + + #[inline] + fn sub(self, other: BigInt) -> BigInt { + -(other - self) + } +} +#[cfg(has_i128)] +impl Sub<BigInt> for u128 { + type Output = BigInt; + + #[inline] + fn sub(self, other: BigInt) -> BigInt { + -(other - self) + } +} + +impl Sub<u64> for BigInt { + type Output = BigInt; + + #[inline] + fn sub(self, other: u64) -> BigInt { + match self.sign { + NoSign => BigInt::from_biguint(Minus, From::from(other)), + Minus => BigInt::from_biguint(Minus, self.data + other), + Plus => match self.data.cmp(&From::from(other)) { + Equal => Zero::zero(), + Greater => BigInt::from_biguint(Plus, self.data - other), + Less => BigInt::from_biguint(Minus, other - self.data), + }, + } + } +} +impl SubAssign<u64> for BigInt { + #[inline] + fn sub_assign(&mut self, other: u64) { + let n = mem::replace(self, BigInt::zero()); + *self = n - other; + } +} + +#[cfg(has_i128)] +impl Sub<u128> for BigInt { + type Output = BigInt; + + #[inline] + fn sub(self, other: u128) -> BigInt { + match self.sign { + NoSign => BigInt::from_biguint(Minus, From::from(other)), + Minus => BigInt::from_biguint(Minus, self.data + other), + Plus => match self.data.cmp(&From::from(other)) { + Equal => Zero::zero(), + Greater => BigInt::from_biguint(Plus, self.data - other), + Less => BigInt::from_biguint(Minus, other - self.data), + }, + } + } +} +#[cfg(has_i128)] +impl SubAssign<u128> for BigInt { + #[inline] + fn sub_assign(&mut self, other: u128) { + let n = mem::replace(self, BigInt::zero()); + *self = n - other; + } +} + +forward_all_scalar_binop_to_val_val!(impl Sub<i32> for BigInt, sub); +forward_all_scalar_binop_to_val_val!(impl Sub<i64> for BigInt, sub); +#[cfg(has_i128)] +forward_all_scalar_binop_to_val_val!(impl Sub<i128> for BigInt, sub); + +impl Sub<i32> for BigInt { + type Output = BigInt; + + #[inline] + fn sub(self, other: i32) -> BigInt { + if other >= 0 { + self - other as u32 + } else { + self + i32_abs_as_u32(other) + } + } +} +impl SubAssign<i32> for BigInt { + #[inline] + fn sub_assign(&mut self, other: i32) { + if other >= 0 { + *self -= other as u32; + } else { + *self += i32_abs_as_u32(other); + } + } +} + +impl Sub<BigInt> for i32 { + type Output = BigInt; + + #[inline] + fn sub(self, other: BigInt) -> BigInt { + if self >= 0 { + self as u32 - other + } else { + -other - i32_abs_as_u32(self) + } + } +} + +impl Sub<i64> for BigInt { + type Output = BigInt; + + #[inline] + fn sub(self, other: i64) -> BigInt { + if other >= 0 { + self - other as u64 + } else { + self + i64_abs_as_u64(other) + } + } +} +impl SubAssign<i64> for BigInt { + #[inline] + fn sub_assign(&mut self, other: i64) { + if other >= 0 { + *self -= other as u64; + } else { + *self += i64_abs_as_u64(other); + } + } +} + +impl Sub<BigInt> for i64 { + type Output = BigInt; + + #[inline] + fn sub(self, other: BigInt) -> BigInt { + if self >= 0 { + self as u64 - other + } else { + -other - i64_abs_as_u64(self) + } + } +} + +#[cfg(has_i128)] +impl Sub<i128> for BigInt { + type Output = BigInt; + + #[inline] + fn sub(self, other: i128) -> BigInt { + if other >= 0 { + self - other as u128 + } else { + self + i128_abs_as_u128(other) + } + } +} +#[cfg(has_i128)] +impl SubAssign<i128> for BigInt { + #[inline] + fn sub_assign(&mut self, other: i128) { + if other >= 0 { + *self -= other as u128; + } else { + *self += i128_abs_as_u128(other); + } + } +} +#[cfg(has_i128)] +impl Sub<BigInt> for i128 { + type Output = BigInt; + + #[inline] + fn sub(self, other: BigInt) -> BigInt { + if self >= 0 { + self as u128 - other + } else { + -other - i128_abs_as_u128(self) + } + } +} + +forward_all_binop_to_ref_ref!(impl Mul for BigInt, mul); + +impl<'a, 'b> Mul<&'b BigInt> for &'a BigInt { + type Output = BigInt; + + #[inline] + fn mul(self, other: &BigInt) -> BigInt { + BigInt::from_biguint(self.sign * other.sign, &self.data * &other.data) + } +} + +impl<'a> MulAssign<&'a BigInt> for BigInt { + #[inline] + fn mul_assign(&mut self, other: &BigInt) { + *self = &*self * other; + } +} +forward_val_assign!(impl MulAssign for BigInt, mul_assign); + +promote_all_scalars!(impl Mul for BigInt, mul); +promote_all_scalars_assign!(impl MulAssign for BigInt, mul_assign); +forward_all_scalar_binop_to_val_val_commutative!(impl Mul<u32> for BigInt, mul); +forward_all_scalar_binop_to_val_val_commutative!(impl Mul<u64> for BigInt, mul); +#[cfg(has_i128)] +forward_all_scalar_binop_to_val_val_commutative!(impl Mul<u128> for BigInt, mul); + +impl Mul<u32> for BigInt { + type Output = BigInt; + + #[inline] + fn mul(self, other: u32) -> BigInt { + BigInt::from_biguint(self.sign, self.data * other) + } +} + +impl MulAssign<u32> for BigInt { + #[inline] + fn mul_assign(&mut self, other: u32) { + self.data *= other; + if self.data.is_zero() { + self.sign = NoSign; + } + } +} + +impl Mul<u64> for BigInt { + type Output = BigInt; + + #[inline] + fn mul(self, other: u64) -> BigInt { + BigInt::from_biguint(self.sign, self.data * other) + } +} + +impl MulAssign<u64> for BigInt { + #[inline] + fn mul_assign(&mut self, other: u64) { + self.data *= other; + if self.data.is_zero() { + self.sign = NoSign; + } + } +} +#[cfg(has_i128)] +impl Mul<u128> for BigInt { + type Output = BigInt; + + #[inline] + fn mul(self, other: u128) -> BigInt { + BigInt::from_biguint(self.sign, self.data * other) + } +} +#[cfg(has_i128)] +impl MulAssign<u128> for BigInt { + #[inline] + fn mul_assign(&mut self, other: u128) { + self.data *= other; + if self.data.is_zero() { + self.sign = NoSign; + } + } +} + +forward_all_scalar_binop_to_val_val_commutative!(impl Mul<i32> for BigInt, mul); +forward_all_scalar_binop_to_val_val_commutative!(impl Mul<i64> for BigInt, mul); +#[cfg(has_i128)] +forward_all_scalar_binop_to_val_val_commutative!(impl Mul<i128> for BigInt, mul); + +impl Mul<i32> for BigInt { + type Output = BigInt; + + #[inline] + fn mul(self, other: i32) -> BigInt { + if other >= 0 { + self * other as u32 + } else { + -(self * i32_abs_as_u32(other)) + } + } +} + +impl MulAssign<i32> for BigInt { + #[inline] + fn mul_assign(&mut self, other: i32) { + if other >= 0 { + *self *= other as u32; + } else { + self.sign = -self.sign; + *self *= i32_abs_as_u32(other); + } + } +} + +impl Mul<i64> for BigInt { + type Output = BigInt; + + #[inline] + fn mul(self, other: i64) -> BigInt { + if other >= 0 { + self * other as u64 + } else { + -(self * i64_abs_as_u64(other)) + } + } +} + +impl MulAssign<i64> for BigInt { + #[inline] + fn mul_assign(&mut self, other: i64) { + if other >= 0 { + *self *= other as u64; + } else { + self.sign = -self.sign; + *self *= i64_abs_as_u64(other); + } + } +} +#[cfg(has_i128)] +impl Mul<i128> for BigInt { + type Output = BigInt; + + #[inline] + fn mul(self, other: i128) -> BigInt { + if other >= 0 { + self * other as u128 + } else { + -(self * i128_abs_as_u128(other)) + } + } +} +#[cfg(has_i128)] +impl MulAssign<i128> for BigInt { + #[inline] + fn mul_assign(&mut self, other: i128) { + if other >= 0 { + *self *= other as u128; + } else { + self.sign = -self.sign; + *self *= i128_abs_as_u128(other); + } + } +} + +forward_all_binop_to_ref_ref!(impl Div for BigInt, div); + +impl<'a, 'b> Div<&'b BigInt> for &'a BigInt { + type Output = BigInt; + + #[inline] + fn div(self, other: &BigInt) -> BigInt { + let (q, _) = self.div_rem(other); + q + } +} + +impl<'a> DivAssign<&'a BigInt> for BigInt { + #[inline] + fn div_assign(&mut self, other: &BigInt) { + *self = &*self / other; + } +} +forward_val_assign!(impl DivAssign for BigInt, div_assign); + +promote_all_scalars!(impl Div for BigInt, div); +promote_all_scalars_assign!(impl DivAssign for BigInt, div_assign); +forward_all_scalar_binop_to_val_val!(impl Div<u32> for BigInt, div); +forward_all_scalar_binop_to_val_val!(impl Div<u64> for BigInt, div); +#[cfg(has_i128)] +forward_all_scalar_binop_to_val_val!(impl Div<u128> for BigInt, div); + +impl Div<u32> for BigInt { + type Output = BigInt; + + #[inline] + fn div(self, other: u32) -> BigInt { + BigInt::from_biguint(self.sign, self.data / other) + } +} + +impl DivAssign<u32> for BigInt { + #[inline] + fn div_assign(&mut self, other: u32) { + self.data /= other; + if self.data.is_zero() { + self.sign = NoSign; + } + } +} + +impl Div<BigInt> for u32 { + type Output = BigInt; + + #[inline] + fn div(self, other: BigInt) -> BigInt { + BigInt::from_biguint(other.sign, self / other.data) + } +} + +impl Div<u64> for BigInt { + type Output = BigInt; + + #[inline] + fn div(self, other: u64) -> BigInt { + BigInt::from_biguint(self.sign, self.data / other) + } +} + +impl DivAssign<u64> for BigInt { + #[inline] + fn div_assign(&mut self, other: u64) { + self.data /= other; + if self.data.is_zero() { + self.sign = NoSign; + } + } +} + +impl Div<BigInt> for u64 { + type Output = BigInt; + + #[inline] + fn div(self, other: BigInt) -> BigInt { + BigInt::from_biguint(other.sign, self / other.data) + } +} + +#[cfg(has_i128)] +impl Div<u128> for BigInt { + type Output = BigInt; + + #[inline] + fn div(self, other: u128) -> BigInt { + BigInt::from_biguint(self.sign, self.data / other) + } +} + +#[cfg(has_i128)] +impl DivAssign<u128> for BigInt { + #[inline] + fn div_assign(&mut self, other: u128) { + self.data /= other; + if self.data.is_zero() { + self.sign = NoSign; + } + } +} + +#[cfg(has_i128)] +impl Div<BigInt> for u128 { + type Output = BigInt; + + #[inline] + fn div(self, other: BigInt) -> BigInt { + BigInt::from_biguint(other.sign, self / other.data) + } +} + +forward_all_scalar_binop_to_val_val!(impl Div<i32> for BigInt, div); +forward_all_scalar_binop_to_val_val!(impl Div<i64> for BigInt, div); +#[cfg(has_i128)] +forward_all_scalar_binop_to_val_val!(impl Div<i128> for BigInt, div); + +impl Div<i32> for BigInt { + type Output = BigInt; + + #[inline] + fn div(self, other: i32) -> BigInt { + if other >= 0 { + self / other as u32 + } else { + -(self / i32_abs_as_u32(other)) + } + } +} + +impl DivAssign<i32> for BigInt { + #[inline] + fn div_assign(&mut self, other: i32) { + if other >= 0 { + *self /= other as u32; + } else { + self.sign = -self.sign; + *self /= i32_abs_as_u32(other); + } + } +} + +impl Div<BigInt> for i32 { + type Output = BigInt; + + #[inline] + fn div(self, other: BigInt) -> BigInt { + if self >= 0 { + self as u32 / other + } else { + -(i32_abs_as_u32(self) / other) + } + } +} + +impl Div<i64> for BigInt { + type Output = BigInt; + + #[inline] + fn div(self, other: i64) -> BigInt { + if other >= 0 { + self / other as u64 + } else { + -(self / i64_abs_as_u64(other)) + } + } +} + +impl DivAssign<i64> for BigInt { + #[inline] + fn div_assign(&mut self, other: i64) { + if other >= 0 { + *self /= other as u64; + } else { + self.sign = -self.sign; + *self /= i64_abs_as_u64(other); + } + } +} + +impl Div<BigInt> for i64 { + type Output = BigInt; + + #[inline] + fn div(self, other: BigInt) -> BigInt { + if self >= 0 { + self as u64 / other + } else { + -(i64_abs_as_u64(self) / other) + } + } +} + +#[cfg(has_i128)] +impl Div<i128> for BigInt { + type Output = BigInt; + + #[inline] + fn div(self, other: i128) -> BigInt { + if other >= 0 { + self / other as u128 + } else { + -(self / i128_abs_as_u128(other)) + } + } +} + +#[cfg(has_i128)] +impl DivAssign<i128> for BigInt { + #[inline] + fn div_assign(&mut self, other: i128) { + if other >= 0 { + *self /= other as u128; + } else { + self.sign = -self.sign; + *self /= i128_abs_as_u128(other); + } + } +} + +#[cfg(has_i128)] +impl Div<BigInt> for i128 { + type Output = BigInt; + + #[inline] + fn div(self, other: BigInt) -> BigInt { + if self >= 0 { + self as u128 / other + } else { + -(i128_abs_as_u128(self) / other) + } + } +} + +forward_all_binop_to_ref_ref!(impl Rem for BigInt, rem); + +impl<'a, 'b> Rem<&'b BigInt> for &'a BigInt { + type Output = BigInt; + + #[inline] + fn rem(self, other: &BigInt) -> BigInt { + let (_, r) = self.div_rem(other); + r + } +} + +impl<'a> RemAssign<&'a BigInt> for BigInt { + #[inline] + fn rem_assign(&mut self, other: &BigInt) { + *self = &*self % other; + } +} +forward_val_assign!(impl RemAssign for BigInt, rem_assign); + +promote_all_scalars!(impl Rem for BigInt, rem); +promote_all_scalars_assign!(impl RemAssign for BigInt, rem_assign); +forward_all_scalar_binop_to_val_val!(impl Rem<u32> for BigInt, rem); +forward_all_scalar_binop_to_val_val!(impl Rem<u64> for BigInt, rem); +#[cfg(has_i128)] +forward_all_scalar_binop_to_val_val!(impl Rem<u128> for BigInt, rem); + +impl Rem<u32> for BigInt { + type Output = BigInt; + + #[inline] + fn rem(self, other: u32) -> BigInt { + BigInt::from_biguint(self.sign, self.data % other) + } +} + +impl RemAssign<u32> for BigInt { + #[inline] + fn rem_assign(&mut self, other: u32) { + self.data %= other; + if self.data.is_zero() { + self.sign = NoSign; + } + } +} + +impl Rem<BigInt> for u32 { + type Output = BigInt; + + #[inline] + fn rem(self, other: BigInt) -> BigInt { + BigInt::from_biguint(Plus, self % other.data) + } +} + +impl Rem<u64> for BigInt { + type Output = BigInt; + + #[inline] + fn rem(self, other: u64) -> BigInt { + BigInt::from_biguint(self.sign, self.data % other) + } +} + +impl RemAssign<u64> for BigInt { + #[inline] + fn rem_assign(&mut self, other: u64) { + self.data %= other; + if self.data.is_zero() { + self.sign = NoSign; + } + } +} + +impl Rem<BigInt> for u64 { + type Output = BigInt; + + #[inline] + fn rem(self, other: BigInt) -> BigInt { + BigInt::from_biguint(Plus, self % other.data) + } +} + +#[cfg(has_i128)] +impl Rem<u128> for BigInt { + type Output = BigInt; + + #[inline] + fn rem(self, other: u128) -> BigInt { + BigInt::from_biguint(self.sign, self.data % other) + } +} + +#[cfg(has_i128)] +impl RemAssign<u128> for BigInt { + #[inline] + fn rem_assign(&mut self, other: u128) { + self.data %= other; + if self.data.is_zero() { + self.sign = NoSign; + } + } +} + +#[cfg(has_i128)] +impl Rem<BigInt> for u128 { + type Output = BigInt; + + #[inline] + fn rem(self, other: BigInt) -> BigInt { + BigInt::from_biguint(Plus, self % other.data) + } +} + +forward_all_scalar_binop_to_val_val!(impl Rem<i32> for BigInt, rem); +forward_all_scalar_binop_to_val_val!(impl Rem<i64> for BigInt, rem); +#[cfg(has_i128)] +forward_all_scalar_binop_to_val_val!(impl Rem<i128> for BigInt, rem); + +impl Rem<i32> for BigInt { + type Output = BigInt; + + #[inline] + fn rem(self, other: i32) -> BigInt { + if other >= 0 { + self % other as u32 + } else { + self % i32_abs_as_u32(other) + } + } +} + +impl RemAssign<i32> for BigInt { + #[inline] + fn rem_assign(&mut self, other: i32) { + if other >= 0 { + *self %= other as u32; + } else { + *self %= i32_abs_as_u32(other); + } + } +} + +impl Rem<BigInt> for i32 { + type Output = BigInt; + + #[inline] + fn rem(self, other: BigInt) -> BigInt { + if self >= 0 { + self as u32 % other + } else { + -(i32_abs_as_u32(self) % other) + } + } +} + +impl Rem<i64> for BigInt { + type Output = BigInt; + + #[inline] + fn rem(self, other: i64) -> BigInt { + if other >= 0 { + self % other as u64 + } else { + self % i64_abs_as_u64(other) + } + } +} + +impl RemAssign<i64> for BigInt { + #[inline] + fn rem_assign(&mut self, other: i64) { + if other >= 0 { + *self %= other as u64; + } else { + *self %= i64_abs_as_u64(other); + } + } +} + +impl Rem<BigInt> for i64 { + type Output = BigInt; + + #[inline] + fn rem(self, other: BigInt) -> BigInt { + if self >= 0 { + self as u64 % other + } else { + -(i64_abs_as_u64(self) % other) + } + } +} + +#[cfg(has_i128)] +impl Rem<i128> for BigInt { + type Output = BigInt; + + #[inline] + fn rem(self, other: i128) -> BigInt { + if other >= 0 { + self % other as u128 + } else { + self % i128_abs_as_u128(other) + } + } +} +#[cfg(has_i128)] +impl RemAssign<i128> for BigInt { + #[inline] + fn rem_assign(&mut self, other: i128) { + if other >= 0 { + *self %= other as u128; + } else { + *self %= i128_abs_as_u128(other); + } + } +} +#[cfg(has_i128)] +impl Rem<BigInt> for i128 { + type Output = BigInt; + + #[inline] + fn rem(self, other: BigInt) -> BigInt { + if self >= 0 { + self as u128 % other + } else { + -(i128_abs_as_u128(self) % other) + } + } +} + +impl Neg for BigInt { + type Output = BigInt; + + #[inline] + fn neg(mut self) -> BigInt { + self.sign = -self.sign; + self + } +} + +impl<'a> Neg for &'a BigInt { + type Output = BigInt; + + #[inline] + fn neg(self) -> BigInt { + -self.clone() + } +} + +impl CheckedAdd for BigInt { + #[inline] + fn checked_add(&self, v: &BigInt) -> Option<BigInt> { + return Some(self.add(v)); + } +} + +impl CheckedSub for BigInt { + #[inline] + fn checked_sub(&self, v: &BigInt) -> Option<BigInt> { + return Some(self.sub(v)); + } +} + +impl CheckedMul for BigInt { + #[inline] + fn checked_mul(&self, v: &BigInt) -> Option<BigInt> { + return Some(self.mul(v)); + } +} + +impl CheckedDiv for BigInt { + #[inline] + fn checked_div(&self, v: &BigInt) -> Option<BigInt> { + if v.is_zero() { + return None; + } + return Some(self.div(v)); + } +} + +impl Integer for BigInt { + #[inline] + fn div_rem(&self, other: &BigInt) -> (BigInt, BigInt) { + // r.sign == self.sign + let (d_ui, r_ui) = self.data.div_mod_floor(&other.data); + let d = BigInt::from_biguint(self.sign, d_ui); + let r = BigInt::from_biguint(self.sign, r_ui); + if other.is_negative() { + (-d, r) + } else { + (d, r) + } + } + + #[inline] + fn div_floor(&self, other: &BigInt) -> BigInt { + let (d, _) = self.div_mod_floor(other); + d + } + + #[inline] + fn mod_floor(&self, other: &BigInt) -> BigInt { + let (_, m) = self.div_mod_floor(other); + m + } + + fn div_mod_floor(&self, other: &BigInt) -> (BigInt, BigInt) { + // m.sign == other.sign + let (d_ui, m_ui) = self.data.div_rem(&other.data); + let d = BigInt::from_biguint(Plus, d_ui); + let m = BigInt::from_biguint(Plus, m_ui); + let one: BigInt = One::one(); + match (self.sign, other.sign) { + (_, NoSign) => panic!(), + (Plus, Plus) | (NoSign, Plus) => (d, m), + (Plus, Minus) | (NoSign, Minus) => { + if m.is_zero() { + (-d, Zero::zero()) + } else { + (-d - one, m + other) + } + } + (Minus, Plus) => { + if m.is_zero() { + (-d, Zero::zero()) + } else { + (-d - one, other - m) + } + } + (Minus, Minus) => (d, -m), + } + } + + /// Calculates the Greatest Common Divisor (GCD) of the number and `other`. + /// + /// The result is always positive. + #[inline] + fn gcd(&self, other: &BigInt) -> BigInt { + BigInt::from_biguint(Plus, self.data.gcd(&other.data)) + } + + /// Calculates the Lowest Common Multiple (LCM) of the number and `other`. + #[inline] + fn lcm(&self, other: &BigInt) -> BigInt { + BigInt::from_biguint(Plus, self.data.lcm(&other.data)) + } + + /// Deprecated, use `is_multiple_of` instead. + #[inline] + fn divides(&self, other: &BigInt) -> bool { + return self.is_multiple_of(other); + } + + /// Returns `true` if the number is a multiple of `other`. + #[inline] + fn is_multiple_of(&self, other: &BigInt) -> bool { + self.data.is_multiple_of(&other.data) + } + + /// Returns `true` if the number is divisible by `2`. + #[inline] + fn is_even(&self) -> bool { + self.data.is_even() + } + + /// Returns `true` if the number is not divisible by `2`. + #[inline] + fn is_odd(&self) -> bool { + self.data.is_odd() + } +} + +impl Roots for BigInt { + fn nth_root(&self, n: u32) -> Self { + assert!( + !(self.is_negative() && n.is_even()), + "root of degree {} is imaginary", + n + ); + + BigInt::from_biguint(self.sign, self.data.nth_root(n)) + } + + fn sqrt(&self) -> Self { + assert!(!self.is_negative(), "square root is imaginary"); + + BigInt::from_biguint(self.sign, self.data.sqrt()) + } + + fn cbrt(&self) -> Self { + BigInt::from_biguint(self.sign, self.data.cbrt()) + } +} + +impl ToPrimitive for BigInt { + #[inline] + fn to_i64(&self) -> Option<i64> { + match self.sign { + Plus => self.data.to_i64(), + NoSign => Some(0), + Minus => self.data.to_u64().and_then(|n| { + let m: u64 = 1 << 63; + if n < m { + Some(-(n as i64)) + } else if n == m { + Some(i64::MIN) + } else { + None + } + }), + } + } + + #[inline] + #[cfg(has_i128)] + fn to_i128(&self) -> Option<i128> { + match self.sign { + Plus => self.data.to_i128(), + NoSign => Some(0), + Minus => self.data.to_u128().and_then(|n| { + let m: u128 = 1 << 127; + if n < m { + Some(-(n as i128)) + } else if n == m { + Some(i128::MIN) + } else { + None + } + }), + } + } + + #[inline] + fn to_u64(&self) -> Option<u64> { + match self.sign { + Plus => self.data.to_u64(), + NoSign => Some(0), + Minus => None, + } + } + + #[inline] + #[cfg(has_i128)] + fn to_u128(&self) -> Option<u128> { + match self.sign { + Plus => self.data.to_u128(), + NoSign => Some(0), + Minus => None, + } + } + + #[inline] + fn to_f32(&self) -> Option<f32> { + self.data + .to_f32() + .map(|n| if self.sign == Minus { -n } else { n }) + } + + #[inline] + fn to_f64(&self) -> Option<f64> { + self.data + .to_f64() + .map(|n| if self.sign == Minus { -n } else { n }) + } +} + +impl FromPrimitive for BigInt { + #[inline] + fn from_i64(n: i64) -> Option<BigInt> { + Some(BigInt::from(n)) + } + + #[inline] + #[cfg(has_i128)] + fn from_i128(n: i128) -> Option<BigInt> { + Some(BigInt::from(n)) + } + + #[inline] + fn from_u64(n: u64) -> Option<BigInt> { + Some(BigInt::from(n)) + } + + #[inline] + #[cfg(has_i128)] + fn from_u128(n: u128) -> Option<BigInt> { + Some(BigInt::from(n)) + } + + #[inline] + fn from_f64(n: f64) -> Option<BigInt> { + if n >= 0.0 { + BigUint::from_f64(n).map(|x| BigInt::from_biguint(Plus, x)) + } else { + BigUint::from_f64(-n).map(|x| BigInt::from_biguint(Minus, x)) + } + } +} + +impl From<i64> for BigInt { + #[inline] + fn from(n: i64) -> Self { + if n >= 0 { + BigInt::from(n as u64) + } else { + let u = u64::MAX - (n as u64) + 1; + BigInt { + sign: Minus, + data: BigUint::from(u), + } + } + } +} + +#[cfg(has_i128)] +impl From<i128> for BigInt { + #[inline] + fn from(n: i128) -> Self { + if n >= 0 { + BigInt::from(n as u128) + } else { + let u = u128::MAX - (n as u128) + 1; + BigInt { + sign: Minus, + data: BigUint::from(u), + } + } + } +} + +macro_rules! impl_bigint_from_int { + ($T:ty) => { + impl From<$T> for BigInt { + #[inline] + fn from(n: $T) -> Self { + BigInt::from(n as i64) + } + } + }; +} + +impl_bigint_from_int!(i8); +impl_bigint_from_int!(i16); +impl_bigint_from_int!(i32); +impl_bigint_from_int!(isize); + +impl From<u64> for BigInt { + #[inline] + fn from(n: u64) -> Self { + if n > 0 { + BigInt { + sign: Plus, + data: BigUint::from(n), + } + } else { + BigInt::zero() + } + } +} + +#[cfg(has_i128)] +impl From<u128> for BigInt { + #[inline] + fn from(n: u128) -> Self { + if n > 0 { + BigInt { + sign: Plus, + data: BigUint::from(n), + } + } else { + BigInt::zero() + } + } +} + +macro_rules! impl_bigint_from_uint { + ($T:ty) => { + impl From<$T> for BigInt { + #[inline] + fn from(n: $T) -> Self { + BigInt::from(n as u64) + } + } + }; +} + +impl_bigint_from_uint!(u8); +impl_bigint_from_uint!(u16); +impl_bigint_from_uint!(u32); +impl_bigint_from_uint!(usize); + +impl From<BigUint> for BigInt { + #[inline] + fn from(n: BigUint) -> Self { + if n.is_zero() { + BigInt::zero() + } else { + BigInt { + sign: Plus, + data: n, + } + } + } +} + +impl IntDigits for BigInt { + #[inline] + fn digits(&self) -> &[BigDigit] { + self.data.digits() + } + #[inline] + fn digits_mut(&mut self) -> &mut Vec<BigDigit> { + self.data.digits_mut() + } + #[inline] + fn normalize(&mut self) { + self.data.normalize(); + if self.data.is_zero() { + self.sign = NoSign; + } + } + #[inline] + fn capacity(&self) -> usize { + self.data.capacity() + } + #[inline] + fn len(&self) -> usize { + self.data.len() + } +} + +#[cfg(feature = "serde")] +impl serde::Serialize for BigInt { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: serde::Serializer, + { + // Note: do not change the serialization format, or it may break + // forward and backward compatibility of serialized data! + (self.sign, &self.data).serialize(serializer) + } +} + +#[cfg(feature = "serde")] +impl<'de> serde::Deserialize<'de> for BigInt { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: serde::Deserializer<'de>, + { + let (sign, data) = serde::Deserialize::deserialize(deserializer)?; + Ok(BigInt::from_biguint(sign, data)) + } +} + +/// A generic trait for converting a value to a `BigInt`. This may return +/// `None` when converting from `f32` or `f64`, and will always succeed +/// when converting from any integer or unsigned primitive, or `BigUint`. +pub trait ToBigInt { + /// Converts the value of `self` to a `BigInt`. + fn to_bigint(&self) -> Option<BigInt>; +} + +impl ToBigInt for BigInt { + #[inline] + fn to_bigint(&self) -> Option<BigInt> { + Some(self.clone()) + } +} + +impl ToBigInt for BigUint { + #[inline] + fn to_bigint(&self) -> Option<BigInt> { + if self.is_zero() { + Some(Zero::zero()) + } else { + Some(BigInt { + sign: Plus, + data: self.clone(), + }) + } + } +} + +impl biguint::ToBigUint for BigInt { + #[inline] + fn to_biguint(&self) -> Option<BigUint> { + match self.sign() { + Plus => Some(self.data.clone()), + NoSign => Some(Zero::zero()), + Minus => None, + } + } +} + +macro_rules! impl_to_bigint { + ($T:ty, $from_ty:path) => { + impl ToBigInt for $T { + #[inline] + fn to_bigint(&self) -> Option<BigInt> { + $from_ty(*self) + } + } + }; +} + +impl_to_bigint!(isize, FromPrimitive::from_isize); +impl_to_bigint!(i8, FromPrimitive::from_i8); +impl_to_bigint!(i16, FromPrimitive::from_i16); +impl_to_bigint!(i32, FromPrimitive::from_i32); +impl_to_bigint!(i64, FromPrimitive::from_i64); +#[cfg(has_i128)] +impl_to_bigint!(i128, FromPrimitive::from_i128); + +impl_to_bigint!(usize, FromPrimitive::from_usize); +impl_to_bigint!(u8, FromPrimitive::from_u8); +impl_to_bigint!(u16, FromPrimitive::from_u16); +impl_to_bigint!(u32, FromPrimitive::from_u32); +impl_to_bigint!(u64, FromPrimitive::from_u64); +#[cfg(has_i128)] +impl_to_bigint!(u128, FromPrimitive::from_u128); + +impl_to_bigint!(f32, FromPrimitive::from_f32); +impl_to_bigint!(f64, FromPrimitive::from_f64); + +impl BigInt { + /// Creates and initializes a BigInt. + /// + /// The digits are in little-endian base 2<sup>32</sup>. + #[inline] + pub fn new(sign: Sign, digits: Vec<u32>) -> BigInt { + BigInt::from_biguint(sign, BigUint::new(digits)) + } + + /// Creates and initializes a `BigInt`. + /// + /// The digits are in little-endian base 2<sup>32</sup>. + #[inline] + pub fn from_biguint(mut sign: Sign, mut data: BigUint) -> BigInt { + if sign == NoSign { + data.assign_from_slice(&[]); + } else if data.is_zero() { + sign = NoSign; + } + + BigInt { + sign: sign, + data: data, + } + } + + /// Creates and initializes a `BigInt`. + #[inline] + pub fn from_slice(sign: Sign, slice: &[u32]) -> BigInt { + BigInt::from_biguint(sign, BigUint::from_slice(slice)) + } + + /// Reinitializes a `BigInt`. + #[inline] + pub fn assign_from_slice(&mut self, sign: Sign, slice: &[u32]) { + if sign == NoSign { + self.data.assign_from_slice(&[]); + self.sign = NoSign; + } else { + self.data.assign_from_slice(slice); + self.sign = match self.data.is_zero() { + true => NoSign, + false => sign, + } + } + } + + /// Creates and initializes a `BigInt`. + /// + /// The bytes are in big-endian byte order. + /// + /// # Examples + /// + /// ``` + /// use num_bigint::{BigInt, Sign}; + /// + /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"A"), + /// BigInt::parse_bytes(b"65", 10).unwrap()); + /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"AA"), + /// BigInt::parse_bytes(b"16705", 10).unwrap()); + /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"AB"), + /// BigInt::parse_bytes(b"16706", 10).unwrap()); + /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"Hello world!"), + /// BigInt::parse_bytes(b"22405534230753963835153736737", 10).unwrap()); + /// ``` + #[inline] + pub fn from_bytes_be(sign: Sign, bytes: &[u8]) -> BigInt { + BigInt::from_biguint(sign, BigUint::from_bytes_be(bytes)) + } + + /// Creates and initializes a `BigInt`. + /// + /// The bytes are in little-endian byte order. + #[inline] + pub fn from_bytes_le(sign: Sign, bytes: &[u8]) -> BigInt { + BigInt::from_biguint(sign, BigUint::from_bytes_le(bytes)) + } + + /// Creates and initializes a `BigInt` from an array of bytes in + /// two's complement binary representation. + /// + /// The digits are in big-endian base 2<sup>8</sup>. + #[inline] + pub fn from_signed_bytes_be(digits: &[u8]) -> BigInt { + let sign = match digits.first() { + Some(v) if *v > 0x7f => Sign::Minus, + Some(_) => Sign::Plus, + None => return BigInt::zero(), + }; + + if sign == Sign::Minus { + // two's-complement the content to retrieve the magnitude + let mut digits = Vec::from(digits); + twos_complement_be(&mut digits); + BigInt::from_biguint(sign, BigUint::from_bytes_be(&*digits)) + } else { + BigInt::from_biguint(sign, BigUint::from_bytes_be(digits)) + } + } + + /// Creates and initializes a `BigInt` from an array of bytes in two's complement. + /// + /// The digits are in little-endian base 2<sup>8</sup>. + #[inline] + pub fn from_signed_bytes_le(digits: &[u8]) -> BigInt { + let sign = match digits.last() { + Some(v) if *v > 0x7f => Sign::Minus, + Some(_) => Sign::Plus, + None => return BigInt::zero(), + }; + + if sign == Sign::Minus { + // two's-complement the content to retrieve the magnitude + let mut digits = Vec::from(digits); + twos_complement_le(&mut digits); + BigInt::from_biguint(sign, BigUint::from_bytes_le(&*digits)) + } else { + BigInt::from_biguint(sign, BigUint::from_bytes_le(digits)) + } + } + + /// Creates and initializes a `BigInt`. + /// + /// # Examples + /// + /// ``` + /// use num_bigint::{BigInt, ToBigInt}; + /// + /// assert_eq!(BigInt::parse_bytes(b"1234", 10), ToBigInt::to_bigint(&1234)); + /// assert_eq!(BigInt::parse_bytes(b"ABCD", 16), ToBigInt::to_bigint(&0xABCD)); + /// assert_eq!(BigInt::parse_bytes(b"G", 16), None); + /// ``` + #[inline] + pub fn parse_bytes(buf: &[u8], radix: u32) -> Option<BigInt> { + str::from_utf8(buf) + .ok() + .and_then(|s| BigInt::from_str_radix(s, radix).ok()) + } + + /// Creates and initializes a `BigInt`. Each u8 of the input slice is + /// interpreted as one digit of the number + /// and must therefore be less than `radix`. + /// + /// The bytes are in big-endian byte order. + /// `radix` must be in the range `2...256`. + /// + /// # Examples + /// + /// ``` + /// use num_bigint::{BigInt, Sign}; + /// + /// let inbase190 = vec![15, 33, 125, 12, 14]; + /// let a = BigInt::from_radix_be(Sign::Minus, &inbase190, 190).unwrap(); + /// assert_eq!(a.to_radix_be(190), (Sign:: Minus, inbase190)); + /// ``` + pub fn from_radix_be(sign: Sign, buf: &[u8], radix: u32) -> Option<BigInt> { + BigUint::from_radix_be(buf, radix).map(|u| BigInt::from_biguint(sign, u)) + } + + /// Creates and initializes a `BigInt`. Each u8 of the input slice is + /// interpreted as one digit of the number + /// and must therefore be less than `radix`. + /// + /// The bytes are in little-endian byte order. + /// `radix` must be in the range `2...256`. + /// + /// # Examples + /// + /// ``` + /// use num_bigint::{BigInt, Sign}; + /// + /// let inbase190 = vec![14, 12, 125, 33, 15]; + /// let a = BigInt::from_radix_be(Sign::Minus, &inbase190, 190).unwrap(); + /// assert_eq!(a.to_radix_be(190), (Sign::Minus, inbase190)); + /// ``` + pub fn from_radix_le(sign: Sign, buf: &[u8], radix: u32) -> Option<BigInt> { + BigUint::from_radix_le(buf, radix).map(|u| BigInt::from_biguint(sign, u)) + } + + /// Returns the sign and the byte representation of the `BigInt` in big-endian byte order. + /// + /// # Examples + /// + /// ``` + /// use num_bigint::{ToBigInt, Sign}; + /// + /// let i = -1125.to_bigint().unwrap(); + /// assert_eq!(i.to_bytes_be(), (Sign::Minus, vec![4, 101])); + /// ``` + #[inline] + pub fn to_bytes_be(&self) -> (Sign, Vec<u8>) { + (self.sign, self.data.to_bytes_be()) + } + + /// Returns the sign and the byte representation of the `BigInt` in little-endian byte order. + /// + /// # Examples + /// + /// ``` + /// use num_bigint::{ToBigInt, Sign}; + /// + /// let i = -1125.to_bigint().unwrap(); + /// assert_eq!(i.to_bytes_le(), (Sign::Minus, vec![101, 4])); + /// ``` + #[inline] + pub fn to_bytes_le(&self) -> (Sign, Vec<u8>) { + (self.sign, self.data.to_bytes_le()) + } + + /// Returns the two's complement byte representation of the `BigInt` in big-endian byte order. + /// + /// # Examples + /// + /// ``` + /// use num_bigint::ToBigInt; + /// + /// let i = -1125.to_bigint().unwrap(); + /// assert_eq!(i.to_signed_bytes_be(), vec![251, 155]); + /// ``` + #[inline] + pub fn to_signed_bytes_be(&self) -> Vec<u8> { + let mut bytes = self.data.to_bytes_be(); + let first_byte = bytes.first().map(|v| *v).unwrap_or(0); + if first_byte > 0x7f + && !(first_byte == 0x80 + && bytes.iter().skip(1).all(Zero::is_zero) + && self.sign == Sign::Minus) + { + // msb used by magnitude, extend by 1 byte + bytes.insert(0, 0); + } + if self.sign == Sign::Minus { + twos_complement_be(&mut bytes); + } + bytes + } + + /// Returns the two's complement byte representation of the `BigInt` in little-endian byte order. + /// + /// # Examples + /// + /// ``` + /// use num_bigint::ToBigInt; + /// + /// let i = -1125.to_bigint().unwrap(); + /// assert_eq!(i.to_signed_bytes_le(), vec![155, 251]); + /// ``` + #[inline] + pub fn to_signed_bytes_le(&self) -> Vec<u8> { + let mut bytes = self.data.to_bytes_le(); + let last_byte = bytes.last().map(|v| *v).unwrap_or(0); + if last_byte > 0x7f + && !(last_byte == 0x80 + && bytes.iter().rev().skip(1).all(Zero::is_zero) + && self.sign == Sign::Minus) + { + // msb used by magnitude, extend by 1 byte + bytes.push(0); + } + if self.sign == Sign::Minus { + twos_complement_le(&mut bytes); + } + bytes + } + + /// Returns the integer formatted as a string in the given radix. + /// `radix` must be in the range `2...36`. + /// + /// # Examples + /// + /// ``` + /// use num_bigint::BigInt; + /// + /// let i = BigInt::parse_bytes(b"ff", 16).unwrap(); + /// assert_eq!(i.to_str_radix(16), "ff"); + /// ``` + #[inline] + pub fn to_str_radix(&self, radix: u32) -> String { + let mut v = to_str_radix_reversed(&self.data, radix); + + if self.is_negative() { + v.push(b'-'); + } + + v.reverse(); + unsafe { String::from_utf8_unchecked(v) } + } + + /// Returns the integer in the requested base in big-endian digit order. + /// The output is not given in a human readable alphabet but as a zero + /// based u8 number. + /// `radix` must be in the range `2...256`. + /// + /// # Examples + /// + /// ``` + /// use num_bigint::{BigInt, Sign}; + /// + /// assert_eq!(BigInt::from(-0xFFFFi64).to_radix_be(159), + /// (Sign::Minus, vec![2, 94, 27])); + /// // 0xFFFF = 65535 = 2*(159^2) + 94*159 + 27 + /// ``` + #[inline] + pub fn to_radix_be(&self, radix: u32) -> (Sign, Vec<u8>) { + (self.sign, self.data.to_radix_be(radix)) + } + + /// Returns the integer in the requested base in little-endian digit order. + /// The output is not given in a human readable alphabet but as a zero + /// based u8 number. + /// `radix` must be in the range `2...256`. + /// + /// # Examples + /// + /// ``` + /// use num_bigint::{BigInt, Sign}; + /// + /// assert_eq!(BigInt::from(-0xFFFFi64).to_radix_le(159), + /// (Sign::Minus, vec![27, 94, 2])); + /// // 0xFFFF = 65535 = 27 + 94*159 + 2*(159^2) + /// ``` + #[inline] + pub fn to_radix_le(&self, radix: u32) -> (Sign, Vec<u8>) { + (self.sign, self.data.to_radix_le(radix)) + } + + /// Returns the sign of the `BigInt` as a `Sign`. + /// + /// # Examples + /// + /// ``` + /// use num_bigint::{ToBigInt, Sign}; + /// + /// assert_eq!(ToBigInt::to_bigint(&1234).unwrap().sign(), Sign::Plus); + /// assert_eq!(ToBigInt::to_bigint(&-4321).unwrap().sign(), Sign::Minus); + /// assert_eq!(ToBigInt::to_bigint(&0).unwrap().sign(), Sign::NoSign); + /// ``` + #[inline] + pub fn sign(&self) -> Sign { + self.sign + } + + /// Determines the fewest bits necessary to express the `BigInt`, + /// not including the sign. + #[inline] + pub fn bits(&self) -> usize { + self.data.bits() + } + + /// Converts this `BigInt` into a `BigUint`, if it's not negative. + #[inline] + pub fn to_biguint(&self) -> Option<BigUint> { + match self.sign { + Plus => Some(self.data.clone()), + NoSign => Some(Zero::zero()), + Minus => None, + } + } + + #[inline] + pub fn checked_add(&self, v: &BigInt) -> Option<BigInt> { + return Some(self.add(v)); + } + + #[inline] + pub fn checked_sub(&self, v: &BigInt) -> Option<BigInt> { + return Some(self.sub(v)); + } + + #[inline] + pub fn checked_mul(&self, v: &BigInt) -> Option<BigInt> { + return Some(self.mul(v)); + } + + #[inline] + pub fn checked_div(&self, v: &BigInt) -> Option<BigInt> { + if v.is_zero() { + return None; + } + return Some(self.div(v)); + } + + /// Returns `(self ^ exponent) mod modulus` + /// + /// Note that this rounds like `mod_floor`, not like the `%` operator, + /// which makes a difference when given a negative `self` or `modulus`. + /// The result will be in the interval `[0, modulus)` for `modulus > 0`, + /// or in the interval `(modulus, 0]` for `modulus < 0` + /// + /// Panics if the exponent is negative or the modulus is zero. + pub fn modpow(&self, exponent: &Self, modulus: &Self) -> Self { + assert!( + !exponent.is_negative(), + "negative exponentiation is not supported!" + ); + assert!(!modulus.is_zero(), "divide by zero!"); + + let result = self.data.modpow(&exponent.data, &modulus.data); + if result.is_zero() { + return BigInt::zero(); + } + + // The sign of the result follows the modulus, like `mod_floor`. + let (sign, mag) = match (self.is_negative(), modulus.is_negative()) { + (false, false) => (Plus, result), + (true, false) => (Plus, &modulus.data - result), + (false, true) => (Minus, &modulus.data - result), + (true, true) => (Minus, result), + }; + BigInt::from_biguint(sign, mag) + } + + /// Returns the truncated principal square root of `self` -- + /// see [Roots::sqrt](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#method.sqrt). + pub fn sqrt(&self) -> Self { + Roots::sqrt(self) + } + + /// Returns the truncated principal cube root of `self` -- + /// see [Roots::cbrt](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#method.cbrt). + pub fn cbrt(&self) -> Self { + Roots::cbrt(self) + } + + /// Returns the truncated principal `n`th root of `self` -- + /// See [Roots::nth_root](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#tymethod.nth_root). + pub fn nth_root(&self, n: u32) -> Self { + Roots::nth_root(self, n) + } +} + +impl_sum_iter_type!(BigInt); +impl_product_iter_type!(BigInt); + +/// Perform in-place two's complement of the given binary representation, +/// in little-endian byte order. +#[inline] +fn twos_complement_le(digits: &mut [u8]) { + twos_complement(digits) +} + +/// Perform in-place two's complement of the given binary representation +/// in big-endian byte order. +#[inline] +fn twos_complement_be(digits: &mut [u8]) { + twos_complement(digits.iter_mut().rev()) +} + +/// Perform in-place two's complement of the given digit iterator +/// starting from the least significant byte. +#[inline] +fn twos_complement<'a, I>(digits: I) +where + I: IntoIterator<Item = &'a mut u8>, +{ + let mut carry = true; + for d in digits { + *d = d.not(); + if carry { + *d = d.wrapping_add(1); + carry = d.is_zero(); + } + } +} + +#[test] +fn test_from_biguint() { + fn check(inp_s: Sign, inp_n: usize, ans_s: Sign, ans_n: usize) { + let inp = BigInt::from_biguint(inp_s, FromPrimitive::from_usize(inp_n).unwrap()); + let ans = BigInt { + sign: ans_s, + data: FromPrimitive::from_usize(ans_n).unwrap(), + }; + assert_eq!(inp, ans); + } + check(Plus, 1, Plus, 1); + check(Plus, 0, NoSign, 0); + check(Minus, 1, Minus, 1); + check(NoSign, 1, NoSign, 0); +} + +#[test] +fn test_from_slice() { + fn check(inp_s: Sign, inp_n: u32, ans_s: Sign, ans_n: u32) { + let inp = BigInt::from_slice(inp_s, &[inp_n]); + let ans = BigInt { + sign: ans_s, + data: FromPrimitive::from_u32(ans_n).unwrap(), + }; + assert_eq!(inp, ans); + } + check(Plus, 1, Plus, 1); + check(Plus, 0, NoSign, 0); + check(Minus, 1, Minus, 1); + check(NoSign, 1, NoSign, 0); +} + +#[test] +fn test_assign_from_slice() { + fn check(inp_s: Sign, inp_n: u32, ans_s: Sign, ans_n: u32) { + let mut inp = BigInt::from_slice(Minus, &[2627_u32, 0_u32, 9182_u32, 42_u32]); + inp.assign_from_slice(inp_s, &[inp_n]); + let ans = BigInt { + sign: ans_s, + data: FromPrimitive::from_u32(ans_n).unwrap(), + }; + assert_eq!(inp, ans); + } + check(Plus, 1, Plus, 1); + check(Plus, 0, NoSign, 0); + check(Minus, 1, Minus, 1); + check(NoSign, 1, NoSign, 0); +} diff --git a/third_party/rust/num-bigint/src/bigrand.rs b/third_party/rust/num-bigint/src/bigrand.rs new file mode 100644 index 0000000000..4a13b29df4 --- /dev/null +++ b/third_party/rust/num-bigint/src/bigrand.rs @@ -0,0 +1,218 @@ +//! Randomization of big integers + +use rand::distributions::uniform::{SampleUniform, UniformSampler}; +use rand::prelude::*; +use rand::AsByteSliceMut; + +use BigInt; +use BigUint; +use Sign::*; + +use big_digit::BigDigit; +use bigint::{into_magnitude, magnitude}; + +use integer::Integer; +use traits::Zero; + +pub trait RandBigInt { + /// Generate a random `BigUint` of the given bit size. + fn gen_biguint(&mut self, bit_size: usize) -> BigUint; + + /// Generate a random BigInt of the given bit size. + fn gen_bigint(&mut self, bit_size: usize) -> BigInt; + + /// Generate a random `BigUint` less than the given bound. Fails + /// when the bound is zero. + fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint; + + /// Generate a random `BigUint` within the given range. The lower + /// bound is inclusive; the upper bound is exclusive. Fails when + /// the upper bound is not greater than the lower bound. + fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint; + + /// Generate a random `BigInt` within the given range. The lower + /// bound is inclusive; the upper bound is exclusive. Fails when + /// the upper bound is not greater than the lower bound. + fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt; +} + +impl<R: Rng + ?Sized> RandBigInt for R { + fn gen_biguint(&mut self, bit_size: usize) -> BigUint { + use super::big_digit::BITS; + let (digits, rem) = bit_size.div_rem(&BITS); + let mut data = vec![BigDigit::default(); digits + (rem > 0) as usize]; + // `fill_bytes` is faster than many `gen::<u32>` calls + self.fill_bytes(data[..].as_byte_slice_mut()); + // Swap bytes per the `Rng::fill` source. This might be + // unnecessary if reproducibility across architectures is not + // desired. + data.to_le(); + if rem > 0 { + data[digits] >>= BITS - rem; + } + BigUint::new(data) + } + + fn gen_bigint(&mut self, bit_size: usize) -> BigInt { + loop { + // Generate a random BigUint... + let biguint = self.gen_biguint(bit_size); + // ...and then randomly assign it a Sign... + let sign = if biguint.is_zero() { + // ...except that if the BigUint is zero, we need to try + // again with probability 0.5. This is because otherwise, + // the probability of generating a zero BigInt would be + // double that of any other number. + if self.gen() { + continue; + } else { + NoSign + } + } else if self.gen() { + Plus + } else { + Minus + }; + return BigInt::from_biguint(sign, biguint); + } + } + + fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint { + assert!(!bound.is_zero()); + let bits = bound.bits(); + loop { + let n = self.gen_biguint(bits); + if n < *bound { + return n; + } + } + } + + fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint { + assert!(*lbound < *ubound); + if lbound.is_zero() { + self.gen_biguint_below(ubound) + } else { + lbound + self.gen_biguint_below(&(ubound - lbound)) + } + } + + fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt { + assert!(*lbound < *ubound); + if lbound.is_zero() { + BigInt::from(self.gen_biguint_below(magnitude(&ubound))) + } else if ubound.is_zero() { + lbound + BigInt::from(self.gen_biguint_below(magnitude(&lbound))) + } else { + let delta = ubound - lbound; + lbound + BigInt::from(self.gen_biguint_below(magnitude(&delta))) + } + } +} + +/// The back-end implementing rand's `UniformSampler` for `BigUint`. +#[derive(Clone, Debug)] +pub struct UniformBigUint { + base: BigUint, + len: BigUint, +} + +impl UniformSampler for UniformBigUint { + type X = BigUint; + + #[inline] + fn new(low: Self::X, high: Self::X) -> Self { + assert!(low < high); + UniformBigUint { + len: high - &low, + base: low, + } + } + + #[inline] + fn new_inclusive(low: Self::X, high: Self::X) -> Self { + assert!(low <= high); + Self::new(low, high + 1u32) + } + + #[inline] + fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X { + &self.base + rng.gen_biguint_below(&self.len) + } + + #[inline] + fn sample_single<R: Rng + ?Sized>(low: Self::X, high: Self::X, rng: &mut R) -> Self::X { + rng.gen_biguint_range(&low, &high) + } +} + +impl SampleUniform for BigUint { + type Sampler = UniformBigUint; +} + +/// The back-end implementing rand's `UniformSampler` for `BigInt`. +#[derive(Clone, Debug)] +pub struct UniformBigInt { + base: BigInt, + len: BigUint, +} + +impl UniformSampler for UniformBigInt { + type X = BigInt; + + #[inline] + fn new(low: Self::X, high: Self::X) -> Self { + assert!(low < high); + UniformBigInt { + len: into_magnitude(high - &low), + base: low, + } + } + + #[inline] + fn new_inclusive(low: Self::X, high: Self::X) -> Self { + assert!(low <= high); + Self::new(low, high + 1u32) + } + + #[inline] + fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X { + &self.base + BigInt::from(rng.gen_biguint_below(&self.len)) + } + + #[inline] + fn sample_single<R: Rng + ?Sized>(low: Self::X, high: Self::X, rng: &mut R) -> Self::X { + rng.gen_bigint_range(&low, &high) + } +} + +impl SampleUniform for BigInt { + type Sampler = UniformBigInt; +} + +/// A random distribution for `BigUint` and `BigInt` values of a particular bit size. +#[derive(Clone, Copy, Debug)] +pub struct RandomBits { + bits: usize, +} + +impl RandomBits { + #[inline] + pub fn new(bits: usize) -> RandomBits { + RandomBits { bits } + } +} + +impl Distribution<BigUint> for RandomBits { + #[inline] + fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> BigUint { + rng.gen_biguint(self.bits) + } +} + +impl Distribution<BigInt> for RandomBits { + #[inline] + fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> BigInt { + rng.gen_bigint(self.bits) + } +} diff --git a/third_party/rust/num-bigint/src/biguint.rs b/third_party/rust/num-bigint/src/biguint.rs new file mode 100644 index 0000000000..e6e9fbcce5 --- /dev/null +++ b/third_party/rust/num-bigint/src/biguint.rs @@ -0,0 +1,3088 @@ +#[allow(deprecated, unused_imports)] +use std::ascii::AsciiExt; +use std::borrow::Cow; +use std::cmp; +use std::cmp::Ordering::{self, Equal, Greater, Less}; +use std::default::Default; +use std::fmt; +use std::iter::{Product, Sum}; +use std::mem; +use std::ops::{ + Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign, + Mul, MulAssign, Neg, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign, +}; +use std::str::{self, FromStr}; +use std::{f32, f64}; +use std::{u64, u8}; + +#[cfg(feature = "serde")] +use serde; + +use integer::{Integer, Roots}; +use traits::{ + CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, Float, FromPrimitive, Num, One, Pow, + ToPrimitive, Unsigned, Zero, +}; + +use big_digit::{self, BigDigit}; + +#[path = "algorithms.rs"] +mod algorithms; +#[path = "monty.rs"] +mod monty; + +use self::algorithms::{__add2, __sub2rev, add2, sub2, sub2rev}; +use self::algorithms::{biguint_shl, biguint_shr}; +use self::algorithms::{cmp_slice, fls, ilog2}; +use self::algorithms::{div_rem, div_rem_digit, div_rem_ref, rem_digit}; +use self::algorithms::{mac_with_carry, mul3, scalar_mul}; +use self::monty::monty_modpow; + +use UsizePromotion; + +use ParseBigIntError; + +#[cfg(feature = "quickcheck")] +use quickcheck::{Arbitrary, Gen}; + +/// A big unsigned integer type. +#[derive(Clone, Debug, Hash)] +pub struct BigUint { + data: Vec<BigDigit>, +} + +#[cfg(feature = "quickcheck")] +impl Arbitrary for BigUint { + fn arbitrary<G: Gen>(g: &mut G) -> Self { + // Use arbitrary from Vec + Self::new(Vec::<u32>::arbitrary(g)) + } + + #[allow(bare_trait_objects)] // `dyn` needs Rust 1.27 to parse, even when cfg-disabled + fn shrink(&self) -> Box<Iterator<Item = Self>> { + // Use shrinker from Vec + Box::new(self.data.shrink().map(|x| BigUint::new(x))) + } +} + +impl PartialEq for BigUint { + #[inline] + fn eq(&self, other: &BigUint) -> bool { + match self.cmp(other) { + Equal => true, + _ => false, + } + } +} +impl Eq for BigUint {} + +impl PartialOrd for BigUint { + #[inline] + fn partial_cmp(&self, other: &BigUint) -> Option<Ordering> { + Some(self.cmp(other)) + } +} + +impl Ord for BigUint { + #[inline] + fn cmp(&self, other: &BigUint) -> Ordering { + cmp_slice(&self.data[..], &other.data[..]) + } +} + +impl Default for BigUint { + #[inline] + fn default() -> BigUint { + Zero::zero() + } +} + +impl fmt::Display for BigUint { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad_integral(true, "", &self.to_str_radix(10)) + } +} + +impl fmt::LowerHex for BigUint { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad_integral(true, "0x", &self.to_str_radix(16)) + } +} + +impl fmt::UpperHex for BigUint { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut s = self.to_str_radix(16); + s.make_ascii_uppercase(); + f.pad_integral(true, "0x", &s) + } +} + +impl fmt::Binary for BigUint { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad_integral(true, "0b", &self.to_str_radix(2)) + } +} + +impl fmt::Octal for BigUint { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad_integral(true, "0o", &self.to_str_radix(8)) + } +} + +impl FromStr for BigUint { + type Err = ParseBigIntError; + + #[inline] + fn from_str(s: &str) -> Result<BigUint, ParseBigIntError> { + BigUint::from_str_radix(s, 10) + } +} + +// Convert from a power of two radix (bits == ilog2(radix)) where bits evenly divides +// BigDigit::BITS +fn from_bitwise_digits_le(v: &[u8], bits: usize) -> BigUint { + debug_assert!(!v.is_empty() && bits <= 8 && big_digit::BITS % bits == 0); + debug_assert!(v.iter().all(|&c| BigDigit::from(c) < (1 << bits))); + + let digits_per_big_digit = big_digit::BITS / bits; + + let data = v + .chunks(digits_per_big_digit) + .map(|chunk| { + chunk + .iter() + .rev() + .fold(0, |acc, &c| (acc << bits) | BigDigit::from(c)) + }) + .collect(); + + BigUint::new(data) +} + +// Convert from a power of two radix (bits == ilog2(radix)) where bits doesn't evenly divide +// BigDigit::BITS +fn from_inexact_bitwise_digits_le(v: &[u8], bits: usize) -> BigUint { + debug_assert!(!v.is_empty() && bits <= 8 && big_digit::BITS % bits != 0); + debug_assert!(v.iter().all(|&c| BigDigit::from(c) < (1 << bits))); + + let big_digits = (v.len() * bits + big_digit::BITS - 1) / big_digit::BITS; + let mut data = Vec::with_capacity(big_digits); + + let mut d = 0; + let mut dbits = 0; // number of bits we currently have in d + + // walk v accumululating bits in d; whenever we accumulate big_digit::BITS in d, spit out a + // big_digit: + for &c in v { + d |= BigDigit::from(c) << dbits; + dbits += bits; + + if dbits >= big_digit::BITS { + data.push(d); + dbits -= big_digit::BITS; + // if dbits was > big_digit::BITS, we dropped some of the bits in c (they couldn't fit + // in d) - grab the bits we lost here: + d = BigDigit::from(c) >> (bits - dbits); + } + } + + if dbits > 0 { + debug_assert!(dbits < big_digit::BITS); + data.push(d as BigDigit); + } + + BigUint::new(data) +} + +// Read little-endian radix digits +fn from_radix_digits_be(v: &[u8], radix: u32) -> BigUint { + debug_assert!(!v.is_empty() && !radix.is_power_of_two()); + debug_assert!(v.iter().all(|&c| u32::from(c) < radix)); + + // Estimate how big the result will be, so we can pre-allocate it. + let bits = f64::from(radix).log2() * v.len() as f64; + let big_digits = (bits / big_digit::BITS as f64).ceil(); + let mut data = Vec::with_capacity(big_digits as usize); + + let (base, power) = get_radix_base(radix); + let radix = radix as BigDigit; + + let r = v.len() % power; + let i = if r == 0 { power } else { r }; + let (head, tail) = v.split_at(i); + + let first = head + .iter() + .fold(0, |acc, &d| acc * radix + BigDigit::from(d)); + data.push(first); + + debug_assert!(tail.len() % power == 0); + for chunk in tail.chunks(power) { + if data.last() != Some(&0) { + data.push(0); + } + + let mut carry = 0; + for d in data.iter_mut() { + *d = mac_with_carry(0, *d, base, &mut carry); + } + debug_assert!(carry == 0); + + let n = chunk + .iter() + .fold(0, |acc, &d| acc * radix + BigDigit::from(d)); + add2(&mut data, &[n]); + } + + BigUint::new(data) +} + +impl Num for BigUint { + type FromStrRadixErr = ParseBigIntError; + + /// Creates and initializes a `BigUint`. + fn from_str_radix(s: &str, radix: u32) -> Result<BigUint, ParseBigIntError> { + assert!(2 <= radix && radix <= 36, "The radix must be within 2...36"); + let mut s = s; + if s.starts_with('+') { + let tail = &s[1..]; + if !tail.starts_with('+') { + s = tail + } + } + + if s.is_empty() { + return Err(ParseBigIntError::empty()); + } + + if s.starts_with('_') { + // Must lead with a real digit! + return Err(ParseBigIntError::invalid()); + } + + // First normalize all characters to plain digit values + let mut v = Vec::with_capacity(s.len()); + for b in s.bytes() { + #[allow(unknown_lints, ellipsis_inclusive_range_patterns)] + let d = match b { + b'0'...b'9' => b - b'0', + b'a'...b'z' => b - b'a' + 10, + b'A'...b'Z' => b - b'A' + 10, + b'_' => continue, + _ => u8::MAX, + }; + if d < radix as u8 { + v.push(d); + } else { + return Err(ParseBigIntError::invalid()); + } + } + + let res = if radix.is_power_of_two() { + // Powers of two can use bitwise masks and shifting instead of multiplication + let bits = ilog2(radix); + v.reverse(); + if big_digit::BITS % bits == 0 { + from_bitwise_digits_le(&v, bits) + } else { + from_inexact_bitwise_digits_le(&v, bits) + } + } else { + from_radix_digits_be(&v, radix) + }; + Ok(res) + } +} + +forward_val_val_binop!(impl BitAnd for BigUint, bitand); +forward_ref_val_binop!(impl BitAnd for BigUint, bitand); + +// do not use forward_ref_ref_binop_commutative! for bitand so that we can +// clone the smaller value rather than the larger, avoiding over-allocation +impl<'a, 'b> BitAnd<&'b BigUint> for &'a BigUint { + type Output = BigUint; + + #[inline] + fn bitand(self, other: &BigUint) -> BigUint { + // forward to val-ref, choosing the smaller to clone + if self.data.len() <= other.data.len() { + self.clone() & other + } else { + other.clone() & self + } + } +} + +forward_val_assign!(impl BitAndAssign for BigUint, bitand_assign); + +impl<'a> BitAnd<&'a BigUint> for BigUint { + type Output = BigUint; + + #[inline] + fn bitand(mut self, other: &BigUint) -> BigUint { + self &= other; + self + } +} +impl<'a> BitAndAssign<&'a BigUint> for BigUint { + #[inline] + fn bitand_assign(&mut self, other: &BigUint) { + for (ai, &bi) in self.data.iter_mut().zip(other.data.iter()) { + *ai &= bi; + } + self.data.truncate(other.data.len()); + self.normalize(); + } +} + +forward_all_binop_to_val_ref_commutative!(impl BitOr for BigUint, bitor); +forward_val_assign!(impl BitOrAssign for BigUint, bitor_assign); + +impl<'a> BitOr<&'a BigUint> for BigUint { + type Output = BigUint; + + fn bitor(mut self, other: &BigUint) -> BigUint { + self |= other; + self + } +} +impl<'a> BitOrAssign<&'a BigUint> for BigUint { + #[inline] + fn bitor_assign(&mut self, other: &BigUint) { + for (ai, &bi) in self.data.iter_mut().zip(other.data.iter()) { + *ai |= bi; + } + if other.data.len() > self.data.len() { + let extra = &other.data[self.data.len()..]; + self.data.extend(extra.iter().cloned()); + } + } +} + +forward_all_binop_to_val_ref_commutative!(impl BitXor for BigUint, bitxor); +forward_val_assign!(impl BitXorAssign for BigUint, bitxor_assign); + +impl<'a> BitXor<&'a BigUint> for BigUint { + type Output = BigUint; + + fn bitxor(mut self, other: &BigUint) -> BigUint { + self ^= other; + self + } +} +impl<'a> BitXorAssign<&'a BigUint> for BigUint { + #[inline] + fn bitxor_assign(&mut self, other: &BigUint) { + for (ai, &bi) in self.data.iter_mut().zip(other.data.iter()) { + *ai ^= bi; + } + if other.data.len() > self.data.len() { + let extra = &other.data[self.data.len()..]; + self.data.extend(extra.iter().cloned()); + } + self.normalize(); + } +} + +impl Shl<usize> for BigUint { + type Output = BigUint; + + #[inline] + fn shl(self, rhs: usize) -> BigUint { + biguint_shl(Cow::Owned(self), rhs) + } +} +impl<'a> Shl<usize> for &'a BigUint { + type Output = BigUint; + + #[inline] + fn shl(self, rhs: usize) -> BigUint { + biguint_shl(Cow::Borrowed(self), rhs) + } +} + +impl ShlAssign<usize> for BigUint { + #[inline] + fn shl_assign(&mut self, rhs: usize) { + let n = mem::replace(self, BigUint::zero()); + *self = n << rhs; + } +} + +impl Shr<usize> for BigUint { + type Output = BigUint; + + #[inline] + fn shr(self, rhs: usize) -> BigUint { + biguint_shr(Cow::Owned(self), rhs) + } +} +impl<'a> Shr<usize> for &'a BigUint { + type Output = BigUint; + + #[inline] + fn shr(self, rhs: usize) -> BigUint { + biguint_shr(Cow::Borrowed(self), rhs) + } +} + +impl ShrAssign<usize> for BigUint { + #[inline] + fn shr_assign(&mut self, rhs: usize) { + let n = mem::replace(self, BigUint::zero()); + *self = n >> rhs; + } +} + +impl Zero for BigUint { + #[inline] + fn zero() -> BigUint { + BigUint::new(Vec::new()) + } + + #[inline] + fn set_zero(&mut self) { + self.data.clear(); + } + + #[inline] + fn is_zero(&self) -> bool { + self.data.is_empty() + } +} + +impl One for BigUint { + #[inline] + fn one() -> BigUint { + BigUint::new(vec![1]) + } + + #[inline] + fn set_one(&mut self) { + self.data.clear(); + self.data.push(1); + } + + #[inline] + fn is_one(&self) -> bool { + self.data[..] == [1] + } +} + +impl Unsigned for BigUint {} + +impl<'a> Pow<BigUint> for &'a BigUint { + type Output = BigUint; + + #[inline] + fn pow(self, exp: BigUint) -> Self::Output { + self.pow(&exp) + } +} + +impl<'a, 'b> Pow<&'b BigUint> for &'a BigUint { + type Output = BigUint; + + #[inline] + fn pow(self, exp: &BigUint) -> Self::Output { + if self.is_one() || exp.is_zero() { + BigUint::one() + } else if self.is_zero() { + BigUint::zero() + } else if let Some(exp) = exp.to_u64() { + self.pow(exp) + } else { + // At this point, `self >= 2` and `exp >= 2⁶⁴`. The smallest possible result + // given `2.pow(2⁶⁴)` would take 2.3 exabytes of memory! + panic!("memory overflow") + } + } +} + +macro_rules! pow_impl { + ($T:ty) => { + impl<'a> Pow<$T> for &'a BigUint { + type Output = BigUint; + + #[inline] + fn pow(self, mut exp: $T) -> Self::Output { + if exp == 0 { + return BigUint::one(); + } + let mut base = self.clone(); + + while exp & 1 == 0 { + base = &base * &base; + exp >>= 1; + } + + if exp == 1 { + return base; + } + + let mut acc = base.clone(); + while exp > 1 { + exp >>= 1; + base = &base * &base; + if exp & 1 == 1 { + acc = &acc * &base; + } + } + acc + } + } + + impl<'a, 'b> Pow<&'b $T> for &'a BigUint { + type Output = BigUint; + + #[inline] + fn pow(self, exp: &$T) -> Self::Output { + self.pow(*exp) + } + } + }; +} + +pow_impl!(u8); +pow_impl!(u16); +pow_impl!(u32); +pow_impl!(u64); +pow_impl!(usize); +#[cfg(has_i128)] +pow_impl!(u128); + +forward_all_binop_to_val_ref_commutative!(impl Add for BigUint, add); +forward_val_assign!(impl AddAssign for BigUint, add_assign); + +impl<'a> Add<&'a BigUint> for BigUint { + type Output = BigUint; + + fn add(mut self, other: &BigUint) -> BigUint { + self += other; + self + } +} +impl<'a> AddAssign<&'a BigUint> for BigUint { + #[inline] + fn add_assign(&mut self, other: &BigUint) { + let self_len = self.data.len(); + let carry = if self_len < other.data.len() { + let lo_carry = __add2(&mut self.data[..], &other.data[..self_len]); + self.data.extend_from_slice(&other.data[self_len..]); + __add2(&mut self.data[self_len..], &[lo_carry]) + } else { + __add2(&mut self.data[..], &other.data[..]) + }; + if carry != 0 { + self.data.push(carry); + } + } +} + +promote_unsigned_scalars!(impl Add for BigUint, add); +promote_unsigned_scalars_assign!(impl AddAssign for BigUint, add_assign); +forward_all_scalar_binop_to_val_val_commutative!(impl Add<u32> for BigUint, add); +forward_all_scalar_binop_to_val_val_commutative!(impl Add<u64> for BigUint, add); +#[cfg(has_i128)] +forward_all_scalar_binop_to_val_val_commutative!(impl Add<u128> for BigUint, add); + +impl Add<u32> for BigUint { + type Output = BigUint; + + #[inline] + fn add(mut self, other: u32) -> BigUint { + self += other; + self + } +} + +impl AddAssign<u32> for BigUint { + #[inline] + fn add_assign(&mut self, other: u32) { + if other != 0 { + if self.data.len() == 0 { + self.data.push(0); + } + + let carry = __add2(&mut self.data, &[other as BigDigit]); + if carry != 0 { + self.data.push(carry); + } + } + } +} + +impl Add<u64> for BigUint { + type Output = BigUint; + + #[inline] + fn add(mut self, other: u64) -> BigUint { + self += other; + self + } +} + +impl AddAssign<u64> for BigUint { + #[inline] + fn add_assign(&mut self, other: u64) { + let (hi, lo) = big_digit::from_doublebigdigit(other); + if hi == 0 { + *self += lo; + } else { + while self.data.len() < 2 { + self.data.push(0); + } + + let carry = __add2(&mut self.data, &[lo, hi]); + if carry != 0 { + self.data.push(carry); + } + } + } +} + +#[cfg(has_i128)] +impl Add<u128> for BigUint { + type Output = BigUint; + + #[inline] + fn add(mut self, other: u128) -> BigUint { + self += other; + self + } +} + +#[cfg(has_i128)] +impl AddAssign<u128> for BigUint { + #[inline] + fn add_assign(&mut self, other: u128) { + if other <= u128::from(u64::max_value()) { + *self += other as u64 + } else { + let (a, b, c, d) = u32_from_u128(other); + let carry = if a > 0 { + while self.data.len() < 4 { + self.data.push(0); + } + __add2(&mut self.data, &[d, c, b, a]) + } else { + debug_assert!(b > 0); + while self.data.len() < 3 { + self.data.push(0); + } + __add2(&mut self.data, &[d, c, b]) + }; + + if carry != 0 { + self.data.push(carry); + } + } + } +} + +forward_val_val_binop!(impl Sub for BigUint, sub); +forward_ref_ref_binop!(impl Sub for BigUint, sub); +forward_val_assign!(impl SubAssign for BigUint, sub_assign); + +impl<'a> Sub<&'a BigUint> for BigUint { + type Output = BigUint; + + fn sub(mut self, other: &BigUint) -> BigUint { + self -= other; + self + } +} +impl<'a> SubAssign<&'a BigUint> for BigUint { + fn sub_assign(&mut self, other: &'a BigUint) { + sub2(&mut self.data[..], &other.data[..]); + self.normalize(); + } +} + +impl<'a> Sub<BigUint> for &'a BigUint { + type Output = BigUint; + + fn sub(self, mut other: BigUint) -> BigUint { + let other_len = other.data.len(); + if other_len < self.data.len() { + let lo_borrow = __sub2rev(&self.data[..other_len], &mut other.data); + other.data.extend_from_slice(&self.data[other_len..]); + if lo_borrow != 0 { + sub2(&mut other.data[other_len..], &[1]) + } + } else { + sub2rev(&self.data[..], &mut other.data[..]); + } + other.normalized() + } +} + +promote_unsigned_scalars!(impl Sub for BigUint, sub); +promote_unsigned_scalars_assign!(impl SubAssign for BigUint, sub_assign); +forward_all_scalar_binop_to_val_val!(impl Sub<u32> for BigUint, sub); +forward_all_scalar_binop_to_val_val!(impl Sub<u64> for BigUint, sub); +#[cfg(has_i128)] +forward_all_scalar_binop_to_val_val!(impl Sub<u128> for BigUint, sub); + +impl Sub<u32> for BigUint { + type Output = BigUint; + + #[inline] + fn sub(mut self, other: u32) -> BigUint { + self -= other; + self + } +} +impl SubAssign<u32> for BigUint { + fn sub_assign(&mut self, other: u32) { + sub2(&mut self.data[..], &[other as BigDigit]); + self.normalize(); + } +} + +impl Sub<BigUint> for u32 { + type Output = BigUint; + + #[inline] + fn sub(self, mut other: BigUint) -> BigUint { + if other.data.len() == 0 { + other.data.push(self as BigDigit); + } else { + sub2rev(&[self as BigDigit], &mut other.data[..]); + } + other.normalized() + } +} + +impl Sub<u64> for BigUint { + type Output = BigUint; + + #[inline] + fn sub(mut self, other: u64) -> BigUint { + self -= other; + self + } +} + +impl SubAssign<u64> for BigUint { + #[inline] + fn sub_assign(&mut self, other: u64) { + let (hi, lo) = big_digit::from_doublebigdigit(other); + sub2(&mut self.data[..], &[lo, hi]); + self.normalize(); + } +} + +impl Sub<BigUint> for u64 { + type Output = BigUint; + + #[inline] + fn sub(self, mut other: BigUint) -> BigUint { + while other.data.len() < 2 { + other.data.push(0); + } + + let (hi, lo) = big_digit::from_doublebigdigit(self); + sub2rev(&[lo, hi], &mut other.data[..]); + other.normalized() + } +} + +#[cfg(has_i128)] +impl Sub<u128> for BigUint { + type Output = BigUint; + + #[inline] + fn sub(mut self, other: u128) -> BigUint { + self -= other; + self + } +} +#[cfg(has_i128)] +impl SubAssign<u128> for BigUint { + fn sub_assign(&mut self, other: u128) { + let (a, b, c, d) = u32_from_u128(other); + sub2(&mut self.data[..], &[d, c, b, a]); + self.normalize(); + } +} + +#[cfg(has_i128)] +impl Sub<BigUint> for u128 { + type Output = BigUint; + + #[inline] + fn sub(self, mut other: BigUint) -> BigUint { + while other.data.len() < 4 { + other.data.push(0); + } + + let (a, b, c, d) = u32_from_u128(self); + sub2rev(&[d, c, b, a], &mut other.data[..]); + other.normalized() + } +} + +forward_all_binop_to_ref_ref!(impl Mul for BigUint, mul); +forward_val_assign!(impl MulAssign for BigUint, mul_assign); + +impl<'a, 'b> Mul<&'b BigUint> for &'a BigUint { + type Output = BigUint; + + #[inline] + fn mul(self, other: &BigUint) -> BigUint { + mul3(&self.data[..], &other.data[..]) + } +} +impl<'a> MulAssign<&'a BigUint> for BigUint { + #[inline] + fn mul_assign(&mut self, other: &'a BigUint) { + *self = &*self * other + } +} + +promote_unsigned_scalars!(impl Mul for BigUint, mul); +promote_unsigned_scalars_assign!(impl MulAssign for BigUint, mul_assign); +forward_all_scalar_binop_to_val_val_commutative!(impl Mul<u32> for BigUint, mul); +forward_all_scalar_binop_to_val_val_commutative!(impl Mul<u64> for BigUint, mul); +#[cfg(has_i128)] +forward_all_scalar_binop_to_val_val_commutative!(impl Mul<u128> for BigUint, mul); + +impl Mul<u32> for BigUint { + type Output = BigUint; + + #[inline] + fn mul(mut self, other: u32) -> BigUint { + self *= other; + self + } +} +impl MulAssign<u32> for BigUint { + #[inline] + fn mul_assign(&mut self, other: u32) { + if other == 0 { + self.data.clear(); + } else { + let carry = scalar_mul(&mut self.data[..], other as BigDigit); + if carry != 0 { + self.data.push(carry); + } + } + } +} + +impl Mul<u64> for BigUint { + type Output = BigUint; + + #[inline] + fn mul(mut self, other: u64) -> BigUint { + self *= other; + self + } +} +impl MulAssign<u64> for BigUint { + #[inline] + fn mul_assign(&mut self, other: u64) { + if other == 0 { + self.data.clear(); + } else if other <= u64::from(BigDigit::max_value()) { + *self *= other as BigDigit + } else { + let (hi, lo) = big_digit::from_doublebigdigit(other); + *self = mul3(&self.data[..], &[lo, hi]) + } + } +} + +#[cfg(has_i128)] +impl Mul<u128> for BigUint { + type Output = BigUint; + + #[inline] + fn mul(mut self, other: u128) -> BigUint { + self *= other; + self + } +} +#[cfg(has_i128)] +impl MulAssign<u128> for BigUint { + #[inline] + fn mul_assign(&mut self, other: u128) { + if other == 0 { + self.data.clear(); + } else if other <= u128::from(BigDigit::max_value()) { + *self *= other as BigDigit + } else { + let (a, b, c, d) = u32_from_u128(other); + *self = mul3(&self.data[..], &[d, c, b, a]) + } + } +} + +forward_val_ref_binop!(impl Div for BigUint, div); +forward_ref_val_binop!(impl Div for BigUint, div); +forward_val_assign!(impl DivAssign for BigUint, div_assign); + +impl Div<BigUint> for BigUint { + type Output = BigUint; + + #[inline] + fn div(self, other: BigUint) -> BigUint { + let (q, _) = div_rem(self, other); + q + } +} + +impl<'a, 'b> Div<&'b BigUint> for &'a BigUint { + type Output = BigUint; + + #[inline] + fn div(self, other: &BigUint) -> BigUint { + let (q, _) = self.div_rem(other); + q + } +} +impl<'a> DivAssign<&'a BigUint> for BigUint { + #[inline] + fn div_assign(&mut self, other: &'a BigUint) { + *self = &*self / other; + } +} + +promote_unsigned_scalars!(impl Div for BigUint, div); +promote_unsigned_scalars_assign!(impl DivAssign for BigUint, div_assign); +forward_all_scalar_binop_to_val_val!(impl Div<u32> for BigUint, div); +forward_all_scalar_binop_to_val_val!(impl Div<u64> for BigUint, div); +#[cfg(has_i128)] +forward_all_scalar_binop_to_val_val!(impl Div<u128> for BigUint, div); + +impl Div<u32> for BigUint { + type Output = BigUint; + + #[inline] + fn div(self, other: u32) -> BigUint { + let (q, _) = div_rem_digit(self, other as BigDigit); + q + } +} +impl DivAssign<u32> for BigUint { + #[inline] + fn div_assign(&mut self, other: u32) { + *self = &*self / other; + } +} + +impl Div<BigUint> for u32 { + type Output = BigUint; + + #[inline] + fn div(self, other: BigUint) -> BigUint { + match other.data.len() { + 0 => panic!(), + 1 => From::from(self as BigDigit / other.data[0]), + _ => Zero::zero(), + } + } +} + +impl Div<u64> for BigUint { + type Output = BigUint; + + #[inline] + fn div(self, other: u64) -> BigUint { + let (q, _) = div_rem(self, From::from(other)); + q + } +} +impl DivAssign<u64> for BigUint { + #[inline] + fn div_assign(&mut self, other: u64) { + // a vec of size 0 does not allocate, so this is fairly cheap + let temp = mem::replace(self, Zero::zero()); + *self = temp / other; + } +} + +impl Div<BigUint> for u64 { + type Output = BigUint; + + #[inline] + fn div(self, other: BigUint) -> BigUint { + match other.data.len() { + 0 => panic!(), + 1 => From::from(self / u64::from(other.data[0])), + 2 => From::from(self / big_digit::to_doublebigdigit(other.data[1], other.data[0])), + _ => Zero::zero(), + } + } +} + +#[cfg(has_i128)] +impl Div<u128> for BigUint { + type Output = BigUint; + + #[inline] + fn div(self, other: u128) -> BigUint { + let (q, _) = div_rem(self, From::from(other)); + q + } +} +#[cfg(has_i128)] +impl DivAssign<u128> for BigUint { + #[inline] + fn div_assign(&mut self, other: u128) { + *self = &*self / other; + } +} + +#[cfg(has_i128)] +impl Div<BigUint> for u128 { + type Output = BigUint; + + #[inline] + fn div(self, other: BigUint) -> BigUint { + match other.data.len() { + 0 => panic!(), + 1 => From::from(self / u128::from(other.data[0])), + 2 => From::from( + self / u128::from(big_digit::to_doublebigdigit(other.data[1], other.data[0])), + ), + 3 => From::from(self / u32_to_u128(0, other.data[2], other.data[1], other.data[0])), + 4 => From::from( + self / u32_to_u128(other.data[3], other.data[2], other.data[1], other.data[0]), + ), + _ => Zero::zero(), + } + } +} + +forward_val_ref_binop!(impl Rem for BigUint, rem); +forward_ref_val_binop!(impl Rem for BigUint, rem); +forward_val_assign!(impl RemAssign for BigUint, rem_assign); + +impl Rem<BigUint> for BigUint { + type Output = BigUint; + + #[inline] + fn rem(self, other: BigUint) -> BigUint { + let (_, r) = div_rem(self, other); + r + } +} + +impl<'a, 'b> Rem<&'b BigUint> for &'a BigUint { + type Output = BigUint; + + #[inline] + fn rem(self, other: &BigUint) -> BigUint { + let (_, r) = self.div_rem(other); + r + } +} +impl<'a> RemAssign<&'a BigUint> for BigUint { + #[inline] + fn rem_assign(&mut self, other: &BigUint) { + *self = &*self % other; + } +} + +promote_unsigned_scalars!(impl Rem for BigUint, rem); +promote_unsigned_scalars_assign!(impl RemAssign for BigUint, rem_assign); +forward_all_scalar_binop_to_ref_val!(impl Rem<u32> for BigUint, rem); +forward_all_scalar_binop_to_val_val!(impl Rem<u64> for BigUint, rem); +#[cfg(has_i128)] +forward_all_scalar_binop_to_val_val!(impl Rem<u128> for BigUint, rem); + +impl<'a> Rem<u32> for &'a BigUint { + type Output = BigUint; + + #[inline] + fn rem(self, other: u32) -> BigUint { + From::from(rem_digit(self, other as BigDigit)) + } +} +impl RemAssign<u32> for BigUint { + #[inline] + fn rem_assign(&mut self, other: u32) { + *self = &*self % other; + } +} + +impl<'a> Rem<&'a BigUint> for u32 { + type Output = BigUint; + + #[inline] + fn rem(mut self, other: &'a BigUint) -> BigUint { + self %= other; + From::from(self) + } +} + +macro_rules! impl_rem_assign_scalar { + ($scalar:ty, $to_scalar:ident) => { + forward_val_assign_scalar!(impl RemAssign for BigUint, $scalar, rem_assign); + impl<'a> RemAssign<&'a BigUint> for $scalar { + #[inline] + fn rem_assign(&mut self, other: &BigUint) { + *self = match other.$to_scalar() { + None => *self, + Some(0) => panic!(), + Some(v) => *self % v + }; + } + } + } +} +// we can scalar %= BigUint for any scalar, including signed types +#[cfg(has_i128)] +impl_rem_assign_scalar!(u128, to_u128); +impl_rem_assign_scalar!(usize, to_usize); +impl_rem_assign_scalar!(u64, to_u64); +impl_rem_assign_scalar!(u32, to_u32); +impl_rem_assign_scalar!(u16, to_u16); +impl_rem_assign_scalar!(u8, to_u8); +#[cfg(has_i128)] +impl_rem_assign_scalar!(i128, to_i128); +impl_rem_assign_scalar!(isize, to_isize); +impl_rem_assign_scalar!(i64, to_i64); +impl_rem_assign_scalar!(i32, to_i32); +impl_rem_assign_scalar!(i16, to_i16); +impl_rem_assign_scalar!(i8, to_i8); + +impl Rem<u64> for BigUint { + type Output = BigUint; + + #[inline] + fn rem(self, other: u64) -> BigUint { + let (_, r) = div_rem(self, From::from(other)); + r + } +} +impl RemAssign<u64> for BigUint { + #[inline] + fn rem_assign(&mut self, other: u64) { + *self = &*self % other; + } +} + +impl Rem<BigUint> for u64 { + type Output = BigUint; + + #[inline] + fn rem(mut self, other: BigUint) -> BigUint { + self %= other; + From::from(self) + } +} + +#[cfg(has_i128)] +impl Rem<u128> for BigUint { + type Output = BigUint; + + #[inline] + fn rem(self, other: u128) -> BigUint { + let (_, r) = div_rem(self, From::from(other)); + r + } +} +#[cfg(has_i128)] +impl RemAssign<u128> for BigUint { + #[inline] + fn rem_assign(&mut self, other: u128) { + *self = &*self % other; + } +} + +#[cfg(has_i128)] +impl Rem<BigUint> for u128 { + type Output = BigUint; + + #[inline] + fn rem(mut self, other: BigUint) -> BigUint { + self %= other; + From::from(self) + } +} + +impl Neg for BigUint { + type Output = BigUint; + + #[inline] + fn neg(self) -> BigUint { + panic!() + } +} + +impl<'a> Neg for &'a BigUint { + type Output = BigUint; + + #[inline] + fn neg(self) -> BigUint { + panic!() + } +} + +impl CheckedAdd for BigUint { + #[inline] + fn checked_add(&self, v: &BigUint) -> Option<BigUint> { + return Some(self.add(v)); + } +} + +impl CheckedSub for BigUint { + #[inline] + fn checked_sub(&self, v: &BigUint) -> Option<BigUint> { + match self.cmp(v) { + Less => None, + Equal => Some(Zero::zero()), + Greater => Some(self.sub(v)), + } + } +} + +impl CheckedMul for BigUint { + #[inline] + fn checked_mul(&self, v: &BigUint) -> Option<BigUint> { + return Some(self.mul(v)); + } +} + +impl CheckedDiv for BigUint { + #[inline] + fn checked_div(&self, v: &BigUint) -> Option<BigUint> { + if v.is_zero() { + return None; + } + return Some(self.div(v)); + } +} + +impl Integer for BigUint { + #[inline] + fn div_rem(&self, other: &BigUint) -> (BigUint, BigUint) { + div_rem_ref(self, other) + } + + #[inline] + fn div_floor(&self, other: &BigUint) -> BigUint { + let (d, _) = div_rem_ref(self, other); + d + } + + #[inline] + fn mod_floor(&self, other: &BigUint) -> BigUint { + let (_, m) = div_rem_ref(self, other); + m + } + + #[inline] + fn div_mod_floor(&self, other: &BigUint) -> (BigUint, BigUint) { + div_rem_ref(self, other) + } + + /// Calculates the Greatest Common Divisor (GCD) of the number and `other`. + /// + /// The result is always positive. + #[inline] + fn gcd(&self, other: &Self) -> Self { + #[inline] + fn twos(x: &BigUint) -> usize { + trailing_zeros(x).unwrap_or(0) + } + + // Stein's algorithm + if self.is_zero() { + return other.clone(); + } + if other.is_zero() { + return self.clone(); + } + let mut m = self.clone(); + let mut n = other.clone(); + + // find common factors of 2 + let shift = cmp::min(twos(&n), twos(&m)); + + // divide m and n by 2 until odd + // m inside loop + n >>= twos(&n); + + while !m.is_zero() { + m >>= twos(&m); + if n > m { + mem::swap(&mut n, &mut m) + } + m -= &n; + } + + n << shift + } + + /// Calculates the Lowest Common Multiple (LCM) of the number and `other`. + #[inline] + fn lcm(&self, other: &BigUint) -> BigUint { + if self.is_zero() && other.is_zero() { + Self::zero() + } else { + self / self.gcd(other) * other + } + } + + /// Deprecated, use `is_multiple_of` instead. + #[inline] + fn divides(&self, other: &BigUint) -> bool { + self.is_multiple_of(other) + } + + /// Returns `true` if the number is a multiple of `other`. + #[inline] + fn is_multiple_of(&self, other: &BigUint) -> bool { + (self % other).is_zero() + } + + /// Returns `true` if the number is divisible by `2`. + #[inline] + fn is_even(&self) -> bool { + // Considering only the last digit. + match self.data.first() { + Some(x) => x.is_even(), + None => true, + } + } + + /// Returns `true` if the number is not divisible by `2`. + #[inline] + fn is_odd(&self) -> bool { + !self.is_even() + } +} + +#[inline] +fn fixpoint<F>(mut x: BigUint, max_bits: usize, f: F) -> BigUint +where + F: Fn(&BigUint) -> BigUint, +{ + let mut xn = f(&x); + + // If the value increased, then the initial guess must have been low. + // Repeat until we reverse course. + while x < xn { + // Sometimes an increase will go way too far, especially with large + // powers, and then take a long time to walk back. We know an upper + // bound based on bit size, so saturate on that. + x = if xn.bits() > max_bits { + BigUint::one() << max_bits + } else { + xn + }; + xn = f(&x); + } + + // Now keep repeating while the estimate is decreasing. + while x > xn { + x = xn; + xn = f(&x); + } + x +} + +impl Roots for BigUint { + // nth_root, sqrt and cbrt use Newton's method to compute + // principal root of a given degree for a given integer. + + // Reference: + // Brent & Zimmermann, Modern Computer Arithmetic, v0.5.9, Algorithm 1.14 + fn nth_root(&self, n: u32) -> Self { + assert!(n > 0, "root degree n must be at least 1"); + + if self.is_zero() || self.is_one() { + return self.clone(); + } + + match n { + // Optimize for small n + 1 => return self.clone(), + 2 => return self.sqrt(), + 3 => return self.cbrt(), + _ => (), + } + + // The root of non-zero values less than 2ⁿ can only be 1. + let bits = self.bits(); + if bits <= n as usize { + return BigUint::one(); + } + + // If we fit in `u64`, compute the root that way. + if let Some(x) = self.to_u64() { + return x.nth_root(n).into(); + } + + let max_bits = bits / n as usize + 1; + + let guess = if let Some(f) = self.to_f64() { + // We fit in `f64` (lossy), so get a better initial guess from that. + BigUint::from_f64((f.ln() / f64::from(n)).exp()).unwrap() + } else { + // Try to guess by scaling down such that it does fit in `f64`. + // With some (x * 2ⁿᵏ), its nth root ≈ (ⁿ√x * 2ᵏ) + let nsz = n as usize; + let extra_bits = bits - (f64::MAX_EXP as usize - 1); + let root_scale = (extra_bits + (nsz - 1)) / nsz; + let scale = root_scale * nsz; + if scale < bits && bits - scale > nsz { + (self >> scale).nth_root(n) << root_scale + } else { + BigUint::one() << max_bits + } + }; + + let n_min_1 = n - 1; + fixpoint(guess, max_bits, move |s| { + let q = self / s.pow(n_min_1); + let t = n_min_1 * s + q; + t / n + }) + } + + // Reference: + // Brent & Zimmermann, Modern Computer Arithmetic, v0.5.9, Algorithm 1.13 + fn sqrt(&self) -> Self { + if self.is_zero() || self.is_one() { + return self.clone(); + } + + // If we fit in `u64`, compute the root that way. + if let Some(x) = self.to_u64() { + return x.sqrt().into(); + } + + let bits = self.bits(); + let max_bits = bits / 2 as usize + 1; + + let guess = if let Some(f) = self.to_f64() { + // We fit in `f64` (lossy), so get a better initial guess from that. + BigUint::from_f64(f.sqrt()).unwrap() + } else { + // Try to guess by scaling down such that it does fit in `f64`. + // With some (x * 2²ᵏ), its sqrt ≈ (√x * 2ᵏ) + let extra_bits = bits - (f64::MAX_EXP as usize - 1); + let root_scale = (extra_bits + 1) / 2; + let scale = root_scale * 2; + (self >> scale).sqrt() << root_scale + }; + + fixpoint(guess, max_bits, move |s| { + let q = self / s; + let t = s + q; + t >> 1 + }) + } + + fn cbrt(&self) -> Self { + if self.is_zero() || self.is_one() { + return self.clone(); + } + + // If we fit in `u64`, compute the root that way. + if let Some(x) = self.to_u64() { + return x.cbrt().into(); + } + + let bits = self.bits(); + let max_bits = bits / 3 as usize + 1; + + let guess = if let Some(f) = self.to_f64() { + // We fit in `f64` (lossy), so get a better initial guess from that. + BigUint::from_f64(f.cbrt()).unwrap() + } else { + // Try to guess by scaling down such that it does fit in `f64`. + // With some (x * 2³ᵏ), its cbrt ≈ (∛x * 2ᵏ) + let extra_bits = bits - (f64::MAX_EXP as usize - 1); + let root_scale = (extra_bits + 2) / 3; + let scale = root_scale * 3; + (self >> scale).cbrt() << root_scale + }; + + fixpoint(guess, max_bits, move |s| { + let q = self / (s * s); + let t = (s << 1) + q; + t / 3u32 + }) + } +} + +fn high_bits_to_u64(v: &BigUint) -> u64 { + match v.data.len() { + 0 => 0, + 1 => u64::from(v.data[0]), + _ => { + let mut bits = v.bits(); + let mut ret = 0u64; + let mut ret_bits = 0; + + for d in v.data.iter().rev() { + let digit_bits = (bits - 1) % big_digit::BITS + 1; + let bits_want = cmp::min(64 - ret_bits, digit_bits); + + if bits_want != 64 { + ret <<= bits_want; + } + ret |= u64::from(*d) >> (digit_bits - bits_want); + ret_bits += bits_want; + bits -= bits_want; + + if ret_bits == 64 { + break; + } + } + + ret + } + } +} + +impl ToPrimitive for BigUint { + #[inline] + fn to_i64(&self) -> Option<i64> { + self.to_u64().as_ref().and_then(u64::to_i64) + } + + #[inline] + #[cfg(has_i128)] + fn to_i128(&self) -> Option<i128> { + self.to_u128().as_ref().and_then(u128::to_i128) + } + + #[inline] + fn to_u64(&self) -> Option<u64> { + let mut ret: u64 = 0; + let mut bits = 0; + + for i in self.data.iter() { + if bits >= 64 { + return None; + } + + ret += u64::from(*i) << bits; + bits += big_digit::BITS; + } + + Some(ret) + } + + #[inline] + #[cfg(has_i128)] + fn to_u128(&self) -> Option<u128> { + let mut ret: u128 = 0; + let mut bits = 0; + + for i in self.data.iter() { + if bits >= 128 { + return None; + } + + ret |= u128::from(*i) << bits; + bits += big_digit::BITS; + } + + Some(ret) + } + + #[inline] + fn to_f32(&self) -> Option<f32> { + let mantissa = high_bits_to_u64(self); + let exponent = self.bits() - fls(mantissa); + + if exponent > f32::MAX_EXP as usize { + None + } else { + let ret = (mantissa as f32) * 2.0f32.powi(exponent as i32); + if ret.is_infinite() { + None + } else { + Some(ret) + } + } + } + + #[inline] + fn to_f64(&self) -> Option<f64> { + let mantissa = high_bits_to_u64(self); + let exponent = self.bits() - fls(mantissa); + + if exponent > f64::MAX_EXP as usize { + None + } else { + let ret = (mantissa as f64) * 2.0f64.powi(exponent as i32); + if ret.is_infinite() { + None + } else { + Some(ret) + } + } + } +} + +impl FromPrimitive for BigUint { + #[inline] + fn from_i64(n: i64) -> Option<BigUint> { + if n >= 0 { + Some(BigUint::from(n as u64)) + } else { + None + } + } + + #[inline] + #[cfg(has_i128)] + fn from_i128(n: i128) -> Option<BigUint> { + if n >= 0 { + Some(BigUint::from(n as u128)) + } else { + None + } + } + + #[inline] + fn from_u64(n: u64) -> Option<BigUint> { + Some(BigUint::from(n)) + } + + #[inline] + #[cfg(has_i128)] + fn from_u128(n: u128) -> Option<BigUint> { + Some(BigUint::from(n)) + } + + #[inline] + fn from_f64(mut n: f64) -> Option<BigUint> { + // handle NAN, INFINITY, NEG_INFINITY + if !n.is_finite() { + return None; + } + + // match the rounding of casting from float to int + n = n.trunc(); + + // handle 0.x, -0.x + if n.is_zero() { + return Some(BigUint::zero()); + } + + let (mantissa, exponent, sign) = Float::integer_decode(n); + + if sign == -1 { + return None; + } + + let mut ret = BigUint::from(mantissa); + if exponent > 0 { + ret = ret << exponent as usize; + } else if exponent < 0 { + ret = ret >> (-exponent) as usize; + } + Some(ret) + } +} + +impl From<u64> for BigUint { + #[inline] + fn from(mut n: u64) -> Self { + let mut ret: BigUint = Zero::zero(); + + while n != 0 { + ret.data.push(n as BigDigit); + // don't overflow if BITS is 64: + n = (n >> 1) >> (big_digit::BITS - 1); + } + + ret + } +} + +#[cfg(has_i128)] +impl From<u128> for BigUint { + #[inline] + fn from(mut n: u128) -> Self { + let mut ret: BigUint = Zero::zero(); + + while n != 0 { + ret.data.push(n as BigDigit); + n >>= big_digit::BITS; + } + + ret + } +} + +macro_rules! impl_biguint_from_uint { + ($T:ty) => { + impl From<$T> for BigUint { + #[inline] + fn from(n: $T) -> Self { + BigUint::from(n as u64) + } + } + }; +} + +impl_biguint_from_uint!(u8); +impl_biguint_from_uint!(u16); +impl_biguint_from_uint!(u32); +impl_biguint_from_uint!(usize); + +/// A generic trait for converting a value to a `BigUint`. +pub trait ToBigUint { + /// Converts the value of `self` to a `BigUint`. + fn to_biguint(&self) -> Option<BigUint>; +} + +impl ToBigUint for BigUint { + #[inline] + fn to_biguint(&self) -> Option<BigUint> { + Some(self.clone()) + } +} + +macro_rules! impl_to_biguint { + ($T:ty, $from_ty:path) => { + impl ToBigUint for $T { + #[inline] + fn to_biguint(&self) -> Option<BigUint> { + $from_ty(*self) + } + } + }; +} + +impl_to_biguint!(isize, FromPrimitive::from_isize); +impl_to_biguint!(i8, FromPrimitive::from_i8); +impl_to_biguint!(i16, FromPrimitive::from_i16); +impl_to_biguint!(i32, FromPrimitive::from_i32); +impl_to_biguint!(i64, FromPrimitive::from_i64); +#[cfg(has_i128)] +impl_to_biguint!(i128, FromPrimitive::from_i128); + +impl_to_biguint!(usize, FromPrimitive::from_usize); +impl_to_biguint!(u8, FromPrimitive::from_u8); +impl_to_biguint!(u16, FromPrimitive::from_u16); +impl_to_biguint!(u32, FromPrimitive::from_u32); +impl_to_biguint!(u64, FromPrimitive::from_u64); +#[cfg(has_i128)] +impl_to_biguint!(u128, FromPrimitive::from_u128); + +impl_to_biguint!(f32, FromPrimitive::from_f32); +impl_to_biguint!(f64, FromPrimitive::from_f64); + +// Extract bitwise digits that evenly divide BigDigit +fn to_bitwise_digits_le(u: &BigUint, bits: usize) -> Vec<u8> { + debug_assert!(!u.is_zero() && bits <= 8 && big_digit::BITS % bits == 0); + + let last_i = u.data.len() - 1; + let mask: BigDigit = (1 << bits) - 1; + let digits_per_big_digit = big_digit::BITS / bits; + let digits = (u.bits() + bits - 1) / bits; + let mut res = Vec::with_capacity(digits); + + for mut r in u.data[..last_i].iter().cloned() { + for _ in 0..digits_per_big_digit { + res.push((r & mask) as u8); + r >>= bits; + } + } + + let mut r = u.data[last_i]; + while r != 0 { + res.push((r & mask) as u8); + r >>= bits; + } + + res +} + +// Extract bitwise digits that don't evenly divide BigDigit +fn to_inexact_bitwise_digits_le(u: &BigUint, bits: usize) -> Vec<u8> { + debug_assert!(!u.is_zero() && bits <= 8 && big_digit::BITS % bits != 0); + + let mask: BigDigit = (1 << bits) - 1; + let digits = (u.bits() + bits - 1) / bits; + let mut res = Vec::with_capacity(digits); + + let mut r = 0; + let mut rbits = 0; + + for c in &u.data { + r |= *c << rbits; + rbits += big_digit::BITS; + + while rbits >= bits { + res.push((r & mask) as u8); + r >>= bits; + + // r had more bits than it could fit - grab the bits we lost + if rbits > big_digit::BITS { + r = *c >> (big_digit::BITS - (rbits - bits)); + } + + rbits -= bits; + } + } + + if rbits != 0 { + res.push(r as u8); + } + + while let Some(&0) = res.last() { + res.pop(); + } + + res +} + +// Extract little-endian radix digits +#[inline(always)] // forced inline to get const-prop for radix=10 +fn to_radix_digits_le(u: &BigUint, radix: u32) -> Vec<u8> { + debug_assert!(!u.is_zero() && !radix.is_power_of_two()); + + // Estimate how big the result will be, so we can pre-allocate it. + let radix_digits = ((u.bits() as f64) / f64::from(radix).log2()).ceil(); + let mut res = Vec::with_capacity(radix_digits as usize); + let mut digits = u.clone(); + + let (base, power) = get_radix_base(radix); + let radix = radix as BigDigit; + + while digits.data.len() > 1 { + let (q, mut r) = div_rem_digit(digits, base); + for _ in 0..power { + res.push((r % radix) as u8); + r /= radix; + } + digits = q; + } + + let mut r = digits.data[0]; + while r != 0 { + res.push((r % radix) as u8); + r /= radix; + } + + res +} + +pub fn to_radix_le(u: &BigUint, radix: u32) -> Vec<u8> { + if u.is_zero() { + vec![0] + } else if radix.is_power_of_two() { + // Powers of two can use bitwise masks and shifting instead of division + let bits = ilog2(radix); + if big_digit::BITS % bits == 0 { + to_bitwise_digits_le(u, bits) + } else { + to_inexact_bitwise_digits_le(u, bits) + } + } else if radix == 10 { + // 10 is so common that it's worth separating out for const-propagation. + // Optimizers can often turn constant division into a faster multiplication. + to_radix_digits_le(u, 10) + } else { + to_radix_digits_le(u, radix) + } +} + +pub fn to_str_radix_reversed(u: &BigUint, radix: u32) -> Vec<u8> { + assert!(2 <= radix && radix <= 36, "The radix must be within 2...36"); + + if u.is_zero() { + return vec![b'0']; + } + + let mut res = to_radix_le(u, radix); + + // Now convert everything to ASCII digits. + for r in &mut res { + debug_assert!(u32::from(*r) < radix); + if *r < 10 { + *r += b'0'; + } else { + *r += b'a' - 10; + } + } + res +} + +impl BigUint { + /// Creates and initializes a `BigUint`. + /// + /// The digits are in little-endian base 2<sup>32</sup>. + #[inline] + pub fn new(digits: Vec<u32>) -> BigUint { + BigUint { data: digits }.normalized() + } + + /// Creates and initializes a `BigUint`. + /// + /// The digits are in little-endian base 2<sup>32</sup>. + #[inline] + pub fn from_slice(slice: &[u32]) -> BigUint { + BigUint::new(slice.to_vec()) + } + + /// Assign a value to a `BigUint`. + /// + /// The digits are in little-endian base 2<sup>32</sup>. + #[inline] + pub fn assign_from_slice(&mut self, slice: &[u32]) { + self.data.resize(slice.len(), 0); + self.data.clone_from_slice(slice); + self.normalize(); + } + + /// Creates and initializes a `BigUint`. + /// + /// The bytes are in big-endian byte order. + /// + /// # Examples + /// + /// ``` + /// use num_bigint::BigUint; + /// + /// assert_eq!(BigUint::from_bytes_be(b"A"), + /// BigUint::parse_bytes(b"65", 10).unwrap()); + /// assert_eq!(BigUint::from_bytes_be(b"AA"), + /// BigUint::parse_bytes(b"16705", 10).unwrap()); + /// assert_eq!(BigUint::from_bytes_be(b"AB"), + /// BigUint::parse_bytes(b"16706", 10).unwrap()); + /// assert_eq!(BigUint::from_bytes_be(b"Hello world!"), + /// BigUint::parse_bytes(b"22405534230753963835153736737", 10).unwrap()); + /// ``` + #[inline] + pub fn from_bytes_be(bytes: &[u8]) -> BigUint { + if bytes.is_empty() { + Zero::zero() + } else { + let mut v = bytes.to_vec(); + v.reverse(); + BigUint::from_bytes_le(&*v) + } + } + + /// Creates and initializes a `BigUint`. + /// + /// The bytes are in little-endian byte order. + #[inline] + pub fn from_bytes_le(bytes: &[u8]) -> BigUint { + if bytes.is_empty() { + Zero::zero() + } else { + from_bitwise_digits_le(bytes, 8) + } + } + + /// Creates and initializes a `BigUint`. The input slice must contain + /// ascii/utf8 characters in [0-9a-zA-Z]. + /// `radix` must be in the range `2...36`. + /// + /// The function `from_str_radix` from the `Num` trait provides the same logic + /// for `&str` buffers. + /// + /// # Examples + /// + /// ``` + /// use num_bigint::{BigUint, ToBigUint}; + /// + /// assert_eq!(BigUint::parse_bytes(b"1234", 10), ToBigUint::to_biguint(&1234)); + /// assert_eq!(BigUint::parse_bytes(b"ABCD", 16), ToBigUint::to_biguint(&0xABCD)); + /// assert_eq!(BigUint::parse_bytes(b"G", 16), None); + /// ``` + #[inline] + pub fn parse_bytes(buf: &[u8], radix: u32) -> Option<BigUint> { + str::from_utf8(buf) + .ok() + .and_then(|s| BigUint::from_str_radix(s, radix).ok()) + } + + /// Creates and initializes a `BigUint`. Each u8 of the input slice is + /// interpreted as one digit of the number + /// and must therefore be less than `radix`. + /// + /// The bytes are in big-endian byte order. + /// `radix` must be in the range `2...256`. + /// + /// # Examples + /// + /// ``` + /// use num_bigint::{BigUint}; + /// + /// let inbase190 = &[15, 33, 125, 12, 14]; + /// let a = BigUint::from_radix_be(inbase190, 190).unwrap(); + /// assert_eq!(a.to_radix_be(190), inbase190); + /// ``` + pub fn from_radix_be(buf: &[u8], radix: u32) -> Option<BigUint> { + assert!( + 2 <= radix && radix <= 256, + "The radix must be within 2...256" + ); + + if radix != 256 && buf.iter().any(|&b| b >= radix as u8) { + return None; + } + + let res = if radix.is_power_of_two() { + // Powers of two can use bitwise masks and shifting instead of multiplication + let bits = ilog2(radix); + let mut v = Vec::from(buf); + v.reverse(); + if big_digit::BITS % bits == 0 { + from_bitwise_digits_le(&v, bits) + } else { + from_inexact_bitwise_digits_le(&v, bits) + } + } else { + from_radix_digits_be(buf, radix) + }; + + Some(res) + } + + /// Creates and initializes a `BigUint`. Each u8 of the input slice is + /// interpreted as one digit of the number + /// and must therefore be less than `radix`. + /// + /// The bytes are in little-endian byte order. + /// `radix` must be in the range `2...256`. + /// + /// # Examples + /// + /// ``` + /// use num_bigint::{BigUint}; + /// + /// let inbase190 = &[14, 12, 125, 33, 15]; + /// let a = BigUint::from_radix_be(inbase190, 190).unwrap(); + /// assert_eq!(a.to_radix_be(190), inbase190); + /// ``` + pub fn from_radix_le(buf: &[u8], radix: u32) -> Option<BigUint> { + assert!( + 2 <= radix && radix <= 256, + "The radix must be within 2...256" + ); + + if radix != 256 && buf.iter().any(|&b| b >= radix as u8) { + return None; + } + + let res = if radix.is_power_of_two() { + // Powers of two can use bitwise masks and shifting instead of multiplication + let bits = ilog2(radix); + if big_digit::BITS % bits == 0 { + from_bitwise_digits_le(buf, bits) + } else { + from_inexact_bitwise_digits_le(buf, bits) + } + } else { + let mut v = Vec::from(buf); + v.reverse(); + from_radix_digits_be(&v, radix) + }; + + Some(res) + } + + /// Returns the byte representation of the `BigUint` in big-endian byte order. + /// + /// # Examples + /// + /// ``` + /// use num_bigint::BigUint; + /// + /// let i = BigUint::parse_bytes(b"1125", 10).unwrap(); + /// assert_eq!(i.to_bytes_be(), vec![4, 101]); + /// ``` + #[inline] + pub fn to_bytes_be(&self) -> Vec<u8> { + let mut v = self.to_bytes_le(); + v.reverse(); + v + } + + /// Returns the byte representation of the `BigUint` in little-endian byte order. + /// + /// # Examples + /// + /// ``` + /// use num_bigint::BigUint; + /// + /// let i = BigUint::parse_bytes(b"1125", 10).unwrap(); + /// assert_eq!(i.to_bytes_le(), vec![101, 4]); + /// ``` + #[inline] + pub fn to_bytes_le(&self) -> Vec<u8> { + if self.is_zero() { + vec![0] + } else { + to_bitwise_digits_le(self, 8) + } + } + + /// Returns the integer formatted as a string in the given radix. + /// `radix` must be in the range `2...36`. + /// + /// # Examples + /// + /// ``` + /// use num_bigint::BigUint; + /// + /// let i = BigUint::parse_bytes(b"ff", 16).unwrap(); + /// assert_eq!(i.to_str_radix(16), "ff"); + /// ``` + #[inline] + pub fn to_str_radix(&self, radix: u32) -> String { + let mut v = to_str_radix_reversed(self, radix); + v.reverse(); + unsafe { String::from_utf8_unchecked(v) } + } + + /// Returns the integer in the requested base in big-endian digit order. + /// The output is not given in a human readable alphabet but as a zero + /// based u8 number. + /// `radix` must be in the range `2...256`. + /// + /// # Examples + /// + /// ``` + /// use num_bigint::BigUint; + /// + /// assert_eq!(BigUint::from(0xFFFFu64).to_radix_be(159), + /// vec![2, 94, 27]); + /// // 0xFFFF = 65535 = 2*(159^2) + 94*159 + 27 + /// ``` + #[inline] + pub fn to_radix_be(&self, radix: u32) -> Vec<u8> { + let mut v = to_radix_le(self, radix); + v.reverse(); + v + } + + /// Returns the integer in the requested base in little-endian digit order. + /// The output is not given in a human readable alphabet but as a zero + /// based u8 number. + /// `radix` must be in the range `2...256`. + /// + /// # Examples + /// + /// ``` + /// use num_bigint::BigUint; + /// + /// assert_eq!(BigUint::from(0xFFFFu64).to_radix_le(159), + /// vec![27, 94, 2]); + /// // 0xFFFF = 65535 = 27 + 94*159 + 2*(159^2) + /// ``` + #[inline] + pub fn to_radix_le(&self, radix: u32) -> Vec<u8> { + to_radix_le(self, radix) + } + + /// Determines the fewest bits necessary to express the `BigUint`. + #[inline] + pub fn bits(&self) -> usize { + if self.is_zero() { + return 0; + } + let zeros = self.data.last().unwrap().leading_zeros(); + return self.data.len() * big_digit::BITS - zeros as usize; + } + + /// Strips off trailing zero bigdigits - comparisons require the last element in the vector to + /// be nonzero. + #[inline] + fn normalize(&mut self) { + while let Some(&0) = self.data.last() { + self.data.pop(); + } + } + + /// Returns a normalized `BigUint`. + #[inline] + fn normalized(mut self) -> BigUint { + self.normalize(); + self + } + + /// Returns `(self ^ exponent) % modulus`. + /// + /// Panics if the modulus is zero. + pub fn modpow(&self, exponent: &Self, modulus: &Self) -> Self { + assert!(!modulus.is_zero(), "divide by zero!"); + + if modulus.is_odd() { + // For an odd modulus, we can use Montgomery multiplication in base 2^32. + monty_modpow(self, exponent, modulus) + } else { + // Otherwise do basically the same as `num::pow`, but with a modulus. + plain_modpow(self, &exponent.data, modulus) + } + } + + /// Returns the truncated principal square root of `self` -- + /// see [Roots::sqrt](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#method.sqrt) + pub fn sqrt(&self) -> Self { + Roots::sqrt(self) + } + + /// Returns the truncated principal cube root of `self` -- + /// see [Roots::cbrt](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#method.cbrt). + pub fn cbrt(&self) -> Self { + Roots::cbrt(self) + } + + /// Returns the truncated principal `n`th root of `self` -- + /// see [Roots::nth_root](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#tymethod.nth_root). + pub fn nth_root(&self, n: u32) -> Self { + Roots::nth_root(self, n) + } +} + +fn plain_modpow(base: &BigUint, exp_data: &[BigDigit], modulus: &BigUint) -> BigUint { + assert!(!modulus.is_zero(), "divide by zero!"); + + let i = match exp_data.iter().position(|&r| r != 0) { + None => return BigUint::one(), + Some(i) => i, + }; + + let mut base = base.clone(); + for _ in 0..i { + for _ in 0..big_digit::BITS { + base = &base * &base % modulus; + } + } + + let mut r = exp_data[i]; + let mut b = 0usize; + while r.is_even() { + base = &base * &base % modulus; + r >>= 1; + b += 1; + } + + let mut exp_iter = exp_data[i + 1..].iter(); + if exp_iter.len() == 0 && r.is_one() { + return base; + } + + let mut acc = base.clone(); + r >>= 1; + b += 1; + + { + let mut unit = |exp_is_odd| { + base = &base * &base % modulus; + if exp_is_odd { + acc = &acc * &base % modulus; + } + }; + + if let Some(&last) = exp_iter.next_back() { + // consume exp_data[i] + for _ in b..big_digit::BITS { + unit(r.is_odd()); + r >>= 1; + } + + // consume all other digits before the last + for &r in exp_iter { + let mut r = r; + for _ in 0..big_digit::BITS { + unit(r.is_odd()); + r >>= 1; + } + } + r = last; + } + + debug_assert_ne!(r, 0); + while !r.is_zero() { + unit(r.is_odd()); + r >>= 1; + } + } + acc +} + +#[test] +fn test_plain_modpow() { + let two = BigUint::from(2u32); + let modulus = BigUint::from(0x1100u32); + + let exp = vec![0, 0b1]; + assert_eq!( + two.pow(0b1_00000000_u32) % &modulus, + plain_modpow(&two, &exp, &modulus) + ); + let exp = vec![0, 0b10]; + assert_eq!( + two.pow(0b10_00000000_u32) % &modulus, + plain_modpow(&two, &exp, &modulus) + ); + let exp = vec![0, 0b110010]; + assert_eq!( + two.pow(0b110010_00000000_u32) % &modulus, + plain_modpow(&two, &exp, &modulus) + ); + let exp = vec![0b1, 0b1]; + assert_eq!( + two.pow(0b1_00000001_u32) % &modulus, + plain_modpow(&two, &exp, &modulus) + ); + let exp = vec![0b1100, 0, 0b1]; + assert_eq!( + two.pow(0b1_00000000_00001100_u32) % &modulus, + plain_modpow(&two, &exp, &modulus) + ); +} + +/// Returns the number of least-significant bits that are zero, +/// or `None` if the entire number is zero. +pub fn trailing_zeros(u: &BigUint) -> Option<usize> { + u.data + .iter() + .enumerate() + .find(|&(_, &digit)| digit != 0) + .map(|(i, digit)| i * big_digit::BITS + digit.trailing_zeros() as usize) +} + +impl_sum_iter_type!(BigUint); +impl_product_iter_type!(BigUint); + +pub trait IntDigits { + fn digits(&self) -> &[BigDigit]; + fn digits_mut(&mut self) -> &mut Vec<BigDigit>; + fn normalize(&mut self); + fn capacity(&self) -> usize; + fn len(&self) -> usize; +} + +impl IntDigits for BigUint { + #[inline] + fn digits(&self) -> &[BigDigit] { + &self.data + } + #[inline] + fn digits_mut(&mut self) -> &mut Vec<BigDigit> { + &mut self.data + } + #[inline] + fn normalize(&mut self) { + self.normalize(); + } + #[inline] + fn capacity(&self) -> usize { + self.data.capacity() + } + #[inline] + fn len(&self) -> usize { + self.data.len() + } +} + +/// Combine four `u32`s into a single `u128`. +#[cfg(has_i128)] +#[inline] +fn u32_to_u128(a: u32, b: u32, c: u32, d: u32) -> u128 { + u128::from(d) | (u128::from(c) << 32) | (u128::from(b) << 64) | (u128::from(a) << 96) +} + +/// Split a single `u128` into four `u32`. +#[cfg(has_i128)] +#[inline] +fn u32_from_u128(n: u128) -> (u32, u32, u32, u32) { + ( + (n >> 96) as u32, + (n >> 64) as u32, + (n >> 32) as u32, + n as u32, + ) +} + +#[cfg(feature = "serde")] +impl serde::Serialize for BigUint { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: serde::Serializer, + { + // Note: do not change the serialization format, or it may break forward + // and backward compatibility of serialized data! If we ever change the + // internal representation, we should still serialize in base-`u32`. + let data: &Vec<u32> = &self.data; + data.serialize(serializer) + } +} + +#[cfg(feature = "serde")] +impl<'de> serde::Deserialize<'de> for BigUint { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: serde::Deserializer<'de>, + { + let data: Vec<u32> = Vec::deserialize(deserializer)?; + Ok(BigUint::new(data)) + } +} + +/// Returns the greatest power of the radix <= big_digit::BASE +#[inline] +fn get_radix_base(radix: u32) -> (BigDigit, usize) { + debug_assert!( + 2 <= radix && radix <= 256, + "The radix must be within 2...256" + ); + debug_assert!(!radix.is_power_of_two()); + + // To generate this table: + // for radix in 2u64..257 { + // let mut power = big_digit::BITS / fls(radix as u64); + // let mut base = radix.pow(power as u32); + // + // while let Some(b) = base.checked_mul(radix) { + // if b > big_digit::MAX { + // break; + // } + // base = b; + // power += 1; + // } + // + // println!("({:10}, {:2}), // {:2}", base, power, radix); + // } + // and + // for radix in 2u64..257 { + // let mut power = 64 / fls(radix as u64); + // let mut base = radix.pow(power as u32); + // + // while let Some(b) = base.checked_mul(radix) { + // base = b; + // power += 1; + // } + // + // println!("({:20}, {:2}), // {:2}", base, power, radix); + // } + match big_digit::BITS { + 32 => { + const BASES: [(u32, usize); 257] = [ + (0, 0), + (0, 0), + (0, 0), // 2 + (3486784401, 20), // 3 + (0, 0), // 4 + (1220703125, 13), // 5 + (2176782336, 12), // 6 + (1977326743, 11), // 7 + (0, 0), // 8 + (3486784401, 10), // 9 + (1000000000, 9), // 10 + (2357947691, 9), // 11 + (429981696, 8), // 12 + (815730721, 8), // 13 + (1475789056, 8), // 14 + (2562890625, 8), // 15 + (0, 0), // 16 + (410338673, 7), // 17 + (612220032, 7), // 18 + (893871739, 7), // 19 + (1280000000, 7), // 20 + (1801088541, 7), // 21 + (2494357888, 7), // 22 + (3404825447, 7), // 23 + (191102976, 6), // 24 + (244140625, 6), // 25 + (308915776, 6), // 26 + (387420489, 6), // 27 + (481890304, 6), // 28 + (594823321, 6), // 29 + (729000000, 6), // 30 + (887503681, 6), // 31 + (0, 0), // 32 + (1291467969, 6), // 33 + (1544804416, 6), // 34 + (1838265625, 6), // 35 + (2176782336, 6), // 36 + (2565726409, 6), // 37 + (3010936384, 6), // 38 + (3518743761, 6), // 39 + (4096000000, 6), // 40 + (115856201, 5), // 41 + (130691232, 5), // 42 + (147008443, 5), // 43 + (164916224, 5), // 44 + (184528125, 5), // 45 + (205962976, 5), // 46 + (229345007, 5), // 47 + (254803968, 5), // 48 + (282475249, 5), // 49 + (312500000, 5), // 50 + (345025251, 5), // 51 + (380204032, 5), // 52 + (418195493, 5), // 53 + (459165024, 5), // 54 + (503284375, 5), // 55 + (550731776, 5), // 56 + (601692057, 5), // 57 + (656356768, 5), // 58 + (714924299, 5), // 59 + (777600000, 5), // 60 + (844596301, 5), // 61 + (916132832, 5), // 62 + (992436543, 5), // 63 + (0, 0), // 64 + (1160290625, 5), // 65 + (1252332576, 5), // 66 + (1350125107, 5), // 67 + (1453933568, 5), // 68 + (1564031349, 5), // 69 + (1680700000, 5), // 70 + (1804229351, 5), // 71 + (1934917632, 5), // 72 + (2073071593, 5), // 73 + (2219006624, 5), // 74 + (2373046875, 5), // 75 + (2535525376, 5), // 76 + (2706784157, 5), // 77 + (2887174368, 5), // 78 + (3077056399, 5), // 79 + (3276800000, 5), // 80 + (3486784401, 5), // 81 + (3707398432, 5), // 82 + (3939040643, 5), // 83 + (4182119424, 5), // 84 + (52200625, 4), // 85 + (54700816, 4), // 86 + (57289761, 4), // 87 + (59969536, 4), // 88 + (62742241, 4), // 89 + (65610000, 4), // 90 + (68574961, 4), // 91 + (71639296, 4), // 92 + (74805201, 4), // 93 + (78074896, 4), // 94 + (81450625, 4), // 95 + (84934656, 4), // 96 + (88529281, 4), // 97 + (92236816, 4), // 98 + (96059601, 4), // 99 + (100000000, 4), // 100 + (104060401, 4), // 101 + (108243216, 4), // 102 + (112550881, 4), // 103 + (116985856, 4), // 104 + (121550625, 4), // 105 + (126247696, 4), // 106 + (131079601, 4), // 107 + (136048896, 4), // 108 + (141158161, 4), // 109 + (146410000, 4), // 110 + (151807041, 4), // 111 + (157351936, 4), // 112 + (163047361, 4), // 113 + (168896016, 4), // 114 + (174900625, 4), // 115 + (181063936, 4), // 116 + (187388721, 4), // 117 + (193877776, 4), // 118 + (200533921, 4), // 119 + (207360000, 4), // 120 + (214358881, 4), // 121 + (221533456, 4), // 122 + (228886641, 4), // 123 + (236421376, 4), // 124 + (244140625, 4), // 125 + (252047376, 4), // 126 + (260144641, 4), // 127 + (0, 0), // 128 + (276922881, 4), // 129 + (285610000, 4), // 130 + (294499921, 4), // 131 + (303595776, 4), // 132 + (312900721, 4), // 133 + (322417936, 4), // 134 + (332150625, 4), // 135 + (342102016, 4), // 136 + (352275361, 4), // 137 + (362673936, 4), // 138 + (373301041, 4), // 139 + (384160000, 4), // 140 + (395254161, 4), // 141 + (406586896, 4), // 142 + (418161601, 4), // 143 + (429981696, 4), // 144 + (442050625, 4), // 145 + (454371856, 4), // 146 + (466948881, 4), // 147 + (479785216, 4), // 148 + (492884401, 4), // 149 + (506250000, 4), // 150 + (519885601, 4), // 151 + (533794816, 4), // 152 + (547981281, 4), // 153 + (562448656, 4), // 154 + (577200625, 4), // 155 + (592240896, 4), // 156 + (607573201, 4), // 157 + (623201296, 4), // 158 + (639128961, 4), // 159 + (655360000, 4), // 160 + (671898241, 4), // 161 + (688747536, 4), // 162 + (705911761, 4), // 163 + (723394816, 4), // 164 + (741200625, 4), // 165 + (759333136, 4), // 166 + (777796321, 4), // 167 + (796594176, 4), // 168 + (815730721, 4), // 169 + (835210000, 4), // 170 + (855036081, 4), // 171 + (875213056, 4), // 172 + (895745041, 4), // 173 + (916636176, 4), // 174 + (937890625, 4), // 175 + (959512576, 4), // 176 + (981506241, 4), // 177 + (1003875856, 4), // 178 + (1026625681, 4), // 179 + (1049760000, 4), // 180 + (1073283121, 4), // 181 + (1097199376, 4), // 182 + (1121513121, 4), // 183 + (1146228736, 4), // 184 + (1171350625, 4), // 185 + (1196883216, 4), // 186 + (1222830961, 4), // 187 + (1249198336, 4), // 188 + (1275989841, 4), // 189 + (1303210000, 4), // 190 + (1330863361, 4), // 191 + (1358954496, 4), // 192 + (1387488001, 4), // 193 + (1416468496, 4), // 194 + (1445900625, 4), // 195 + (1475789056, 4), // 196 + (1506138481, 4), // 197 + (1536953616, 4), // 198 + (1568239201, 4), // 199 + (1600000000, 4), // 200 + (1632240801, 4), // 201 + (1664966416, 4), // 202 + (1698181681, 4), // 203 + (1731891456, 4), // 204 + (1766100625, 4), // 205 + (1800814096, 4), // 206 + (1836036801, 4), // 207 + (1871773696, 4), // 208 + (1908029761, 4), // 209 + (1944810000, 4), // 210 + (1982119441, 4), // 211 + (2019963136, 4), // 212 + (2058346161, 4), // 213 + (2097273616, 4), // 214 + (2136750625, 4), // 215 + (2176782336, 4), // 216 + (2217373921, 4), // 217 + (2258530576, 4), // 218 + (2300257521, 4), // 219 + (2342560000, 4), // 220 + (2385443281, 4), // 221 + (2428912656, 4), // 222 + (2472973441, 4), // 223 + (2517630976, 4), // 224 + (2562890625, 4), // 225 + (2608757776, 4), // 226 + (2655237841, 4), // 227 + (2702336256, 4), // 228 + (2750058481, 4), // 229 + (2798410000, 4), // 230 + (2847396321, 4), // 231 + (2897022976, 4), // 232 + (2947295521, 4), // 233 + (2998219536, 4), // 234 + (3049800625, 4), // 235 + (3102044416, 4), // 236 + (3154956561, 4), // 237 + (3208542736, 4), // 238 + (3262808641, 4), // 239 + (3317760000, 4), // 240 + (3373402561, 4), // 241 + (3429742096, 4), // 242 + (3486784401, 4), // 243 + (3544535296, 4), // 244 + (3603000625, 4), // 245 + (3662186256, 4), // 246 + (3722098081, 4), // 247 + (3782742016, 4), // 248 + (3844124001, 4), // 249 + (3906250000, 4), // 250 + (3969126001, 4), // 251 + (4032758016, 4), // 252 + (4097152081, 4), // 253 + (4162314256, 4), // 254 + (4228250625, 4), // 255 + (0, 0), // 256 + ]; + + let (base, power) = BASES[radix as usize]; + (base as BigDigit, power) + } + 64 => { + const BASES: [(u64, usize); 257] = [ + (0, 0), + (0, 0), + (9223372036854775808, 63), // 2 + (12157665459056928801, 40), // 3 + (4611686018427387904, 31), // 4 + (7450580596923828125, 27), // 5 + (4738381338321616896, 24), // 6 + (3909821048582988049, 22), // 7 + (9223372036854775808, 21), // 8 + (12157665459056928801, 20), // 9 + (10000000000000000000, 19), // 10 + (5559917313492231481, 18), // 11 + (2218611106740436992, 17), // 12 + (8650415919381337933, 17), // 13 + (2177953337809371136, 16), // 14 + (6568408355712890625, 16), // 15 + (1152921504606846976, 15), // 16 + (2862423051509815793, 15), // 17 + (6746640616477458432, 15), // 18 + (15181127029874798299, 15), // 19 + (1638400000000000000, 14), // 20 + (3243919932521508681, 14), // 21 + (6221821273427820544, 14), // 22 + (11592836324538749809, 14), // 23 + (876488338465357824, 13), // 24 + (1490116119384765625, 13), // 25 + (2481152873203736576, 13), // 26 + (4052555153018976267, 13), // 27 + (6502111422497947648, 13), // 28 + (10260628712958602189, 13), // 29 + (15943230000000000000, 13), // 30 + (787662783788549761, 12), // 31 + (1152921504606846976, 12), // 32 + (1667889514952984961, 12), // 33 + (2386420683693101056, 12), // 34 + (3379220508056640625, 12), // 35 + (4738381338321616896, 12), // 36 + (6582952005840035281, 12), // 37 + (9065737908494995456, 12), // 38 + (12381557655576425121, 12), // 39 + (16777216000000000000, 12), // 40 + (550329031716248441, 11), // 41 + (717368321110468608, 11), // 42 + (929293739471222707, 11), // 43 + (1196683881290399744, 11), // 44 + (1532278301220703125, 11), // 45 + (1951354384207722496, 11), // 46 + (2472159215084012303, 11), // 47 + (3116402981210161152, 11), // 48 + (3909821048582988049, 11), // 49 + (4882812500000000000, 11), // 50 + (6071163615208263051, 11), // 51 + (7516865509350965248, 11), // 52 + (9269035929372191597, 11), // 53 + (11384956040305711104, 11), // 54 + (13931233916552734375, 11), // 55 + (16985107389382393856, 11), // 56 + (362033331456891249, 10), // 57 + (430804206899405824, 10), // 58 + (511116753300641401, 10), // 59 + (604661760000000000, 10), // 60 + (713342911662882601, 10), // 61 + (839299365868340224, 10), // 62 + (984930291881790849, 10), // 63 + (1152921504606846976, 10), // 64 + (1346274334462890625, 10), // 65 + (1568336880910795776, 10), // 66 + (1822837804551761449, 10), // 67 + (2113922820157210624, 10), // 68 + (2446194060654759801, 10), // 69 + (2824752490000000000, 10), // 70 + (3255243551009881201, 10), // 71 + (3743906242624487424, 10), // 72 + (4297625829703557649, 10), // 73 + (4923990397355877376, 10), // 74 + (5631351470947265625, 10), // 75 + (6428888932339941376, 10), // 76 + (7326680472586200649, 10), // 77 + (8335775831236199424, 10), // 78 + (9468276082626847201, 10), // 79 + (10737418240000000000, 10), // 80 + (12157665459056928801, 10), // 81 + (13744803133596058624, 10), // 82 + (15516041187205853449, 10), // 83 + (17490122876598091776, 10), // 84 + (231616946283203125, 9), // 85 + (257327417311663616, 9), // 86 + (285544154243029527, 9), // 87 + (316478381828866048, 9), // 88 + (350356403707485209, 9), // 89 + (387420489000000000, 9), // 90 + (427929800129788411, 9), // 91 + (472161363286556672, 9), // 92 + (520411082988487293, 9), // 93 + (572994802228616704, 9), // 94 + (630249409724609375, 9), // 95 + (692533995824480256, 9), // 96 + (760231058654565217, 9), // 97 + (833747762130149888, 9), // 98 + (913517247483640899, 9), // 99 + (1000000000000000000, 9), // 100 + (1093685272684360901, 9), // 101 + (1195092568622310912, 9), // 102 + (1304773183829244583, 9), // 103 + (1423311812421484544, 9), // 104 + (1551328215978515625, 9), // 105 + (1689478959002692096, 9), // 106 + (1838459212420154507, 9), // 107 + (1999004627104432128, 9), // 108 + (2171893279442309389, 9), // 109 + (2357947691000000000, 9), // 110 + (2558036924386500591, 9), // 111 + (2773078757450186752, 9), // 112 + (3004041937984268273, 9), // 113 + (3251948521156637184, 9), // 114 + (3517876291919921875, 9), // 115 + (3802961274698203136, 9), // 116 + (4108400332687853397, 9), // 117 + (4435453859151328768, 9), // 118 + (4785448563124474679, 9), // 119 + (5159780352000000000, 9), // 120 + (5559917313492231481, 9), // 121 + (5987402799531080192, 9), // 122 + (6443858614676334363, 9), // 123 + (6930988311686938624, 9), // 124 + (7450580596923828125, 9), // 125 + (8004512848309157376, 9), // 126 + (8594754748609397887, 9), // 127 + (9223372036854775808, 9), // 128 + (9892530380752880769, 9), // 129 + (10604499373000000000, 9), // 130 + (11361656654439817571, 9), // 131 + (12166492167065567232, 9), // 132 + (13021612539908538853, 9), // 133 + (13929745610903012864, 9), // 134 + (14893745087865234375, 9), // 135 + (15916595351771938816, 9), // 136 + (17001416405572203977, 9), // 137 + (18151468971815029248, 9), // 138 + (139353667211683681, 8), // 139 + (147578905600000000, 8), // 140 + (156225851787813921, 8), // 141 + (165312903998914816, 8), // 142 + (174859124550883201, 8), // 143 + (184884258895036416, 8), // 144 + (195408755062890625, 8), // 145 + (206453783524884736, 8), // 146 + (218041257467152161, 8), // 147 + (230193853492166656, 8), // 148 + (242935032749128801, 8), // 149 + (256289062500000000, 8), // 150 + (270281038127131201, 8), // 151 + (284936905588473856, 8), // 152 + (300283484326400961, 8), // 153 + (316348490636206336, 8), // 154 + (333160561500390625, 8), // 155 + (350749278894882816, 8), // 156 + (369145194573386401, 8), // 157 + (388379855336079616, 8), // 158 + (408485828788939521, 8), // 159 + (429496729600000000, 8), // 160 + (451447246258894081, 8), // 161 + (474373168346071296, 8), // 162 + (498311414318121121, 8), // 163 + (523300059815673856, 8), // 164 + (549378366500390625, 8), // 165 + (576586811427594496, 8), // 166 + (604967116961135041, 8), // 167 + (634562281237118976, 8), // 168 + (665416609183179841, 8), // 169 + (697575744100000000, 8), // 170 + (731086699811838561, 8), // 171 + (765997893392859136, 8), // 172 + (802359178476091681, 8), // 173 + (840221879151902976, 8), // 174 + (879638824462890625, 8), // 175 + (920664383502155776, 8), // 176 + (963354501121950081, 8), // 177 + (1007766734259732736, 8), // 178 + (1053960288888713761, 8), // 179 + (1101996057600000000, 8), // 180 + (1151936657823500641, 8), // 181 + (1203846470694789376, 8), // 182 + (1257791680575160641, 8), // 183 + (1313840315232157696, 8), // 184 + (1372062286687890625, 8), // 185 + (1432529432742502656, 8), // 186 + (1495315559180183521, 8), // 187 + (1560496482665168896, 8), // 188 + (1628150074335205281, 8), // 189 + (1698356304100000000, 8), // 190 + (1771197285652216321, 8), // 191 + (1846757322198614016, 8), // 192 + (1925122952918976001, 8), // 193 + (2006383000160502016, 8), // 194 + (2090628617375390625, 8), // 195 + (2177953337809371136, 8), // 196 + (2268453123948987361, 8), // 197 + (2362226417735475456, 8), // 198 + (2459374191553118401, 8), // 199 + (2560000000000000000, 8), // 200 + (2664210032449121601, 8), // 201 + (2772113166407885056, 8), // 202 + (2883821021683985761, 8), // 203 + (2999448015365799936, 8), // 204 + (3119111417625390625, 8), // 205 + (3242931408352297216, 8), // 206 + (3371031134626313601, 8), // 207 + (3503536769037500416, 8), // 208 + (3640577568861717121, 8), // 209 + (3782285936100000000, 8), // 210 + (3928797478390152481, 8), // 211 + (4080251070798954496, 8), // 212 + (4236788918503437921, 8), // 213 + (4398556620369715456, 8), // 214 + (4565703233437890625, 8), // 215 + (4738381338321616896, 8), // 216 + (4916747105530914241, 8), // 217 + (5100960362726891776, 8), // 218 + (5291184662917065441, 8), // 219 + (5487587353600000000, 8), // 220 + (5690339646868044961, 8), // 221 + (5899616690476974336, 8), // 222 + (6115597639891380481, 8), // 223 + (6338465731314712576, 8), // 224 + (6568408355712890625, 8), // 225 + (6805617133840466176, 8), // 226 + (7050287992278341281, 8), // 227 + (7302621240492097536, 8), // 228 + (7562821648920027361, 8), // 229 + (7831098528100000000, 8), // 230 + (8107665808844335041, 8), // 231 + (8392742123471896576, 8), // 232 + (8686550888106661441, 8), // 233 + (8989320386052055296, 8), // 234 + (9301283852250390625, 8), // 235 + (9622679558836781056, 8), // 236 + (9953750901796946721, 8), // 237 + (10294746488738365696, 8), // 238 + (10645920227784266881, 8), // 239 + (11007531417600000000, 8), // 240 + (11379844838561358721, 8), // 241 + (11763130845074473216, 8), // 242 + (12157665459056928801, 8), // 243 + (12563730464589807616, 8), // 244 + (12981613503750390625, 8), // 245 + (13411608173635297536, 8), // 246 + (13854014124583882561, 8), // 247 + (14309137159611744256, 8), // 248 + (14777289335064248001, 8), // 249 + (15258789062500000000, 8), // 250 + (15753961211814252001, 8), // 251 + (16263137215612256256, 8), // 252 + (16786655174842630561, 8), // 253 + (17324859965700833536, 8), // 254 + (17878103347812890625, 8), // 255 + (72057594037927936, 7), // 256 + ]; + + let (base, power) = BASES[radix as usize]; + (base as BigDigit, power) + } + _ => panic!("Invalid bigdigit size"), + } +} + +#[test] +fn test_from_slice() { + fn check(slice: &[BigDigit], data: &[BigDigit]) { + assert!(BigUint::from_slice(slice).data == data); + } + check(&[1], &[1]); + check(&[0, 0, 0], &[]); + check(&[1, 2, 0, 0], &[1, 2]); + check(&[0, 0, 1, 2], &[0, 0, 1, 2]); + check(&[0, 0, 1, 2, 0, 0], &[0, 0, 1, 2]); + check(&[-1i32 as BigDigit], &[-1i32 as BigDigit]); +} + +#[test] +fn test_assign_from_slice() { + fn check(slice: &[BigDigit], data: &[BigDigit]) { + let mut p = BigUint::from_slice(&[2627_u32, 0_u32, 9182_u32, 42_u32]); + p.assign_from_slice(slice); + assert!(p.data == data); + } + check(&[1], &[1]); + check(&[0, 0, 0], &[]); + check(&[1, 2, 0, 0], &[1, 2]); + check(&[0, 0, 1, 2], &[0, 0, 1, 2]); + check(&[0, 0, 1, 2, 0, 0], &[0, 0, 1, 2]); + check(&[-1i32 as BigDigit], &[-1i32 as BigDigit]); +} + +#[cfg(has_i128)] +#[test] +fn test_u32_u128() { + assert_eq!(u32_from_u128(0u128), (0, 0, 0, 0)); + assert_eq!( + u32_from_u128(u128::max_value()), + ( + u32::max_value(), + u32::max_value(), + u32::max_value(), + u32::max_value() + ) + ); + + assert_eq!( + u32_from_u128(u32::max_value() as u128), + (0, 0, 0, u32::max_value()) + ); + + assert_eq!( + u32_from_u128(u64::max_value() as u128), + (0, 0, u32::max_value(), u32::max_value()) + ); + + assert_eq!( + u32_from_u128((u64::max_value() as u128) + u32::max_value() as u128), + (0, 1, 0, u32::max_value() - 1) + ); + + assert_eq!(u32_from_u128(36_893_488_151_714_070_528), (0, 2, 1, 0)); +} + +#[cfg(has_i128)] +#[test] +fn test_u128_u32_roundtrip() { + // roundtrips + let values = vec![ + 0u128, + 1u128, + u64::max_value() as u128 * 3, + u32::max_value() as u128, + u64::max_value() as u128, + (u64::max_value() as u128) + u32::max_value() as u128, + u128::max_value(), + ]; + + for val in &values { + let (a, b, c, d) = u32_from_u128(*val); + assert_eq!(u32_to_u128(a, b, c, d), *val); + } +} + +#[test] +fn test_pow_biguint() { + let base = BigUint::from(5u8); + let exponent = BigUint::from(3u8); + + assert_eq!(BigUint::from(125u8), base.pow(exponent)); +} diff --git a/third_party/rust/num-bigint/src/lib.rs b/third_party/rust/num-bigint/src/lib.rs new file mode 100644 index 0000000000..dece7bab00 --- /dev/null +++ b/third_party/rust/num-bigint/src/lib.rs @@ -0,0 +1,206 @@ +// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A Big integer (signed version: `BigInt`, unsigned version: `BigUint`). +//! +//! A `BigUint` is represented as a vector of `BigDigit`s. +//! A `BigInt` is a combination of `BigUint` and `Sign`. +//! +//! Common numerical operations are overloaded, so we can treat them +//! the same way we treat other numbers. +//! +//! ## Example +//! +//! ```rust +//! extern crate num_bigint; +//! extern crate num_traits; +//! +//! # fn main() { +//! use num_bigint::BigUint; +//! use num_traits::{Zero, One}; +//! use std::mem::replace; +//! +//! // Calculate large fibonacci numbers. +//! fn fib(n: usize) -> BigUint { +//! let mut f0: BigUint = Zero::zero(); +//! let mut f1: BigUint = One::one(); +//! for _ in 0..n { +//! let f2 = f0 + &f1; +//! // This is a low cost way of swapping f0 with f1 and f1 with f2. +//! f0 = replace(&mut f1, f2); +//! } +//! f0 +//! } +//! +//! // This is a very large number. +//! println!("fib(1000) = {}", fib(1000)); +//! # } +//! ``` +//! +//! It's easy to generate large random numbers: +//! +//! ```rust +//! # #[cfg(feature = "rand")] +//! extern crate rand; +//! extern crate num_bigint as bigint; +//! +//! # #[cfg(feature = "rand")] +//! # fn main() { +//! use bigint::{ToBigInt, RandBigInt}; +//! +//! let mut rng = rand::thread_rng(); +//! let a = rng.gen_bigint(1000); +//! +//! let low = -10000.to_bigint().unwrap(); +//! let high = 10000.to_bigint().unwrap(); +//! let b = rng.gen_bigint_range(&low, &high); +//! +//! // Probably an even larger number. +//! println!("{}", a * b); +//! # } +//! +//! # #[cfg(not(feature = "rand"))] +//! # fn main() { +//! # } +//! ``` +//! +//! ## Compatibility +//! +//! The `num-bigint` crate is tested for rustc 1.15 and greater. + +#![doc(html_root_url = "https://docs.rs/num-bigint/0.2")] +// We don't actually support `no_std` yet, and probably won't until `alloc` is stable. We're just +// reserving this ability with the "std" feature now, and compilation will fail without. +#![cfg_attr(not(feature = "std"), no_std)] + +#[cfg(feature = "rand")] +extern crate rand; +#[cfg(feature = "serde")] +extern crate serde; + +extern crate num_integer as integer; +extern crate num_traits as traits; +#[cfg(feature = "quickcheck")] +extern crate quickcheck; + +use std::error::Error; +use std::fmt; + +#[macro_use] +mod macros; + +mod bigint; +mod biguint; + +#[cfg(feature = "rand")] +mod bigrand; + +#[cfg(target_pointer_width = "32")] +type UsizePromotion = u32; +#[cfg(target_pointer_width = "64")] +type UsizePromotion = u64; + +#[cfg(target_pointer_width = "32")] +type IsizePromotion = i32; +#[cfg(target_pointer_width = "64")] +type IsizePromotion = i64; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ParseBigIntError { + kind: BigIntErrorKind, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum BigIntErrorKind { + Empty, + InvalidDigit, +} + +impl ParseBigIntError { + fn __description(&self) -> &str { + use BigIntErrorKind::*; + match self.kind { + Empty => "cannot parse integer from empty string", + InvalidDigit => "invalid digit found in string", + } + } + + fn empty() -> Self { + ParseBigIntError { + kind: BigIntErrorKind::Empty, + } + } + + fn invalid() -> Self { + ParseBigIntError { + kind: BigIntErrorKind::InvalidDigit, + } + } +} + +impl fmt::Display for ParseBigIntError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.__description().fmt(f) + } +} + +impl Error for ParseBigIntError { + fn description(&self) -> &str { + self.__description() + } +} + +pub use biguint::BigUint; +pub use biguint::ToBigUint; + +pub use bigint::BigInt; +pub use bigint::Sign; +pub use bigint::ToBigInt; + +#[cfg(feature = "rand")] +pub use bigrand::{RandBigInt, RandomBits, UniformBigInt, UniformBigUint}; + +mod big_digit { + /// A `BigDigit` is a `BigUint`'s composing element. + pub type BigDigit = u32; + + /// A `DoubleBigDigit` is the internal type used to do the computations. Its + /// size is the double of the size of `BigDigit`. + pub type DoubleBigDigit = u64; + + /// A `SignedDoubleBigDigit` is the signed version of `DoubleBigDigit`. + pub type SignedDoubleBigDigit = i64; + + // `DoubleBigDigit` size dependent + pub const BITS: usize = 32; + + const LO_MASK: DoubleBigDigit = (-1i32 as DoubleBigDigit) >> BITS; + + #[inline] + fn get_hi(n: DoubleBigDigit) -> BigDigit { + (n >> BITS) as BigDigit + } + #[inline] + fn get_lo(n: DoubleBigDigit) -> BigDigit { + (n & LO_MASK) as BigDigit + } + + /// Split one `DoubleBigDigit` into two `BigDigit`s. + #[inline] + pub fn from_doublebigdigit(n: DoubleBigDigit) -> (BigDigit, BigDigit) { + (get_hi(n), get_lo(n)) + } + + /// Join two `BigDigit`s into one `DoubleBigDigit` + #[inline] + pub fn to_doublebigdigit(hi: BigDigit, lo: BigDigit) -> DoubleBigDigit { + DoubleBigDigit::from(lo) | (DoubleBigDigit::from(hi) << BITS) + } +} diff --git a/third_party/rust/num-bigint/src/macros.rs b/third_party/rust/num-bigint/src/macros.rs new file mode 100644 index 0000000000..0ba6e48c72 --- /dev/null +++ b/third_party/rust/num-bigint/src/macros.rs @@ -0,0 +1,445 @@ +#![allow(unknown_lints)] // older rustc doesn't know `unused_macros` +#![allow(unused_macros)] + +macro_rules! forward_val_val_binop { + (impl $imp:ident for $res:ty, $method:ident) => { + impl $imp<$res> for $res { + type Output = $res; + + #[inline] + fn $method(self, other: $res) -> $res { + // forward to val-ref + $imp::$method(self, &other) + } + } + }; +} + +macro_rules! forward_val_val_binop_commutative { + (impl $imp:ident for $res:ty, $method:ident) => { + impl $imp<$res> for $res { + type Output = $res; + + #[inline] + fn $method(self, other: $res) -> $res { + // forward to val-ref, with the larger capacity as val + if self.capacity() >= other.capacity() { + $imp::$method(self, &other) + } else { + $imp::$method(other, &self) + } + } + } + }; +} + +macro_rules! forward_ref_val_binop { + (impl $imp:ident for $res:ty, $method:ident) => { + impl<'a> $imp<$res> for &'a $res { + type Output = $res; + + #[inline] + fn $method(self, other: $res) -> $res { + // forward to ref-ref + $imp::$method(self, &other) + } + } + }; +} + +macro_rules! forward_ref_val_binop_commutative { + (impl $imp:ident for $res:ty, $method:ident) => { + impl<'a> $imp<$res> for &'a $res { + type Output = $res; + + #[inline] + fn $method(self, other: $res) -> $res { + // reverse, forward to val-ref + $imp::$method(other, self) + } + } + }; +} + +macro_rules! forward_val_ref_binop { + (impl $imp:ident for $res:ty, $method:ident) => { + impl<'a> $imp<&'a $res> for $res { + type Output = $res; + + #[inline] + fn $method(self, other: &$res) -> $res { + // forward to ref-ref + $imp::$method(&self, other) + } + } + }; +} + +macro_rules! forward_ref_ref_binop { + (impl $imp:ident for $res:ty, $method:ident) => { + impl<'a, 'b> $imp<&'b $res> for &'a $res { + type Output = $res; + + #[inline] + fn $method(self, other: &$res) -> $res { + // forward to val-ref + $imp::$method(self.clone(), other) + } + } + }; +} + +macro_rules! forward_ref_ref_binop_commutative { + (impl $imp:ident for $res:ty, $method:ident) => { + impl<'a, 'b> $imp<&'b $res> for &'a $res { + type Output = $res; + + #[inline] + fn $method(self, other: &$res) -> $res { + // forward to val-ref, choosing the larger to clone + if self.len() >= other.len() { + $imp::$method(self.clone(), other) + } else { + $imp::$method(other.clone(), self) + } + } + } + }; +} + +macro_rules! forward_val_assign { + (impl $imp:ident for $res:ty, $method:ident) => { + impl $imp<$res> for $res { + #[inline] + fn $method(&mut self, other: $res) { + self.$method(&other); + } + } + }; +} + +macro_rules! forward_val_assign_scalar { + (impl $imp:ident for $res:ty, $scalar:ty, $method:ident) => { + impl $imp<$res> for $scalar { + #[inline] + fn $method(&mut self, other: $res) { + self.$method(&other); + } + } + }; +} + +/// use this if val_val_binop is already implemented and the reversed order is required +macro_rules! forward_scalar_val_val_binop_commutative { + (impl $imp:ident < $scalar:ty > for $res:ty, $method:ident) => { + impl $imp<$res> for $scalar { + type Output = $res; + + #[inline] + fn $method(self, other: $res) -> $res { + $imp::$method(other, self) + } + } + }; +} + +// Forward scalar to ref-val, when reusing storage is not helpful +macro_rules! forward_scalar_val_val_binop_to_ref_val { + (impl $imp:ident<$scalar:ty> for $res:ty, $method:ident) => { + impl $imp<$scalar> for $res { + type Output = $res; + + #[inline] + fn $method(self, other: $scalar) -> $res { + $imp::$method(&self, other) + } + } + + impl $imp<$res> for $scalar { + type Output = $res; + + #[inline] + fn $method(self, other: $res) -> $res { + $imp::$method(self, &other) + } + } + }; +} + +macro_rules! forward_scalar_ref_ref_binop_to_ref_val { + (impl $imp:ident<$scalar:ty> for $res:ty, $method:ident) => { + impl<'a, 'b> $imp<&'b $scalar> for &'a $res { + type Output = $res; + + #[inline] + fn $method(self, other: &$scalar) -> $res { + $imp::$method(self, *other) + } + } + + impl<'a, 'b> $imp<&'a $res> for &'b $scalar { + type Output = $res; + + #[inline] + fn $method(self, other: &$res) -> $res { + $imp::$method(*self, other) + } + } + }; +} + +macro_rules! forward_scalar_val_ref_binop_to_ref_val { + (impl $imp:ident<$scalar:ty> for $res:ty, $method:ident) => { + impl<'a> $imp<&'a $scalar> for $res { + type Output = $res; + + #[inline] + fn $method(self, other: &$scalar) -> $res { + $imp::$method(&self, *other) + } + } + + impl<'a> $imp<$res> for &'a $scalar { + type Output = $res; + + #[inline] + fn $method(self, other: $res) -> $res { + $imp::$method(*self, &other) + } + } + }; +} + +macro_rules! forward_scalar_val_ref_binop_to_val_val { + (impl $imp:ident<$scalar:ty> for $res:ty, $method:ident) => { + impl<'a> $imp<&'a $scalar> for $res { + type Output = $res; + + #[inline] + fn $method(self, other: &$scalar) -> $res { + $imp::$method(self, *other) + } + } + + impl<'a> $imp<$res> for &'a $scalar { + type Output = $res; + + #[inline] + fn $method(self, other: $res) -> $res { + $imp::$method(*self, other) + } + } + }; +} + +macro_rules! forward_scalar_ref_val_binop_to_val_val { + (impl $imp:ident < $scalar:ty > for $res:ty, $method:ident) => { + impl<'a> $imp<$scalar> for &'a $res { + type Output = $res; + + #[inline] + fn $method(self, other: $scalar) -> $res { + $imp::$method(self.clone(), other) + } + } + + impl<'a> $imp<&'a $res> for $scalar { + type Output = $res; + + #[inline] + fn $method(self, other: &$res) -> $res { + $imp::$method(self, other.clone()) + } + } + }; +} + +macro_rules! forward_scalar_ref_ref_binop_to_val_val { + (impl $imp:ident<$scalar:ty> for $res:ty, $method:ident) => { + impl<'a, 'b> $imp<&'b $scalar> for &'a $res { + type Output = $res; + + #[inline] + fn $method(self, other: &$scalar) -> $res { + $imp::$method(self.clone(), *other) + } + } + + impl<'a, 'b> $imp<&'a $res> for &'b $scalar { + type Output = $res; + + #[inline] + fn $method(self, other: &$res) -> $res { + $imp::$method(*self, other.clone()) + } + } + }; +} + +macro_rules! promote_scalars { + (impl $imp:ident<$promo:ty> for $res:ty, $method:ident, $( $scalar:ty ),*) => { + $( + forward_all_scalar_binop_to_val_val!(impl $imp<$scalar> for $res, $method); + + impl $imp<$scalar> for $res { + type Output = $res; + + #[cfg_attr(feature = "cargo-clippy", allow(renamed_and_removed_lints))] + #[cfg_attr(feature = "cargo-clippy", allow(cast_lossless))] + #[inline] + fn $method(self, other: $scalar) -> $res { + $imp::$method(self, other as $promo) + } + } + + impl $imp<$res> for $scalar { + type Output = $res; + + #[cfg_attr(feature = "cargo-clippy", allow(renamed_and_removed_lints))] + #[cfg_attr(feature = "cargo-clippy", allow(cast_lossless))] + #[inline] + fn $method(self, other: $res) -> $res { + $imp::$method(self as $promo, other) + } + } + )* + } +} +macro_rules! promote_scalars_assign { + (impl $imp:ident<$promo:ty> for $res:ty, $method:ident, $( $scalar:ty ),*) => { + $( + impl $imp<$scalar> for $res { + #[cfg_attr(feature = "cargo-clippy", allow(renamed_and_removed_lints))] + #[cfg_attr(feature = "cargo-clippy", allow(cast_lossless))] + #[inline] + fn $method(&mut self, other: $scalar) { + self.$method(other as $promo); + } + } + )* + } +} + +macro_rules! promote_unsigned_scalars { + (impl $imp:ident for $res:ty, $method:ident) => { + promote_scalars!(impl $imp<u32> for $res, $method, u8, u16); + promote_scalars!(impl $imp<UsizePromotion> for $res, $method, usize); + } +} + +macro_rules! promote_unsigned_scalars_assign { + (impl $imp:ident for $res:ty, $method:ident) => { + promote_scalars_assign!(impl $imp<u32> for $res, $method, u8, u16); + promote_scalars_assign!(impl $imp<UsizePromotion> for $res, $method, usize); + } +} + +macro_rules! promote_signed_scalars { + (impl $imp:ident for $res:ty, $method:ident) => { + promote_scalars!(impl $imp<i32> for $res, $method, i8, i16); + promote_scalars!(impl $imp<IsizePromotion> for $res, $method, isize); + } +} + +macro_rules! promote_signed_scalars_assign { + (impl $imp:ident for $res:ty, $method:ident) => { + promote_scalars_assign!(impl $imp<i32> for $res, $method, i8, i16); + promote_scalars_assign!(impl $imp<UsizePromotion> for $res, $method, isize); + } +} + +// Forward everything to ref-ref, when reusing storage is not helpful +macro_rules! forward_all_binop_to_ref_ref { + (impl $imp:ident for $res:ty, $method:ident) => { + forward_val_val_binop!(impl $imp for $res, $method); + forward_val_ref_binop!(impl $imp for $res, $method); + forward_ref_val_binop!(impl $imp for $res, $method); + }; +} + +// Forward everything to val-ref, so LHS storage can be reused +macro_rules! forward_all_binop_to_val_ref { + (impl $imp:ident for $res:ty, $method:ident) => { + forward_val_val_binop!(impl $imp for $res, $method); + forward_ref_val_binop!(impl $imp for $res, $method); + forward_ref_ref_binop!(impl $imp for $res, $method); + }; +} + +// Forward everything to val-ref, commutatively, so either LHS or RHS storage can be reused +macro_rules! forward_all_binop_to_val_ref_commutative { + (impl $imp:ident for $res:ty, $method:ident) => { + forward_val_val_binop_commutative!(impl $imp for $res, $method); + forward_ref_val_binop_commutative!(impl $imp for $res, $method); + forward_ref_ref_binop_commutative!(impl $imp for $res, $method); + }; +} + +macro_rules! forward_all_scalar_binop_to_ref_val { + (impl $imp:ident<$scalar:ty> for $res:ty, $method:ident) => { + forward_scalar_val_val_binop_to_ref_val!(impl $imp<$scalar> for $res, $method); + forward_scalar_val_ref_binop_to_ref_val!(impl $imp<$scalar> for $res, $method); + forward_scalar_ref_ref_binop_to_ref_val!(impl $imp<$scalar> for $res, $method); + } +} + +macro_rules! forward_all_scalar_binop_to_val_val { + (impl $imp:ident<$scalar:ty> for $res:ty, $method:ident) => { + forward_scalar_val_ref_binop_to_val_val!(impl $imp<$scalar> for $res, $method); + forward_scalar_ref_val_binop_to_val_val!(impl $imp<$scalar> for $res, $method); + forward_scalar_ref_ref_binop_to_val_val!(impl $imp<$scalar> for $res, $method); + } +} + +macro_rules! forward_all_scalar_binop_to_val_val_commutative { + (impl $imp:ident<$scalar:ty> for $res:ty, $method:ident) => { + forward_scalar_val_val_binop_commutative!(impl $imp<$scalar> for $res, $method); + forward_all_scalar_binop_to_val_val!(impl $imp<$scalar> for $res, $method); + } +} + +macro_rules! promote_all_scalars { + (impl $imp:ident for $res:ty, $method:ident) => { + promote_unsigned_scalars!(impl $imp for $res, $method); + promote_signed_scalars!(impl $imp for $res, $method); + } +} + +macro_rules! promote_all_scalars_assign { + (impl $imp:ident for $res:ty, $method:ident) => { + promote_unsigned_scalars_assign!(impl $imp for $res, $method); + promote_signed_scalars_assign!(impl $imp for $res, $method); + } +} + +macro_rules! impl_sum_iter_type { + ($res:ty) => { + impl<T> Sum<T> for $res + where + $res: Add<T, Output = $res>, + { + fn sum<I>(iter: I) -> Self + where + I: Iterator<Item = T>, + { + iter.fold(Zero::zero(), <$res>::add) + } + } + }; +} + +macro_rules! impl_product_iter_type { + ($res:ty) => { + impl<T> Product<T> for $res + where + $res: Mul<T, Output = $res>, + { + fn product<I>(iter: I) -> Self + where + I: Iterator<Item = T>, + { + iter.fold(One::one(), <$res>::mul) + } + } + }; +} diff --git a/third_party/rust/num-bigint/src/monty.rs b/third_party/rust/num-bigint/src/monty.rs new file mode 100644 index 0000000000..72a4ab53eb --- /dev/null +++ b/third_party/rust/num-bigint/src/monty.rs @@ -0,0 +1,129 @@ +use integer::Integer; +use traits::Zero; + +use biguint::BigUint; + +struct MontyReducer<'a> { + n: &'a BigUint, + n0inv: u32, +} + +// Calculate the modular inverse of `num`, using Extended GCD. +// +// Reference: +// Brent & Zimmermann, Modern Computer Arithmetic, v0.5.9, Algorithm 1.20 +fn inv_mod_u32(num: u32) -> u32 { + // num needs to be relatively prime to 2**32 -- i.e. it must be odd. + assert!(num % 2 != 0); + + let mut a: i64 = i64::from(num); + let mut b: i64 = i64::from(u32::max_value()) + 1; + + // ExtendedGcd + // Input: positive integers a and b + // Output: integers (g, u, v) such that g = gcd(a, b) = ua + vb + // As we don't need v for modular inverse, we don't calculate it. + + // 1: (u, w) <- (1, 0) + let mut u = 1; + let mut w = 0; + // 3: while b != 0 + while b != 0 { + // 4: (q, r) <- DivRem(a, b) + let q = a / b; + let r = a % b; + // 5: (a, b) <- (b, r) + a = b; + b = r; + // 6: (u, w) <- (w, u - qw) + let m = u - w * q; + u = w; + w = m; + } + + assert!(a == 1); + // Downcasting acts like a mod 2^32 too. + u as u32 +} + +impl<'a> MontyReducer<'a> { + fn new(n: &'a BigUint) -> Self { + let n0inv = inv_mod_u32(n.data[0]); + MontyReducer { n: n, n0inv: n0inv } + } +} + +// Montgomery Reduction +// +// Reference: +// Brent & Zimmermann, Modern Computer Arithmetic, v0.5.9, Algorithm 2.6 +fn monty_redc(a: BigUint, mr: &MontyReducer) -> BigUint { + let mut c = a.data; + let n = &mr.n.data; + let n_size = n.len(); + + // Allocate sufficient work space + c.resize(2 * n_size + 2, 0); + + // β is the size of a word, in this case 32 bits. So "a mod β" is + // equivalent to masking a to 32 bits. + // mu <- -N^(-1) mod β + let mu = 0u32.wrapping_sub(mr.n0inv); + + // 1: for i = 0 to (n-1) + for i in 0..n_size { + // 2: q_i <- mu*c_i mod β + let q_i = c[i].wrapping_mul(mu); + + // 3: C <- C + q_i * N * β^i + super::algorithms::mac_digit(&mut c[i..], n, q_i); + } + + // 4: R <- C * β^(-n) + // This is an n-word bitshift, equivalent to skipping n words. + let ret = BigUint::new(c[n_size..].to_vec()); + + // 5: if R >= β^n then return R-N else return R. + if &ret < mr.n { + ret + } else { + ret - mr.n + } +} + +// Montgomery Multiplication +fn monty_mult(a: BigUint, b: &BigUint, mr: &MontyReducer) -> BigUint { + monty_redc(a * b, mr) +} + +// Montgomery Squaring +fn monty_sqr(a: BigUint, mr: &MontyReducer) -> BigUint { + // TODO: Replace with an optimised squaring function + monty_redc(&a * &a, mr) +} + +pub fn monty_modpow(a: &BigUint, exp: &BigUint, modulus: &BigUint) -> BigUint { + let mr = MontyReducer::new(modulus); + + // Calculate the Montgomery parameter + let mut v = vec![0; modulus.data.len()]; + v.push(1); + let r = BigUint::new(v); + + // Map the base to the Montgomery domain + let mut apri = a * &r % modulus; + + // Binary exponentiation + let mut ans = &r % modulus; + let mut e = exp.clone(); + while !e.is_zero() { + if e.is_odd() { + ans = monty_mult(ans, &apri, &mr); + } + apri = monty_sqr(apri, &mr); + e = e >> 1; + } + + // Map the result back to the residues domain + monty_redc(ans, &mr) +} diff --git a/third_party/rust/num-bigint/tests/bigint.rs b/third_party/rust/num-bigint/tests/bigint.rs new file mode 100644 index 0000000000..911bff0020 --- /dev/null +++ b/third_party/rust/num-bigint/tests/bigint.rs @@ -0,0 +1,1193 @@ +extern crate num_bigint; +extern crate num_integer; +extern crate num_traits; +#[cfg(feature = "rand")] +extern crate rand; + +use num_bigint::BigUint; +use num_bigint::Sign::{Minus, NoSign, Plus}; +use num_bigint::{BigInt, ToBigInt}; + +use std::cmp::Ordering::{Equal, Greater, Less}; +use std::collections::hash_map::RandomState; +use std::hash::{BuildHasher, Hash, Hasher}; +use std::iter::repeat; +use std::ops::Neg; +use std::{f32, f64}; +#[cfg(has_i128)] +use std::{i128, u128}; +use std::{i16, i32, i64, i8, isize}; +use std::{u16, u32, u64, u8, usize}; + +use num_integer::Integer; +use num_traits::{Float, FromPrimitive, Num, One, Pow, Signed, ToPrimitive, Zero}; + +mod consts; +use consts::*; + +#[macro_use] +mod macros; + +#[test] +fn test_from_bytes_be() { + fn check(s: &str, result: &str) { + assert_eq!( + BigInt::from_bytes_be(Plus, s.as_bytes()), + BigInt::parse_bytes(result.as_bytes(), 10).unwrap() + ); + } + check("A", "65"); + check("AA", "16705"); + check("AB", "16706"); + check("Hello world!", "22405534230753963835153736737"); + assert_eq!(BigInt::from_bytes_be(Plus, &[]), Zero::zero()); + assert_eq!(BigInt::from_bytes_be(Minus, &[]), Zero::zero()); +} + +#[test] +fn test_to_bytes_be() { + fn check(s: &str, result: &str) { + let b = BigInt::parse_bytes(result.as_bytes(), 10).unwrap(); + let (sign, v) = b.to_bytes_be(); + assert_eq!((Plus, s.as_bytes()), (sign, &*v)); + } + check("A", "65"); + check("AA", "16705"); + check("AB", "16706"); + check("Hello world!", "22405534230753963835153736737"); + let b: BigInt = Zero::zero(); + assert_eq!(b.to_bytes_be(), (NoSign, vec![0])); + + // Test with leading/trailing zero bytes and a full BigDigit of value 0 + let b = BigInt::from_str_radix("00010000000000000200", 16).unwrap(); + assert_eq!(b.to_bytes_be(), (Plus, vec![1, 0, 0, 0, 0, 0, 0, 2, 0])); +} + +#[test] +fn test_from_bytes_le() { + fn check(s: &str, result: &str) { + assert_eq!( + BigInt::from_bytes_le(Plus, s.as_bytes()), + BigInt::parse_bytes(result.as_bytes(), 10).unwrap() + ); + } + check("A", "65"); + check("AA", "16705"); + check("BA", "16706"); + check("!dlrow olleH", "22405534230753963835153736737"); + assert_eq!(BigInt::from_bytes_le(Plus, &[]), Zero::zero()); + assert_eq!(BigInt::from_bytes_le(Minus, &[]), Zero::zero()); +} + +#[test] +fn test_to_bytes_le() { + fn check(s: &str, result: &str) { + let b = BigInt::parse_bytes(result.as_bytes(), 10).unwrap(); + let (sign, v) = b.to_bytes_le(); + assert_eq!((Plus, s.as_bytes()), (sign, &*v)); + } + check("A", "65"); + check("AA", "16705"); + check("BA", "16706"); + check("!dlrow olleH", "22405534230753963835153736737"); + let b: BigInt = Zero::zero(); + assert_eq!(b.to_bytes_le(), (NoSign, vec![0])); + + // Test with leading/trailing zero bytes and a full BigDigit of value 0 + let b = BigInt::from_str_radix("00010000000000000200", 16).unwrap(); + assert_eq!(b.to_bytes_le(), (Plus, vec![0, 2, 0, 0, 0, 0, 0, 0, 1])); +} + +#[test] +fn test_to_signed_bytes_le() { + fn check(s: &str, result: Vec<u8>) { + assert_eq!( + BigInt::parse_bytes(s.as_bytes(), 10) + .unwrap() + .to_signed_bytes_le(), + result + ); + } + + check("0", vec![0]); + check("32767", vec![0xff, 0x7f]); + check("-1", vec![0xff]); + check("16777216", vec![0, 0, 0, 1]); + check("-100", vec![156]); + check("-8388608", vec![0, 0, 0x80]); + check("-192", vec![0x40, 0xff]); + check("128", vec![0x80, 0]) +} + +#[test] +fn test_from_signed_bytes_le() { + fn check(s: &[u8], result: &str) { + assert_eq!( + BigInt::from_signed_bytes_le(s), + BigInt::parse_bytes(result.as_bytes(), 10).unwrap() + ); + } + + check(&[], "0"); + check(&[0], "0"); + check(&[0; 10], "0"); + check(&[0xff, 0x7f], "32767"); + check(&[0xff], "-1"); + check(&[0, 0, 0, 1], "16777216"); + check(&[156], "-100"); + check(&[0, 0, 0x80], "-8388608"); + check(&[0xff; 10], "-1"); + check(&[0x40, 0xff], "-192"); +} + +#[test] +fn test_to_signed_bytes_be() { + fn check(s: &str, result: Vec<u8>) { + assert_eq!( + BigInt::parse_bytes(s.as_bytes(), 10) + .unwrap() + .to_signed_bytes_be(), + result + ); + } + + check("0", vec![0]); + check("32767", vec![0x7f, 0xff]); + check("-1", vec![255]); + check("16777216", vec![1, 0, 0, 0]); + check("-100", vec![156]); + check("-8388608", vec![128, 0, 0]); + check("-192", vec![0xff, 0x40]); + check("128", vec![0, 0x80]); +} + +#[test] +fn test_from_signed_bytes_be() { + fn check(s: &[u8], result: &str) { + assert_eq!( + BigInt::from_signed_bytes_be(s), + BigInt::parse_bytes(result.as_bytes(), 10).unwrap() + ); + } + + check(&[], "0"); + check(&[0], "0"); + check(&[0; 10], "0"); + check(&[127, 255], "32767"); + check(&[255], "-1"); + check(&[1, 0, 0, 0], "16777216"); + check(&[156], "-100"); + check(&[128, 0, 0], "-8388608"); + check(&[255; 10], "-1"); + check(&[0xff, 0x40], "-192"); +} + +#[test] +fn test_signed_bytes_be_round_trip() { + for i in -0x1FFFF..0x20000 { + let n = BigInt::from(i); + assert_eq!(n, BigInt::from_signed_bytes_be(&n.to_signed_bytes_be())); + } +} + +#[test] +fn test_signed_bytes_le_round_trip() { + for i in -0x1FFFF..0x20000 { + let n = BigInt::from(i); + assert_eq!(n, BigInt::from_signed_bytes_le(&n.to_signed_bytes_le())); + } +} + +#[test] +fn test_cmp() { + let vs: [&[u32]; 4] = [&[2 as u32], &[1, 1], &[2, 1], &[1, 1, 1]]; + let mut nums = Vec::new(); + for s in vs.iter().rev() { + nums.push(BigInt::from_slice(Minus, *s)); + } + nums.push(Zero::zero()); + nums.extend(vs.iter().map(|s| BigInt::from_slice(Plus, *s))); + + for (i, ni) in nums.iter().enumerate() { + for (j0, nj) in nums[i..].iter().enumerate() { + let j = i + j0; + if i == j { + assert_eq!(ni.cmp(nj), Equal); + assert_eq!(nj.cmp(ni), Equal); + assert_eq!(ni, nj); + assert!(!(ni != nj)); + assert!(ni <= nj); + assert!(ni >= nj); + assert!(!(ni < nj)); + assert!(!(ni > nj)); + } else { + assert_eq!(ni.cmp(nj), Less); + assert_eq!(nj.cmp(ni), Greater); + + assert!(!(ni == nj)); + assert!(ni != nj); + + assert!(ni <= nj); + assert!(!(ni >= nj)); + assert!(ni < nj); + assert!(!(ni > nj)); + + assert!(!(nj <= ni)); + assert!(nj >= ni); + assert!(!(nj < ni)); + assert!(nj > ni); + } + } + } +} + +fn hash<T: Hash>(x: &T) -> u64 { + let mut hasher = <RandomState as BuildHasher>::Hasher::new(); + x.hash(&mut hasher); + hasher.finish() +} + +#[test] +fn test_hash() { + let a = BigInt::new(NoSign, vec![]); + let b = BigInt::new(NoSign, vec![0]); + let c = BigInt::new(Plus, vec![1]); + let d = BigInt::new(Plus, vec![1, 0, 0, 0, 0, 0]); + let e = BigInt::new(Plus, vec![0, 0, 0, 0, 0, 1]); + let f = BigInt::new(Minus, vec![1]); + assert!(hash(&a) == hash(&b)); + assert!(hash(&b) != hash(&c)); + assert!(hash(&c) == hash(&d)); + assert!(hash(&d) != hash(&e)); + assert!(hash(&c) != hash(&f)); +} + +#[test] +fn test_convert_i64() { + fn check(b1: BigInt, i: i64) { + let b2: BigInt = FromPrimitive::from_i64(i).unwrap(); + assert!(b1 == b2); + assert!(b1.to_i64().unwrap() == i); + } + + check(Zero::zero(), 0); + check(One::one(), 1); + check(i64::MIN.to_bigint().unwrap(), i64::MIN); + check(i64::MAX.to_bigint().unwrap(), i64::MAX); + + assert_eq!((i64::MAX as u64 + 1).to_bigint().unwrap().to_i64(), None); + + assert_eq!( + BigInt::from_biguint(Plus, BigUint::new(vec![1, 2, 3, 4, 5])).to_i64(), + None + ); + + assert_eq!( + BigInt::from_biguint(Minus, BigUint::new(vec![1, 0, 0, 1 << 31])).to_i64(), + None + ); + + assert_eq!( + BigInt::from_biguint(Minus, BigUint::new(vec![1, 2, 3, 4, 5])).to_i64(), + None + ); +} + +#[test] +#[cfg(has_i128)] +fn test_convert_i128() { + fn check(b1: BigInt, i: i128) { + let b2: BigInt = FromPrimitive::from_i128(i).unwrap(); + assert!(b1 == b2); + assert!(b1.to_i128().unwrap() == i); + } + + check(Zero::zero(), 0); + check(One::one(), 1); + check(i128::MIN.to_bigint().unwrap(), i128::MIN); + check(i128::MAX.to_bigint().unwrap(), i128::MAX); + + assert_eq!((i128::MAX as u128 + 1).to_bigint().unwrap().to_i128(), None); + + assert_eq!( + BigInt::from_biguint(Plus, BigUint::new(vec![1, 2, 3, 4, 5])).to_i128(), + None + ); + + assert_eq!( + BigInt::from_biguint(Minus, BigUint::new(vec![1, 0, 0, 1 << 31])).to_i128(), + None + ); + + assert_eq!( + BigInt::from_biguint(Minus, BigUint::new(vec![1, 2, 3, 4, 5])).to_i128(), + None + ); +} + +#[test] +fn test_convert_u64() { + fn check(b1: BigInt, u: u64) { + let b2: BigInt = FromPrimitive::from_u64(u).unwrap(); + assert!(b1 == b2); + assert!(b1.to_u64().unwrap() == u); + } + + check(Zero::zero(), 0); + check(One::one(), 1); + check(u64::MIN.to_bigint().unwrap(), u64::MIN); + check(u64::MAX.to_bigint().unwrap(), u64::MAX); + + assert_eq!( + BigInt::from_biguint(Plus, BigUint::new(vec![1, 2, 3, 4, 5])).to_u64(), + None + ); + + let max_value: BigUint = FromPrimitive::from_u64(u64::MAX).unwrap(); + assert_eq!(BigInt::from_biguint(Minus, max_value).to_u64(), None); + assert_eq!( + BigInt::from_biguint(Minus, BigUint::new(vec![1, 2, 3, 4, 5])).to_u64(), + None + ); +} + +#[test] +#[cfg(has_i128)] +fn test_convert_u128() { + fn check(b1: BigInt, u: u128) { + let b2: BigInt = FromPrimitive::from_u128(u).unwrap(); + assert!(b1 == b2); + assert!(b1.to_u128().unwrap() == u); + } + + check(Zero::zero(), 0); + check(One::one(), 1); + check(u128::MIN.to_bigint().unwrap(), u128::MIN); + check(u128::MAX.to_bigint().unwrap(), u128::MAX); + + assert_eq!( + BigInt::from_biguint(Plus, BigUint::new(vec![1, 2, 3, 4, 5])).to_u128(), + None + ); + + let max_value: BigUint = FromPrimitive::from_u128(u128::MAX).unwrap(); + assert_eq!(BigInt::from_biguint(Minus, max_value).to_u128(), None); + assert_eq!( + BigInt::from_biguint(Minus, BigUint::new(vec![1, 2, 3, 4, 5])).to_u128(), + None + ); +} + +#[test] +fn test_convert_f32() { + fn check(b1: &BigInt, f: f32) { + let b2 = BigInt::from_f32(f).unwrap(); + assert_eq!(b1, &b2); + assert_eq!(b1.to_f32().unwrap(), f); + let neg_b1 = -b1; + let neg_b2 = BigInt::from_f32(-f).unwrap(); + assert_eq!(neg_b1, neg_b2); + assert_eq!(neg_b1.to_f32().unwrap(), -f); + } + + check(&BigInt::zero(), 0.0); + check(&BigInt::one(), 1.0); + check(&BigInt::from(u16::MAX), 2.0.powi(16) - 1.0); + check(&BigInt::from(1u64 << 32), 2.0.powi(32)); + check(&BigInt::from_slice(Plus, &[0, 0, 1]), 2.0.powi(64)); + check( + &((BigInt::one() << 100) + (BigInt::one() << 123)), + 2.0.powi(100) + 2.0.powi(123), + ); + check(&(BigInt::one() << 127), 2.0.powi(127)); + check(&(BigInt::from((1u64 << 24) - 1) << (128 - 24)), f32::MAX); + + // keeping all 24 digits with the bits at different offsets to the BigDigits + let x: u32 = 0b00000000101111011111011011011101; + let mut f = x as f32; + let mut b = BigInt::from(x); + for _ in 0..64 { + check(&b, f); + f *= 2.0; + b = b << 1; + } + + // this number when rounded to f64 then f32 isn't the same as when rounded straight to f32 + let mut n: i64 = 0b0000000000111111111111111111111111011111111111111111111111111111; + assert!((n as f64) as f32 != n as f32); + assert_eq!(BigInt::from(n).to_f32(), Some(n as f32)); + n = -n; + assert!((n as f64) as f32 != n as f32); + assert_eq!(BigInt::from(n).to_f32(), Some(n as f32)); + + // test rounding up with the bits at different offsets to the BigDigits + let mut f = ((1u64 << 25) - 1) as f32; + let mut b = BigInt::from(1u64 << 25); + for _ in 0..64 { + assert_eq!(b.to_f32(), Some(f)); + f *= 2.0; + b = b << 1; + } + + // rounding + assert_eq!( + BigInt::from_f32(-f32::consts::PI), + Some(BigInt::from(-3i32)) + ); + assert_eq!(BigInt::from_f32(-f32::consts::E), Some(BigInt::from(-2i32))); + assert_eq!(BigInt::from_f32(-0.99999), Some(BigInt::zero())); + assert_eq!(BigInt::from_f32(-0.5), Some(BigInt::zero())); + assert_eq!(BigInt::from_f32(-0.0), Some(BigInt::zero())); + assert_eq!( + BigInt::from_f32(f32::MIN_POSITIVE / 2.0), + Some(BigInt::zero()) + ); + assert_eq!(BigInt::from_f32(f32::MIN_POSITIVE), Some(BigInt::zero())); + assert_eq!(BigInt::from_f32(0.5), Some(BigInt::zero())); + assert_eq!(BigInt::from_f32(0.99999), Some(BigInt::zero())); + assert_eq!(BigInt::from_f32(f32::consts::E), Some(BigInt::from(2u32))); + assert_eq!(BigInt::from_f32(f32::consts::PI), Some(BigInt::from(3u32))); + + // special float values + assert_eq!(BigInt::from_f32(f32::NAN), None); + assert_eq!(BigInt::from_f32(f32::INFINITY), None); + assert_eq!(BigInt::from_f32(f32::NEG_INFINITY), None); + + // largest BigInt that will round to a finite f32 value + let big_num = (BigInt::one() << 128) - BigInt::one() - (BigInt::one() << (128 - 25)); + assert_eq!(big_num.to_f32(), Some(f32::MAX)); + assert_eq!((&big_num + BigInt::one()).to_f32(), None); + assert_eq!((-&big_num).to_f32(), Some(f32::MIN)); + assert_eq!(((-&big_num) - BigInt::one()).to_f32(), None); + + assert_eq!(((BigInt::one() << 128) - BigInt::one()).to_f32(), None); + assert_eq!((BigInt::one() << 128).to_f32(), None); + assert_eq!((-((BigInt::one() << 128) - BigInt::one())).to_f32(), None); + assert_eq!((-(BigInt::one() << 128)).to_f32(), None); +} + +#[test] +fn test_convert_f64() { + fn check(b1: &BigInt, f: f64) { + let b2 = BigInt::from_f64(f).unwrap(); + assert_eq!(b1, &b2); + assert_eq!(b1.to_f64().unwrap(), f); + let neg_b1 = -b1; + let neg_b2 = BigInt::from_f64(-f).unwrap(); + assert_eq!(neg_b1, neg_b2); + assert_eq!(neg_b1.to_f64().unwrap(), -f); + } + + check(&BigInt::zero(), 0.0); + check(&BigInt::one(), 1.0); + check(&BigInt::from(u32::MAX), 2.0.powi(32) - 1.0); + check(&BigInt::from(1u64 << 32), 2.0.powi(32)); + check(&BigInt::from_slice(Plus, &[0, 0, 1]), 2.0.powi(64)); + check( + &((BigInt::one() << 100) + (BigInt::one() << 152)), + 2.0.powi(100) + 2.0.powi(152), + ); + check(&(BigInt::one() << 1023), 2.0.powi(1023)); + check(&(BigInt::from((1u64 << 53) - 1) << (1024 - 53)), f64::MAX); + + // keeping all 53 digits with the bits at different offsets to the BigDigits + let x: u64 = 0b0000000000011110111110110111111101110111101111011111011011011101; + let mut f = x as f64; + let mut b = BigInt::from(x); + for _ in 0..128 { + check(&b, f); + f *= 2.0; + b = b << 1; + } + + // test rounding up with the bits at different offsets to the BigDigits + let mut f = ((1u64 << 54) - 1) as f64; + let mut b = BigInt::from(1u64 << 54); + for _ in 0..128 { + assert_eq!(b.to_f64(), Some(f)); + f *= 2.0; + b = b << 1; + } + + // rounding + assert_eq!( + BigInt::from_f64(-f64::consts::PI), + Some(BigInt::from(-3i32)) + ); + assert_eq!(BigInt::from_f64(-f64::consts::E), Some(BigInt::from(-2i32))); + assert_eq!(BigInt::from_f64(-0.99999), Some(BigInt::zero())); + assert_eq!(BigInt::from_f64(-0.5), Some(BigInt::zero())); + assert_eq!(BigInt::from_f64(-0.0), Some(BigInt::zero())); + assert_eq!( + BigInt::from_f64(f64::MIN_POSITIVE / 2.0), + Some(BigInt::zero()) + ); + assert_eq!(BigInt::from_f64(f64::MIN_POSITIVE), Some(BigInt::zero())); + assert_eq!(BigInt::from_f64(0.5), Some(BigInt::zero())); + assert_eq!(BigInt::from_f64(0.99999), Some(BigInt::zero())); + assert_eq!(BigInt::from_f64(f64::consts::E), Some(BigInt::from(2u32))); + assert_eq!(BigInt::from_f64(f64::consts::PI), Some(BigInt::from(3u32))); + + // special float values + assert_eq!(BigInt::from_f64(f64::NAN), None); + assert_eq!(BigInt::from_f64(f64::INFINITY), None); + assert_eq!(BigInt::from_f64(f64::NEG_INFINITY), None); + + // largest BigInt that will round to a finite f64 value + let big_num = (BigInt::one() << 1024) - BigInt::one() - (BigInt::one() << (1024 - 54)); + assert_eq!(big_num.to_f64(), Some(f64::MAX)); + assert_eq!((&big_num + BigInt::one()).to_f64(), None); + assert_eq!((-&big_num).to_f64(), Some(f64::MIN)); + assert_eq!(((-&big_num) - BigInt::one()).to_f64(), None); + + assert_eq!(((BigInt::one() << 1024) - BigInt::one()).to_f64(), None); + assert_eq!((BigInt::one() << 1024).to_f64(), None); + assert_eq!((-((BigInt::one() << 1024) - BigInt::one())).to_f64(), None); + assert_eq!((-(BigInt::one() << 1024)).to_f64(), None); +} + +#[test] +fn test_convert_to_biguint() { + fn check(n: BigInt, ans_1: BigUint) { + assert_eq!(n.to_biguint().unwrap(), ans_1); + assert_eq!(n.to_biguint().unwrap().to_bigint().unwrap(), n); + } + let zero: BigInt = Zero::zero(); + let unsigned_zero: BigUint = Zero::zero(); + let positive = BigInt::from_biguint(Plus, BigUint::new(vec![1, 2, 3])); + let negative = -&positive; + + check(zero, unsigned_zero); + check(positive, BigUint::new(vec![1, 2, 3])); + + assert_eq!(negative.to_biguint(), None); +} + +#[test] +fn test_convert_from_uint() { + macro_rules! check { + ($ty:ident, $max:expr) => { + assert_eq!(BigInt::from($ty::zero()), BigInt::zero()); + assert_eq!(BigInt::from($ty::one()), BigInt::one()); + assert_eq!(BigInt::from($ty::MAX - $ty::one()), $max - BigInt::one()); + assert_eq!(BigInt::from($ty::MAX), $max); + }; + } + + check!(u8, BigInt::from_slice(Plus, &[u8::MAX as u32])); + check!(u16, BigInt::from_slice(Plus, &[u16::MAX as u32])); + check!(u32, BigInt::from_slice(Plus, &[u32::MAX])); + check!(u64, BigInt::from_slice(Plus, &[u32::MAX, u32::MAX])); + #[cfg(has_i128)] + check!( + u128, + BigInt::from_slice(Plus, &[u32::MAX, u32::MAX, u32::MAX, u32::MAX]) + ); + check!(usize, BigInt::from(usize::MAX as u64)); +} + +#[test] +fn test_convert_from_int() { + macro_rules! check { + ($ty:ident, $min:expr, $max:expr) => { + assert_eq!(BigInt::from($ty::MIN), $min); + assert_eq!(BigInt::from($ty::MIN + $ty::one()), $min + BigInt::one()); + assert_eq!(BigInt::from(-$ty::one()), -BigInt::one()); + assert_eq!(BigInt::from($ty::zero()), BigInt::zero()); + assert_eq!(BigInt::from($ty::one()), BigInt::one()); + assert_eq!(BigInt::from($ty::MAX - $ty::one()), $max - BigInt::one()); + assert_eq!(BigInt::from($ty::MAX), $max); + }; + } + + check!( + i8, + BigInt::from_slice(Minus, &[1 << 7]), + BigInt::from_slice(Plus, &[i8::MAX as u32]) + ); + check!( + i16, + BigInt::from_slice(Minus, &[1 << 15]), + BigInt::from_slice(Plus, &[i16::MAX as u32]) + ); + check!( + i32, + BigInt::from_slice(Minus, &[1 << 31]), + BigInt::from_slice(Plus, &[i32::MAX as u32]) + ); + check!( + i64, + BigInt::from_slice(Minus, &[0, 1 << 31]), + BigInt::from_slice(Plus, &[u32::MAX, i32::MAX as u32]) + ); + #[cfg(has_i128)] + check!( + i128, + BigInt::from_slice(Minus, &[0, 0, 0, 1 << 31]), + BigInt::from_slice(Plus, &[u32::MAX, u32::MAX, u32::MAX, i32::MAX as u32]) + ); + check!( + isize, + BigInt::from(isize::MIN as i64), + BigInt::from(isize::MAX as i64) + ); +} + +#[test] +fn test_convert_from_biguint() { + assert_eq!(BigInt::from(BigUint::zero()), BigInt::zero()); + assert_eq!(BigInt::from(BigUint::one()), BigInt::one()); + assert_eq!( + BigInt::from(BigUint::from_slice(&[1, 2, 3])), + BigInt::from_slice(Plus, &[1, 2, 3]) + ); +} + +#[test] +fn test_add() { + for elm in SUM_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + let (na, nb, nc) = (-&a, -&b, -&c); + + assert_op!(a + b == c); + assert_op!(b + a == c); + assert_op!(c + na == b); + assert_op!(c + nb == a); + assert_op!(a + nc == nb); + assert_op!(b + nc == na); + assert_op!(na + nb == nc); + assert_op!(a + na == Zero::zero()); + + assert_assign_op!(a += b == c); + assert_assign_op!(b += a == c); + assert_assign_op!(c += na == b); + assert_assign_op!(c += nb == a); + assert_assign_op!(a += nc == nb); + assert_assign_op!(b += nc == na); + assert_assign_op!(na += nb == nc); + assert_assign_op!(a += na == Zero::zero()); + } +} + +#[test] +fn test_sub() { + for elm in SUM_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + let (na, nb, nc) = (-&a, -&b, -&c); + + assert_op!(c - a == b); + assert_op!(c - b == a); + assert_op!(nb - a == nc); + assert_op!(na - b == nc); + assert_op!(b - na == c); + assert_op!(a - nb == c); + assert_op!(nc - na == nb); + assert_op!(a - a == Zero::zero()); + + assert_assign_op!(c -= a == b); + assert_assign_op!(c -= b == a); + assert_assign_op!(nb -= a == nc); + assert_assign_op!(na -= b == nc); + assert_assign_op!(b -= na == c); + assert_assign_op!(a -= nb == c); + assert_assign_op!(nc -= na == nb); + assert_assign_op!(a -= a == Zero::zero()); + } +} + +#[test] +fn test_mul() { + for elm in MUL_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + let (na, nb, nc) = (-&a, -&b, -&c); + + assert_op!(a * b == c); + assert_op!(b * a == c); + assert_op!(na * nb == c); + + assert_op!(na * b == nc); + assert_op!(nb * a == nc); + + assert_assign_op!(a *= b == c); + assert_assign_op!(b *= a == c); + assert_assign_op!(na *= nb == c); + + assert_assign_op!(na *= b == nc); + assert_assign_op!(nb *= a == nc); + } + + for elm in DIV_REM_QUADRUPLES.iter() { + let (a_vec, b_vec, c_vec, d_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + let d = BigInt::from_slice(Plus, d_vec); + + assert!(a == &b * &c + &d); + assert!(a == &c * &b + &d); + } +} + +#[test] +fn test_div_mod_floor() { + fn check_sub(a: &BigInt, b: &BigInt, ans_d: &BigInt, ans_m: &BigInt) { + let (d, m) = a.div_mod_floor(b); + if !m.is_zero() { + assert_eq!(m.sign(), b.sign()); + } + assert!(m.abs() <= b.abs()); + assert!(*a == b * &d + &m); + assert!(d == *ans_d); + assert!(m == *ans_m); + } + + fn check(a: &BigInt, b: &BigInt, d: &BigInt, m: &BigInt) { + if m.is_zero() { + check_sub(a, b, d, m); + check_sub(a, &b.neg(), &d.neg(), m); + check_sub(&a.neg(), b, &d.neg(), m); + check_sub(&a.neg(), &b.neg(), d, m); + } else { + let one: BigInt = One::one(); + check_sub(a, b, d, m); + check_sub(a, &b.neg(), &(d.neg() - &one), &(m - b)); + check_sub(&a.neg(), b, &(d.neg() - &one), &(b - m)); + check_sub(&a.neg(), &b.neg(), d, &m.neg()); + } + } + + for elm in MUL_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + + if !a.is_zero() { + check(&c, &a, &b, &Zero::zero()); + } + if !b.is_zero() { + check(&c, &b, &a, &Zero::zero()); + } + } + + for elm in DIV_REM_QUADRUPLES.iter() { + let (a_vec, b_vec, c_vec, d_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + let d = BigInt::from_slice(Plus, d_vec); + + if !b.is_zero() { + check(&a, &b, &c, &d); + } + } +} + +#[test] +fn test_div_rem() { + fn check_sub(a: &BigInt, b: &BigInt, ans_q: &BigInt, ans_r: &BigInt) { + let (q, r) = a.div_rem(b); + if !r.is_zero() { + assert_eq!(r.sign(), a.sign()); + } + assert!(r.abs() <= b.abs()); + assert!(*a == b * &q + &r); + assert!(q == *ans_q); + assert!(r == *ans_r); + + let (a, b, ans_q, ans_r) = (a.clone(), b.clone(), ans_q.clone(), ans_r.clone()); + assert_op!(a / b == ans_q); + assert_op!(a % b == ans_r); + assert_assign_op!(a /= b == ans_q); + assert_assign_op!(a %= b == ans_r); + } + + fn check(a: &BigInt, b: &BigInt, q: &BigInt, r: &BigInt) { + check_sub(a, b, q, r); + check_sub(a, &b.neg(), &q.neg(), r); + check_sub(&a.neg(), b, &q.neg(), &r.neg()); + check_sub(&a.neg(), &b.neg(), q, &r.neg()); + } + for elm in MUL_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + + if !a.is_zero() { + check(&c, &a, &b, &Zero::zero()); + } + if !b.is_zero() { + check(&c, &b, &a, &Zero::zero()); + } + } + + for elm in DIV_REM_QUADRUPLES.iter() { + let (a_vec, b_vec, c_vec, d_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + let d = BigInt::from_slice(Plus, d_vec); + + if !b.is_zero() { + check(&a, &b, &c, &d); + } + } +} + +#[test] +fn test_checked_add() { + for elm in SUM_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + + assert!(a.checked_add(&b).unwrap() == c); + assert!(b.checked_add(&a).unwrap() == c); + assert!(c.checked_add(&(-&a)).unwrap() == b); + assert!(c.checked_add(&(-&b)).unwrap() == a); + assert!(a.checked_add(&(-&c)).unwrap() == (-&b)); + assert!(b.checked_add(&(-&c)).unwrap() == (-&a)); + assert!((-&a).checked_add(&(-&b)).unwrap() == (-&c)); + assert!(a.checked_add(&(-&a)).unwrap() == Zero::zero()); + } +} + +#[test] +fn test_checked_sub() { + for elm in SUM_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + + assert!(c.checked_sub(&a).unwrap() == b); + assert!(c.checked_sub(&b).unwrap() == a); + assert!((-&b).checked_sub(&a).unwrap() == (-&c)); + assert!((-&a).checked_sub(&b).unwrap() == (-&c)); + assert!(b.checked_sub(&(-&a)).unwrap() == c); + assert!(a.checked_sub(&(-&b)).unwrap() == c); + assert!((-&c).checked_sub(&(-&a)).unwrap() == (-&b)); + assert!(a.checked_sub(&a).unwrap() == Zero::zero()); + } +} + +#[test] +fn test_checked_mul() { + for elm in MUL_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + + assert!(a.checked_mul(&b).unwrap() == c); + assert!(b.checked_mul(&a).unwrap() == c); + + assert!((-&a).checked_mul(&b).unwrap() == -&c); + assert!((-&b).checked_mul(&a).unwrap() == -&c); + } + + for elm in DIV_REM_QUADRUPLES.iter() { + let (a_vec, b_vec, c_vec, d_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + let d = BigInt::from_slice(Plus, d_vec); + + assert!(a == b.checked_mul(&c).unwrap() + &d); + assert!(a == c.checked_mul(&b).unwrap() + &d); + } +} +#[test] +fn test_checked_div() { + for elm in MUL_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + + if !a.is_zero() { + assert!(c.checked_div(&a).unwrap() == b); + assert!((-&c).checked_div(&(-&a)).unwrap() == b); + assert!((-&c).checked_div(&a).unwrap() == -&b); + } + if !b.is_zero() { + assert!(c.checked_div(&b).unwrap() == a); + assert!((-&c).checked_div(&(-&b)).unwrap() == a); + assert!((-&c).checked_div(&b).unwrap() == -&a); + } + + assert!(c.checked_div(&Zero::zero()).is_none()); + assert!((-&c).checked_div(&Zero::zero()).is_none()); + } +} + +#[test] +fn test_gcd() { + fn check(a: isize, b: isize, c: isize) { + let big_a: BigInt = FromPrimitive::from_isize(a).unwrap(); + let big_b: BigInt = FromPrimitive::from_isize(b).unwrap(); + let big_c: BigInt = FromPrimitive::from_isize(c).unwrap(); + + assert_eq!(big_a.gcd(&big_b), big_c); + } + + check(10, 2, 2); + check(10, 3, 1); + check(0, 3, 3); + check(3, 3, 3); + check(56, 42, 14); + check(3, -3, 3); + check(-6, 3, 3); + check(-4, -2, 2); +} + +#[test] +fn test_lcm() { + fn check(a: isize, b: isize, c: isize) { + let big_a: BigInt = FromPrimitive::from_isize(a).unwrap(); + let big_b: BigInt = FromPrimitive::from_isize(b).unwrap(); + let big_c: BigInt = FromPrimitive::from_isize(c).unwrap(); + + assert_eq!(big_a.lcm(&big_b), big_c); + } + + check(0, 0, 0); + check(1, 0, 0); + check(0, 1, 0); + check(1, 1, 1); + check(-1, 1, 1); + check(1, -1, 1); + check(-1, -1, 1); + check(8, 9, 72); + check(11, 5, 55); +} + +#[test] +fn test_abs_sub() { + let zero: BigInt = Zero::zero(); + let one: BigInt = One::one(); + assert_eq!((-&one).abs_sub(&one), zero); + let one: BigInt = One::one(); + let zero: BigInt = Zero::zero(); + assert_eq!(one.abs_sub(&one), zero); + let one: BigInt = One::one(); + let zero: BigInt = Zero::zero(); + assert_eq!(one.abs_sub(&zero), one); + let one: BigInt = One::one(); + let two: BigInt = FromPrimitive::from_isize(2).unwrap(); + assert_eq!(one.abs_sub(&-&one), two); +} + +#[test] +fn test_from_str_radix() { + fn check(s: &str, ans: Option<isize>) { + let ans = ans.map(|n| { + let x: BigInt = FromPrimitive::from_isize(n).unwrap(); + x + }); + assert_eq!(BigInt::from_str_radix(s, 10).ok(), ans); + } + check("10", Some(10)); + check("1", Some(1)); + check("0", Some(0)); + check("-1", Some(-1)); + check("-10", Some(-10)); + check("+10", Some(10)); + check("--7", None); + check("++5", None); + check("+-9", None); + check("-+3", None); + check("Z", None); + check("_", None); + + // issue 10522, this hit an edge case that caused it to + // attempt to allocate a vector of size (-1u) == huge. + let x: BigInt = format!("1{}", repeat("0").take(36).collect::<String>()) + .parse() + .unwrap(); + let _y = x.to_string(); +} + +#[test] +fn test_lower_hex() { + let a = BigInt::parse_bytes(b"A", 16).unwrap(); + let hello = BigInt::parse_bytes("-22405534230753963835153736737".as_bytes(), 10).unwrap(); + + assert_eq!(format!("{:x}", a), "a"); + assert_eq!(format!("{:x}", hello), "-48656c6c6f20776f726c6421"); + assert_eq!(format!("{:♥>+#8x}", a), "♥♥♥♥+0xa"); +} + +#[test] +fn test_upper_hex() { + let a = BigInt::parse_bytes(b"A", 16).unwrap(); + let hello = BigInt::parse_bytes("-22405534230753963835153736737".as_bytes(), 10).unwrap(); + + assert_eq!(format!("{:X}", a), "A"); + assert_eq!(format!("{:X}", hello), "-48656C6C6F20776F726C6421"); + assert_eq!(format!("{:♥>+#8X}", a), "♥♥♥♥+0xA"); +} + +#[test] +fn test_binary() { + let a = BigInt::parse_bytes(b"A", 16).unwrap(); + let hello = BigInt::parse_bytes("-224055342307539".as_bytes(), 10).unwrap(); + + assert_eq!(format!("{:b}", a), "1010"); + assert_eq!( + format!("{:b}", hello), + "-110010111100011011110011000101101001100011010011" + ); + assert_eq!(format!("{:♥>+#8b}", a), "♥+0b1010"); +} + +#[test] +fn test_octal() { + let a = BigInt::parse_bytes(b"A", 16).unwrap(); + let hello = BigInt::parse_bytes("-22405534230753963835153736737".as_bytes(), 10).unwrap(); + + assert_eq!(format!("{:o}", a), "12"); + assert_eq!(format!("{:o}", hello), "-22062554330674403566756233062041"); + assert_eq!(format!("{:♥>+#8o}", a), "♥♥♥+0o12"); +} + +#[test] +fn test_display() { + let a = BigInt::parse_bytes(b"A", 16).unwrap(); + let hello = BigInt::parse_bytes("-22405534230753963835153736737".as_bytes(), 10).unwrap(); + + assert_eq!(format!("{}", a), "10"); + assert_eq!(format!("{}", hello), "-22405534230753963835153736737"); + assert_eq!(format!("{:♥>+#8}", a), "♥♥♥♥♥+10"); +} + +#[test] +fn test_neg() { + assert!(-BigInt::new(Plus, vec![1, 1, 1]) == BigInt::new(Minus, vec![1, 1, 1])); + assert!(-BigInt::new(Minus, vec![1, 1, 1]) == BigInt::new(Plus, vec![1, 1, 1])); + let zero: BigInt = Zero::zero(); + assert_eq!(-&zero, zero); +} + +#[test] +fn test_negative_shr() { + assert_eq!(BigInt::from(-1) >> 1, BigInt::from(-1)); + assert_eq!(BigInt::from(-2) >> 1, BigInt::from(-1)); + assert_eq!(BigInt::from(-3) >> 1, BigInt::from(-2)); + assert_eq!(BigInt::from(-3) >> 2, BigInt::from(-1)); +} + +#[test] +#[cfg(feature = "rand")] +fn test_random_shr() { + use rand::distributions::Standard; + use rand::Rng; + let mut rng = rand::thread_rng(); + + for p in rng.sample_iter::<i64, _>(&Standard).take(1000) { + let big = BigInt::from(p); + let bigger = &big << 1000; + assert_eq!(&bigger >> 1000, big); + for i in 0..64 { + let answer = BigInt::from(p >> i); + assert_eq!(&big >> i, answer); + assert_eq!(&bigger >> (1000 + i), answer); + } + } +} + +#[test] +fn test_iter_sum() { + let result: BigInt = FromPrimitive::from_isize(-1234567).unwrap(); + let data: Vec<BigInt> = vec![ + FromPrimitive::from_i32(-1000000).unwrap(), + FromPrimitive::from_i32(-200000).unwrap(), + FromPrimitive::from_i32(-30000).unwrap(), + FromPrimitive::from_i32(-4000).unwrap(), + FromPrimitive::from_i32(-500).unwrap(), + FromPrimitive::from_i32(-60).unwrap(), + FromPrimitive::from_i32(-7).unwrap(), + ]; + + assert_eq!(result, data.iter().sum()); + assert_eq!(result, data.into_iter().sum()); +} + +#[test] +fn test_iter_product() { + let data: Vec<BigInt> = vec![ + FromPrimitive::from_i32(1001).unwrap(), + FromPrimitive::from_i32(-1002).unwrap(), + FromPrimitive::from_i32(1003).unwrap(), + FromPrimitive::from_i32(-1004).unwrap(), + FromPrimitive::from_i32(1005).unwrap(), + ]; + let result = data.get(0).unwrap() + * data.get(1).unwrap() + * data.get(2).unwrap() + * data.get(3).unwrap() + * data.get(4).unwrap(); + + assert_eq!(result, data.iter().product()); + assert_eq!(result, data.into_iter().product()); +} + +#[test] +fn test_iter_sum_generic() { + let result: BigInt = FromPrimitive::from_isize(-1234567).unwrap(); + let data = vec![-1000000, -200000, -30000, -4000, -500, -60, -7]; + + assert_eq!(result, data.iter().sum()); + assert_eq!(result, data.into_iter().sum()); +} + +#[test] +fn test_iter_product_generic() { + let data = vec![1001, -1002, 1003, -1004, 1005]; + let result = data[0].to_bigint().unwrap() + * data[1].to_bigint().unwrap() + * data[2].to_bigint().unwrap() + * data[3].to_bigint().unwrap() + * data[4].to_bigint().unwrap(); + + assert_eq!(result, data.iter().product()); + assert_eq!(result, data.into_iter().product()); +} + +#[test] +fn test_pow() { + let one = BigInt::from(1i32); + let two = BigInt::from(2i32); + let four = BigInt::from(4i32); + let eight = BigInt::from(8i32); + let minus_two = BigInt::from(-2i32); + macro_rules! check { + ($t:ty) => { + assert_eq!(two.pow(0 as $t), one); + assert_eq!(two.pow(1 as $t), two); + assert_eq!(two.pow(2 as $t), four); + assert_eq!(two.pow(3 as $t), eight); + assert_eq!(two.pow(&(3 as $t)), eight); + assert_eq!(minus_two.pow(0 as $t), one, "-2^0"); + assert_eq!(minus_two.pow(1 as $t), minus_two, "-2^1"); + assert_eq!(minus_two.pow(2 as $t), four, "-2^2"); + assert_eq!(minus_two.pow(3 as $t), -&eight, "-2^3"); + }; + } + check!(u8); + check!(u16); + check!(u32); + check!(u64); + check!(usize); +} diff --git a/third_party/rust/num-bigint/tests/bigint_bitwise.rs b/third_party/rust/num-bigint/tests/bigint_bitwise.rs new file mode 100644 index 0000000000..cc0c493cb5 --- /dev/null +++ b/third_party/rust/num-bigint/tests/bigint_bitwise.rs @@ -0,0 +1,181 @@ +extern crate num_bigint; +extern crate num_traits; + +use num_bigint::{BigInt, Sign, ToBigInt}; +use num_traits::ToPrimitive; +use std::{i32, i64, u32}; + +enum ValueVec { + N, + P(&'static [u32]), + M(&'static [u32]), +} + +use ValueVec::*; + +impl ToBigInt for ValueVec { + fn to_bigint(&self) -> Option<BigInt> { + match self { + &N => Some(BigInt::from_slice(Sign::NoSign, &[])), + &P(s) => Some(BigInt::from_slice(Sign::Plus, s)), + &M(s) => Some(BigInt::from_slice(Sign::Minus, s)), + } + } +} + +// a, !a +const NOT_VALUES: &'static [(ValueVec, ValueVec)] = &[ + (N, M(&[1])), + (P(&[1]), M(&[2])), + (P(&[2]), M(&[3])), + (P(&[!0 - 2]), M(&[!0 - 1])), + (P(&[!0 - 1]), M(&[!0])), + (P(&[!0]), M(&[0, 1])), + (P(&[0, 1]), M(&[1, 1])), + (P(&[1, 1]), M(&[2, 1])), +]; + +// a, b, a & b, a | b, a ^ b +const BITWISE_VALUES: &'static [(ValueVec, ValueVec, ValueVec, ValueVec, ValueVec)] = &[ + (N, N, N, N, N), + (N, P(&[1]), N, P(&[1]), P(&[1])), + (N, P(&[!0]), N, P(&[!0]), P(&[!0])), + (N, P(&[0, 1]), N, P(&[0, 1]), P(&[0, 1])), + (N, M(&[1]), N, M(&[1]), M(&[1])), + (N, M(&[!0]), N, M(&[!0]), M(&[!0])), + (N, M(&[0, 1]), N, M(&[0, 1]), M(&[0, 1])), + (P(&[1]), P(&[!0]), P(&[1]), P(&[!0]), P(&[!0 - 1])), + (P(&[!0]), P(&[!0]), P(&[!0]), P(&[!0]), N), + (P(&[!0]), P(&[1, 1]), P(&[1]), P(&[!0, 1]), P(&[!0 - 1, 1])), + (P(&[1]), M(&[!0]), P(&[1]), M(&[!0]), M(&[0, 1])), + (P(&[!0]), M(&[1]), P(&[!0]), M(&[1]), M(&[0, 1])), + (P(&[!0]), M(&[!0]), P(&[1]), M(&[1]), M(&[2])), + (P(&[!0]), M(&[1, 1]), P(&[!0]), M(&[1, 1]), M(&[0, 2])), + (P(&[1, 1]), M(&[!0]), P(&[1, 1]), M(&[!0]), M(&[0, 2])), + (M(&[1]), M(&[!0]), M(&[!0]), M(&[1]), P(&[!0 - 1])), + (M(&[!0]), M(&[!0]), M(&[!0]), M(&[!0]), N), + (M(&[!0]), M(&[1, 1]), M(&[!0, 1]), M(&[1]), P(&[!0 - 1, 1])), +]; + +const I32_MIN: i64 = i32::MIN as i64; +const I32_MAX: i64 = i32::MAX as i64; +const U32_MAX: i64 = u32::MAX as i64; + +// some corner cases +const I64_VALUES: &'static [i64] = &[ + i64::MIN, + i64::MIN + 1, + i64::MIN + 2, + i64::MIN + 3, + -U32_MAX - 3, + -U32_MAX - 2, + -U32_MAX - 1, + -U32_MAX, + -U32_MAX + 1, + -U32_MAX + 2, + -U32_MAX + 3, + I32_MIN - 3, + I32_MIN - 2, + I32_MIN - 1, + I32_MIN, + I32_MIN + 1, + I32_MIN + 2, + I32_MIN + 3, + -3, + -2, + -1, + 0, + 1, + 2, + 3, + I32_MAX - 3, + I32_MAX - 2, + I32_MAX - 1, + I32_MAX, + I32_MAX + 1, + I32_MAX + 2, + I32_MAX + 3, + U32_MAX - 3, + U32_MAX - 2, + U32_MAX - 1, + U32_MAX, + U32_MAX + 1, + U32_MAX + 2, + U32_MAX + 3, + i64::MAX - 3, + i64::MAX - 2, + i64::MAX - 1, + i64::MAX, +]; + +#[test] +fn test_not() { + for &(ref a, ref not) in NOT_VALUES.iter() { + let a = a.to_bigint().unwrap(); + let not = not.to_bigint().unwrap(); + + // sanity check for tests that fit in i64 + if let (Some(prim_a), Some(prim_not)) = (a.to_i64(), not.to_i64()) { + assert_eq!(!prim_a, prim_not); + } + + assert_eq!(!a.clone(), not, "!{:x}", a); + assert_eq!(!not.clone(), a, "!{:x}", not); + } +} + +#[test] +fn test_not_i64() { + for &prim_a in I64_VALUES.iter() { + let a = prim_a.to_bigint().unwrap(); + let not = (!prim_a).to_bigint().unwrap(); + assert_eq!(!a.clone(), not, "!{:x}", a); + } +} + +#[test] +fn test_bitwise() { + for &(ref a, ref b, ref and, ref or, ref xor) in BITWISE_VALUES.iter() { + let a = a.to_bigint().unwrap(); + let b = b.to_bigint().unwrap(); + let and = and.to_bigint().unwrap(); + let or = or.to_bigint().unwrap(); + let xor = xor.to_bigint().unwrap(); + + // sanity check for tests that fit in i64 + if let (Some(prim_a), Some(prim_b)) = (a.to_i64(), b.to_i64()) { + if let Some(prim_and) = and.to_i64() { + assert_eq!(prim_a & prim_b, prim_and); + } + if let Some(prim_or) = or.to_i64() { + assert_eq!(prim_a | prim_b, prim_or); + } + if let Some(prim_xor) = xor.to_i64() { + assert_eq!(prim_a ^ prim_b, prim_xor); + } + } + + assert_eq!(a.clone() & &b, and, "{:x} & {:x}", a, b); + assert_eq!(b.clone() & &a, and, "{:x} & {:x}", b, a); + assert_eq!(a.clone() | &b, or, "{:x} | {:x}", a, b); + assert_eq!(b.clone() | &a, or, "{:x} | {:x}", b, a); + assert_eq!(a.clone() ^ &b, xor, "{:x} ^ {:x}", a, b); + assert_eq!(b.clone() ^ &a, xor, "{:x} ^ {:x}", b, a); + } +} + +#[test] +fn test_bitwise_i64() { + for &prim_a in I64_VALUES.iter() { + let a = prim_a.to_bigint().unwrap(); + for &prim_b in I64_VALUES.iter() { + let b = prim_b.to_bigint().unwrap(); + let and = (prim_a & prim_b).to_bigint().unwrap(); + let or = (prim_a | prim_b).to_bigint().unwrap(); + let xor = (prim_a ^ prim_b).to_bigint().unwrap(); + assert_eq!(a.clone() & &b, and, "{:x} & {:x}", a, b); + assert_eq!(a.clone() | &b, or, "{:x} | {:x}", a, b); + assert_eq!(a.clone() ^ &b, xor, "{:x} ^ {:x}", a, b); + } + } +} diff --git a/third_party/rust/num-bigint/tests/bigint_scalar.rs b/third_party/rust/num-bigint/tests/bigint_scalar.rs new file mode 100644 index 0000000000..ae9a6d7aa2 --- /dev/null +++ b/third_party/rust/num-bigint/tests/bigint_scalar.rs @@ -0,0 +1,145 @@ +extern crate num_bigint; +extern crate num_traits; + +use num_bigint::BigInt; +use num_bigint::Sign::Plus; +use num_traits::{Signed, ToPrimitive, Zero}; + +use std::ops::Neg; + +mod consts; +use consts::*; + +#[macro_use] +mod macros; + +#[test] +fn test_scalar_add() { + fn check(x: &BigInt, y: &BigInt, z: &BigInt) { + let (x, y, z) = (x.clone(), y.clone(), z.clone()); + assert_signed_scalar_op!(x + y == z); + } + + for elm in SUM_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + let (na, nb, nc) = (-&a, -&b, -&c); + + check(&a, &b, &c); + check(&b, &a, &c); + check(&c, &na, &b); + check(&c, &nb, &a); + check(&a, &nc, &nb); + check(&b, &nc, &na); + check(&na, &nb, &nc); + check(&a, &na, &Zero::zero()); + } +} + +#[test] +fn test_scalar_sub() { + fn check(x: &BigInt, y: &BigInt, z: &BigInt) { + let (x, y, z) = (x.clone(), y.clone(), z.clone()); + assert_signed_scalar_op!(x - y == z); + } + + for elm in SUM_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + let (na, nb, nc) = (-&a, -&b, -&c); + + check(&c, &a, &b); + check(&c, &b, &a); + check(&nb, &a, &nc); + check(&na, &b, &nc); + check(&b, &na, &c); + check(&a, &nb, &c); + check(&nc, &na, &nb); + check(&a, &a, &Zero::zero()); + } +} + +#[test] +fn test_scalar_mul() { + fn check(x: &BigInt, y: &BigInt, z: &BigInt) { + let (x, y, z) = (x.clone(), y.clone(), z.clone()); + assert_signed_scalar_op!(x * y == z); + } + + for elm in MUL_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + let (na, nb, nc) = (-&a, -&b, -&c); + + check(&a, &b, &c); + check(&b, &a, &c); + check(&na, &nb, &c); + + check(&na, &b, &nc); + check(&nb, &a, &nc); + } +} + +#[test] +fn test_scalar_div_rem() { + fn check_sub(a: &BigInt, b: u32, ans_q: &BigInt, ans_r: &BigInt) { + let (q, r) = (a / b, a % b); + if !r.is_zero() { + assert_eq!(r.sign(), a.sign()); + } + assert!(r.abs() <= From::from(b)); + assert!(*a == b * &q + &r); + assert!(q == *ans_q); + assert!(r == *ans_r); + + let (a, b, ans_q, ans_r) = (a.clone(), b.clone(), ans_q.clone(), ans_r.clone()); + assert_op!(a / b == ans_q); + assert_op!(a % b == ans_r); + + if b <= i32::max_value() as u32 { + let nb = -(b as i32); + assert_op!(a / nb == -ans_q.clone()); + assert_op!(a % nb == ans_r); + } + } + + fn check(a: &BigInt, b: u32, q: &BigInt, r: &BigInt) { + check_sub(a, b, q, r); + check_sub(&a.neg(), b, &q.neg(), &r.neg()); + } + + for elm in MUL_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + + if a_vec.len() == 1 && a_vec[0] != 0 { + let a = a_vec[0]; + check(&c, a, &b, &Zero::zero()); + } + + if b_vec.len() == 1 && b_vec[0] != 0 { + let b = b_vec[0]; + check(&c, b, &a, &Zero::zero()); + } + } + + for elm in DIV_REM_QUADRUPLES.iter() { + let (a_vec, b_vec, c_vec, d_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let c = BigInt::from_slice(Plus, c_vec); + let d = BigInt::from_slice(Plus, d_vec); + + if b_vec.len() == 1 && b_vec[0] != 0 { + let b = b_vec[0]; + check(&a, b, &c, &d); + } + } +} diff --git a/third_party/rust/num-bigint/tests/biguint.rs b/third_party/rust/num-bigint/tests/biguint.rs new file mode 100644 index 0000000000..1e23aa17f9 --- /dev/null +++ b/third_party/rust/num-bigint/tests/biguint.rs @@ -0,0 +1,1713 @@ +extern crate num_bigint; +extern crate num_integer; +extern crate num_traits; + +use num_bigint::Sign::Plus; +use num_bigint::{BigInt, ToBigInt}; +use num_bigint::{BigUint, ToBigUint}; +use num_integer::Integer; + +use std::cmp::Ordering::{Equal, Greater, Less}; +use std::collections::hash_map::RandomState; +use std::hash::{BuildHasher, Hash, Hasher}; +use std::i64; +use std::iter::repeat; +use std::str::FromStr; +use std::{f32, f64}; +#[cfg(has_i128)] +use std::{i128, u128}; +use std::{u16, u32, u64, u8, usize}; + +use num_traits::{ + CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, Float, FromPrimitive, Num, One, Pow, + ToPrimitive, Zero, +}; + +mod consts; +use consts::*; + +#[macro_use] +mod macros; + +#[test] +fn test_from_bytes_be() { + fn check(s: &str, result: &str) { + assert_eq!( + BigUint::from_bytes_be(s.as_bytes()), + BigUint::parse_bytes(result.as_bytes(), 10).unwrap() + ); + } + check("A", "65"); + check("AA", "16705"); + check("AB", "16706"); + check("Hello world!", "22405534230753963835153736737"); + assert_eq!(BigUint::from_bytes_be(&[]), Zero::zero()); +} + +#[test] +fn test_to_bytes_be() { + fn check(s: &str, result: &str) { + let b = BigUint::parse_bytes(result.as_bytes(), 10).unwrap(); + assert_eq!(b.to_bytes_be(), s.as_bytes()); + } + check("A", "65"); + check("AA", "16705"); + check("AB", "16706"); + check("Hello world!", "22405534230753963835153736737"); + let b: BigUint = Zero::zero(); + assert_eq!(b.to_bytes_be(), [0]); + + // Test with leading/trailing zero bytes and a full BigDigit of value 0 + let b = BigUint::from_str_radix("00010000000000000200", 16).unwrap(); + assert_eq!(b.to_bytes_be(), [1, 0, 0, 0, 0, 0, 0, 2, 0]); +} + +#[test] +fn test_from_bytes_le() { + fn check(s: &str, result: &str) { + assert_eq!( + BigUint::from_bytes_le(s.as_bytes()), + BigUint::parse_bytes(result.as_bytes(), 10).unwrap() + ); + } + check("A", "65"); + check("AA", "16705"); + check("BA", "16706"); + check("!dlrow olleH", "22405534230753963835153736737"); + assert_eq!(BigUint::from_bytes_le(&[]), Zero::zero()); +} + +#[test] +fn test_to_bytes_le() { + fn check(s: &str, result: &str) { + let b = BigUint::parse_bytes(result.as_bytes(), 10).unwrap(); + assert_eq!(b.to_bytes_le(), s.as_bytes()); + } + check("A", "65"); + check("AA", "16705"); + check("BA", "16706"); + check("!dlrow olleH", "22405534230753963835153736737"); + let b: BigUint = Zero::zero(); + assert_eq!(b.to_bytes_le(), [0]); + + // Test with leading/trailing zero bytes and a full BigDigit of value 0 + let b = BigUint::from_str_radix("00010000000000000200", 16).unwrap(); + assert_eq!(b.to_bytes_le(), [0, 2, 0, 0, 0, 0, 0, 0, 1]); +} + +#[test] +fn test_cmp() { + let data: [&[_]; 7] = [&[], &[1], &[2], &[!0], &[0, 1], &[2, 1], &[1, 1, 1]]; + let data: Vec<BigUint> = data.iter().map(|v| BigUint::from_slice(*v)).collect(); + for (i, ni) in data.iter().enumerate() { + for (j0, nj) in data[i..].iter().enumerate() { + let j = j0 + i; + if i == j { + assert_eq!(ni.cmp(nj), Equal); + assert_eq!(nj.cmp(ni), Equal); + assert_eq!(ni, nj); + assert!(!(ni != nj)); + assert!(ni <= nj); + assert!(ni >= nj); + assert!(!(ni < nj)); + assert!(!(ni > nj)); + } else { + assert_eq!(ni.cmp(nj), Less); + assert_eq!(nj.cmp(ni), Greater); + + assert!(!(ni == nj)); + assert!(ni != nj); + + assert!(ni <= nj); + assert!(!(ni >= nj)); + assert!(ni < nj); + assert!(!(ni > nj)); + + assert!(!(nj <= ni)); + assert!(nj >= ni); + assert!(!(nj < ni)); + assert!(nj > ni); + } + } + } +} + +fn hash<T: Hash>(x: &T) -> u64 { + let mut hasher = <RandomState as BuildHasher>::Hasher::new(); + x.hash(&mut hasher); + hasher.finish() +} + +#[test] +fn test_hash() { + use hash; + + let a = BigUint::new(vec![]); + let b = BigUint::new(vec![0]); + let c = BigUint::new(vec![1]); + let d = BigUint::new(vec![1, 0, 0, 0, 0, 0]); + let e = BigUint::new(vec![0, 0, 0, 0, 0, 1]); + assert!(hash(&a) == hash(&b)); + assert!(hash(&b) != hash(&c)); + assert!(hash(&c) == hash(&d)); + assert!(hash(&d) != hash(&e)); +} + +// LEFT, RIGHT, AND, OR, XOR +const BIT_TESTS: &'static [( + &'static [u32], + &'static [u32], + &'static [u32], + &'static [u32], + &'static [u32], +)] = &[ + (&[], &[], &[], &[], &[]), + (&[1, 0, 1], &[1, 1], &[1], &[1, 1, 1], &[0, 1, 1]), + (&[1, 0, 1], &[0, 1, 1], &[0, 0, 1], &[1, 1, 1], &[1, 1]), + ( + &[268, 482, 17], + &[964, 54], + &[260, 34], + &[972, 502, 17], + &[712, 468, 17], + ), +]; + +#[test] +fn test_bitand() { + for elm in BIT_TESTS { + let (a_vec, b_vec, c_vec, _, _) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + assert_op!(a & b == c); + assert_op!(b & a == c); + assert_assign_op!(a &= b == c); + assert_assign_op!(b &= a == c); + } +} + +#[test] +fn test_bitor() { + for elm in BIT_TESTS { + let (a_vec, b_vec, _, c_vec, _) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + assert_op!(a | b == c); + assert_op!(b | a == c); + assert_assign_op!(a |= b == c); + assert_assign_op!(b |= a == c); + } +} + +#[test] +fn test_bitxor() { + for elm in BIT_TESTS { + let (a_vec, b_vec, _, _, c_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + assert_op!(a ^ b == c); + assert_op!(b ^ a == c); + assert_op!(a ^ c == b); + assert_op!(c ^ a == b); + assert_op!(b ^ c == a); + assert_op!(c ^ b == a); + assert_assign_op!(a ^= b == c); + assert_assign_op!(b ^= a == c); + assert_assign_op!(a ^= c == b); + assert_assign_op!(c ^= a == b); + assert_assign_op!(b ^= c == a); + assert_assign_op!(c ^= b == a); + } +} + +#[test] +fn test_shl() { + fn check(s: &str, shift: usize, ans: &str) { + let opt_biguint = BigUint::from_str_radix(s, 16).ok(); + let mut bu_assign = opt_biguint.unwrap(); + let bu = (bu_assign.clone() << shift).to_str_radix(16); + assert_eq!(bu, ans); + bu_assign <<= shift; + assert_eq!(bu_assign.to_str_radix(16), ans); + } + + check("0", 3, "0"); + check("1", 3, "8"); + + check( + "1\ + 0000\ + 0000\ + 0000\ + 0001\ + 0000\ + 0000\ + 0000\ + 0001", + 3, + "8\ + 0000\ + 0000\ + 0000\ + 0008\ + 0000\ + 0000\ + 0000\ + 0008", + ); + check( + "1\ + 0000\ + 0001\ + 0000\ + 0001", + 2, + "4\ + 0000\ + 0004\ + 0000\ + 0004", + ); + check( + "1\ + 0001\ + 0001", + 1, + "2\ + 0002\ + 0002", + ); + + check( + "\ + 4000\ + 0000\ + 0000\ + 0000", + 3, + "2\ + 0000\ + 0000\ + 0000\ + 0000", + ); + check( + "4000\ + 0000", + 2, + "1\ + 0000\ + 0000", + ); + check( + "4000", + 2, + "1\ + 0000", + ); + + check( + "4000\ + 0000\ + 0000\ + 0000", + 67, + "2\ + 0000\ + 0000\ + 0000\ + 0000\ + 0000\ + 0000\ + 0000\ + 0000", + ); + check( + "4000\ + 0000", + 35, + "2\ + 0000\ + 0000\ + 0000\ + 0000", + ); + check( + "4000", + 19, + "2\ + 0000\ + 0000", + ); + + check( + "fedc\ + ba98\ + 7654\ + 3210\ + fedc\ + ba98\ + 7654\ + 3210", + 4, + "f\ + edcb\ + a987\ + 6543\ + 210f\ + edcb\ + a987\ + 6543\ + 2100", + ); + check( + "88887777666655554444333322221111", + 16, + "888877776666555544443333222211110000", + ); +} + +#[test] +fn test_shr() { + fn check(s: &str, shift: usize, ans: &str) { + let opt_biguint = BigUint::from_str_radix(s, 16).ok(); + let mut bu_assign = opt_biguint.unwrap(); + let bu = (bu_assign.clone() >> shift).to_str_radix(16); + assert_eq!(bu, ans); + bu_assign >>= shift; + assert_eq!(bu_assign.to_str_radix(16), ans); + } + + check("0", 3, "0"); + check("f", 3, "1"); + + check( + "1\ + 0000\ + 0000\ + 0000\ + 0001\ + 0000\ + 0000\ + 0000\ + 0001", + 3, + "2000\ + 0000\ + 0000\ + 0000\ + 2000\ + 0000\ + 0000\ + 0000", + ); + check( + "1\ + 0000\ + 0001\ + 0000\ + 0001", + 2, + "4000\ + 0000\ + 4000\ + 0000", + ); + check( + "1\ + 0001\ + 0001", + 1, + "8000\ + 8000", + ); + + check( + "2\ + 0000\ + 0000\ + 0000\ + 0001\ + 0000\ + 0000\ + 0000\ + 0001", + 67, + "4000\ + 0000\ + 0000\ + 0000", + ); + check( + "2\ + 0000\ + 0001\ + 0000\ + 0001", + 35, + "4000\ + 0000", + ); + check( + "2\ + 0001\ + 0001", + 19, + "4000", + ); + + check( + "1\ + 0000\ + 0000\ + 0000\ + 0000", + 1, + "8000\ + 0000\ + 0000\ + 0000", + ); + check( + "1\ + 0000\ + 0000", + 1, + "8000\ + 0000", + ); + check( + "1\ + 0000", + 1, + "8000", + ); + check( + "f\ + edcb\ + a987\ + 6543\ + 210f\ + edcb\ + a987\ + 6543\ + 2100", + 4, + "fedc\ + ba98\ + 7654\ + 3210\ + fedc\ + ba98\ + 7654\ + 3210", + ); + + check( + "888877776666555544443333222211110000", + 16, + "88887777666655554444333322221111", + ); +} + +// `DoubleBigDigit` size dependent +#[test] +fn test_convert_i64() { + fn check(b1: BigUint, i: i64) { + let b2: BigUint = FromPrimitive::from_i64(i).unwrap(); + assert_eq!(b1, b2); + assert_eq!(b1.to_i64().unwrap(), i); + } + + check(Zero::zero(), 0); + check(One::one(), 1); + check(i64::MAX.to_biguint().unwrap(), i64::MAX); + + check(BigUint::new(vec![]), 0); + check(BigUint::new(vec![1]), 1); + check(BigUint::new(vec![N1]), (1 << 32) - 1); + check(BigUint::new(vec![0, 1]), 1 << 32); + check(BigUint::new(vec![N1, N1 >> 1]), i64::MAX); + + assert_eq!(i64::MIN.to_biguint(), None); + assert_eq!(BigUint::new(vec![N1, N1]).to_i64(), None); + assert_eq!(BigUint::new(vec![0, 0, 1]).to_i64(), None); + assert_eq!(BigUint::new(vec![N1, N1, N1]).to_i64(), None); +} + +#[test] +#[cfg(has_i128)] +fn test_convert_i128() { + fn check(b1: BigUint, i: i128) { + let b2: BigUint = FromPrimitive::from_i128(i).unwrap(); + assert_eq!(b1, b2); + assert_eq!(b1.to_i128().unwrap(), i); + } + + check(Zero::zero(), 0); + check(One::one(), 1); + check(i128::MAX.to_biguint().unwrap(), i128::MAX); + + check(BigUint::new(vec![]), 0); + check(BigUint::new(vec![1]), 1); + check(BigUint::new(vec![N1]), (1 << 32) - 1); + check(BigUint::new(vec![0, 1]), 1 << 32); + check(BigUint::new(vec![N1, N1, N1, N1 >> 1]), i128::MAX); + + assert_eq!(i128::MIN.to_biguint(), None); + assert_eq!(BigUint::new(vec![N1, N1, N1, N1]).to_i128(), None); + assert_eq!(BigUint::new(vec![0, 0, 0, 0, 1]).to_i128(), None); + assert_eq!(BigUint::new(vec![N1, N1, N1, N1, N1]).to_i128(), None); +} + +// `DoubleBigDigit` size dependent +#[test] +fn test_convert_u64() { + fn check(b1: BigUint, u: u64) { + let b2: BigUint = FromPrimitive::from_u64(u).unwrap(); + assert_eq!(b1, b2); + assert_eq!(b1.to_u64().unwrap(), u); + } + + check(Zero::zero(), 0); + check(One::one(), 1); + check(u64::MIN.to_biguint().unwrap(), u64::MIN); + check(u64::MAX.to_biguint().unwrap(), u64::MAX); + + check(BigUint::new(vec![]), 0); + check(BigUint::new(vec![1]), 1); + check(BigUint::new(vec![N1]), (1 << 32) - 1); + check(BigUint::new(vec![0, 1]), 1 << 32); + check(BigUint::new(vec![N1, N1]), u64::MAX); + + assert_eq!(BigUint::new(vec![0, 0, 1]).to_u64(), None); + assert_eq!(BigUint::new(vec![N1, N1, N1]).to_u64(), None); +} + +#[test] +#[cfg(has_i128)] +fn test_convert_u128() { + fn check(b1: BigUint, u: u128) { + let b2: BigUint = FromPrimitive::from_u128(u).unwrap(); + assert_eq!(b1, b2); + assert_eq!(b1.to_u128().unwrap(), u); + } + + check(Zero::zero(), 0); + check(One::one(), 1); + check(u128::MIN.to_biguint().unwrap(), u128::MIN); + check(u128::MAX.to_biguint().unwrap(), u128::MAX); + + check(BigUint::new(vec![]), 0); + check(BigUint::new(vec![1]), 1); + check(BigUint::new(vec![N1]), (1 << 32) - 1); + check(BigUint::new(vec![0, 1]), 1 << 32); + check(BigUint::new(vec![N1, N1, N1, N1]), u128::MAX); + + assert_eq!(BigUint::new(vec![0, 0, 0, 0, 1]).to_u128(), None); + assert_eq!(BigUint::new(vec![N1, N1, N1, N1, N1]).to_u128(), None); +} + +#[test] +fn test_convert_f32() { + fn check(b1: &BigUint, f: f32) { + let b2 = BigUint::from_f32(f).unwrap(); + assert_eq!(b1, &b2); + assert_eq!(b1.to_f32().unwrap(), f); + } + + check(&BigUint::zero(), 0.0); + check(&BigUint::one(), 1.0); + check(&BigUint::from(u16::MAX), 2.0.powi(16) - 1.0); + check(&BigUint::from(1u64 << 32), 2.0.powi(32)); + check(&BigUint::from_slice(&[0, 0, 1]), 2.0.powi(64)); + check( + &((BigUint::one() << 100) + (BigUint::one() << 123)), + 2.0.powi(100) + 2.0.powi(123), + ); + check(&(BigUint::one() << 127), 2.0.powi(127)); + check(&(BigUint::from((1u64 << 24) - 1) << (128 - 24)), f32::MAX); + + // keeping all 24 digits with the bits at different offsets to the BigDigits + let x: u32 = 0b00000000101111011111011011011101; + let mut f = x as f32; + let mut b = BigUint::from(x); + for _ in 0..64 { + check(&b, f); + f *= 2.0; + b = b << 1; + } + + // this number when rounded to f64 then f32 isn't the same as when rounded straight to f32 + let n: u64 = 0b0000000000111111111111111111111111011111111111111111111111111111; + assert!((n as f64) as f32 != n as f32); + assert_eq!(BigUint::from(n).to_f32(), Some(n as f32)); + + // test rounding up with the bits at different offsets to the BigDigits + let mut f = ((1u64 << 25) - 1) as f32; + let mut b = BigUint::from(1u64 << 25); + for _ in 0..64 { + assert_eq!(b.to_f32(), Some(f)); + f *= 2.0; + b = b << 1; + } + + // rounding + assert_eq!(BigUint::from_f32(-1.0), None); + assert_eq!(BigUint::from_f32(-0.99999), Some(BigUint::zero())); + assert_eq!(BigUint::from_f32(-0.5), Some(BigUint::zero())); + assert_eq!(BigUint::from_f32(-0.0), Some(BigUint::zero())); + assert_eq!( + BigUint::from_f32(f32::MIN_POSITIVE / 2.0), + Some(BigUint::zero()) + ); + assert_eq!(BigUint::from_f32(f32::MIN_POSITIVE), Some(BigUint::zero())); + assert_eq!(BigUint::from_f32(0.5), Some(BigUint::zero())); + assert_eq!(BigUint::from_f32(0.99999), Some(BigUint::zero())); + assert_eq!(BigUint::from_f32(f32::consts::E), Some(BigUint::from(2u32))); + assert_eq!( + BigUint::from_f32(f32::consts::PI), + Some(BigUint::from(3u32)) + ); + + // special float values + assert_eq!(BigUint::from_f32(f32::NAN), None); + assert_eq!(BigUint::from_f32(f32::INFINITY), None); + assert_eq!(BigUint::from_f32(f32::NEG_INFINITY), None); + assert_eq!(BigUint::from_f32(f32::MIN), None); + + // largest BigUint that will round to a finite f32 value + let big_num = (BigUint::one() << 128) - BigUint::one() - (BigUint::one() << (128 - 25)); + assert_eq!(big_num.to_f32(), Some(f32::MAX)); + assert_eq!((big_num + BigUint::one()).to_f32(), None); + + assert_eq!(((BigUint::one() << 128) - BigUint::one()).to_f32(), None); + assert_eq!((BigUint::one() << 128).to_f32(), None); +} + +#[test] +fn test_convert_f64() { + fn check(b1: &BigUint, f: f64) { + let b2 = BigUint::from_f64(f).unwrap(); + assert_eq!(b1, &b2); + assert_eq!(b1.to_f64().unwrap(), f); + } + + check(&BigUint::zero(), 0.0); + check(&BigUint::one(), 1.0); + check(&BigUint::from(u32::MAX), 2.0.powi(32) - 1.0); + check(&BigUint::from(1u64 << 32), 2.0.powi(32)); + check(&BigUint::from_slice(&[0, 0, 1]), 2.0.powi(64)); + check( + &((BigUint::one() << 100) + (BigUint::one() << 152)), + 2.0.powi(100) + 2.0.powi(152), + ); + check(&(BigUint::one() << 1023), 2.0.powi(1023)); + check(&(BigUint::from((1u64 << 53) - 1) << (1024 - 53)), f64::MAX); + + // keeping all 53 digits with the bits at different offsets to the BigDigits + let x: u64 = 0b0000000000011110111110110111111101110111101111011111011011011101; + let mut f = x as f64; + let mut b = BigUint::from(x); + for _ in 0..128 { + check(&b, f); + f *= 2.0; + b = b << 1; + } + + // test rounding up with the bits at different offsets to the BigDigits + let mut f = ((1u64 << 54) - 1) as f64; + let mut b = BigUint::from(1u64 << 54); + for _ in 0..128 { + assert_eq!(b.to_f64(), Some(f)); + f *= 2.0; + b = b << 1; + } + + // rounding + assert_eq!(BigUint::from_f64(-1.0), None); + assert_eq!(BigUint::from_f64(-0.99999), Some(BigUint::zero())); + assert_eq!(BigUint::from_f64(-0.5), Some(BigUint::zero())); + assert_eq!(BigUint::from_f64(-0.0), Some(BigUint::zero())); + assert_eq!( + BigUint::from_f64(f64::MIN_POSITIVE / 2.0), + Some(BigUint::zero()) + ); + assert_eq!(BigUint::from_f64(f64::MIN_POSITIVE), Some(BigUint::zero())); + assert_eq!(BigUint::from_f64(0.5), Some(BigUint::zero())); + assert_eq!(BigUint::from_f64(0.99999), Some(BigUint::zero())); + assert_eq!(BigUint::from_f64(f64::consts::E), Some(BigUint::from(2u32))); + assert_eq!( + BigUint::from_f64(f64::consts::PI), + Some(BigUint::from(3u32)) + ); + + // special float values + assert_eq!(BigUint::from_f64(f64::NAN), None); + assert_eq!(BigUint::from_f64(f64::INFINITY), None); + assert_eq!(BigUint::from_f64(f64::NEG_INFINITY), None); + assert_eq!(BigUint::from_f64(f64::MIN), None); + + // largest BigUint that will round to a finite f64 value + let big_num = (BigUint::one() << 1024) - BigUint::one() - (BigUint::one() << (1024 - 54)); + assert_eq!(big_num.to_f64(), Some(f64::MAX)); + assert_eq!((big_num + BigUint::one()).to_f64(), None); + + assert_eq!(((BigInt::one() << 1024) - BigInt::one()).to_f64(), None); + assert_eq!((BigUint::one() << 1024).to_f64(), None); +} + +#[test] +fn test_convert_to_bigint() { + fn check(n: BigUint, ans: BigInt) { + assert_eq!(n.to_bigint().unwrap(), ans); + assert_eq!(n.to_bigint().unwrap().to_biguint().unwrap(), n); + } + check(Zero::zero(), Zero::zero()); + check( + BigUint::new(vec![1, 2, 3]), + BigInt::from_biguint(Plus, BigUint::new(vec![1, 2, 3])), + ); +} + +#[test] +fn test_convert_from_uint() { + macro_rules! check { + ($ty:ident, $max:expr) => { + assert_eq!(BigUint::from($ty::zero()), BigUint::zero()); + assert_eq!(BigUint::from($ty::one()), BigUint::one()); + assert_eq!(BigUint::from($ty::MAX - $ty::one()), $max - BigUint::one()); + assert_eq!(BigUint::from($ty::MAX), $max); + }; + } + + check!(u8, BigUint::from_slice(&[u8::MAX as u32])); + check!(u16, BigUint::from_slice(&[u16::MAX as u32])); + check!(u32, BigUint::from_slice(&[u32::MAX])); + check!(u64, BigUint::from_slice(&[u32::MAX, u32::MAX])); + #[cfg(has_i128)] + check!( + u128, + BigUint::from_slice(&[u32::MAX, u32::MAX, u32::MAX, u32::MAX]) + ); + check!(usize, BigUint::from(usize::MAX as u64)); +} + +#[test] +fn test_add() { + for elm in SUM_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + assert_op!(a + b == c); + assert_op!(b + a == c); + assert_assign_op!(a += b == c); + assert_assign_op!(b += a == c); + } +} + +#[test] +fn test_sub() { + for elm in SUM_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + assert_op!(c - a == b); + assert_op!(c - b == a); + assert_assign_op!(c -= a == b); + assert_assign_op!(c -= b == a); + } +} + +#[test] +#[should_panic] +fn test_sub_fail_on_underflow() { + let (a, b): (BigUint, BigUint) = (Zero::zero(), One::one()); + let _ = a - b; +} + +#[test] +fn test_mul() { + for elm in MUL_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + assert_op!(a * b == c); + assert_op!(b * a == c); + assert_assign_op!(a *= b == c); + assert_assign_op!(b *= a == c); + } + + for elm in DIV_REM_QUADRUPLES.iter() { + let (a_vec, b_vec, c_vec, d_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + let d = BigUint::from_slice(d_vec); + + assert!(a == &b * &c + &d); + assert!(a == &c * &b + &d); + } +} + +#[test] +fn test_div_rem() { + for elm in MUL_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + if !a.is_zero() { + assert_op!(c / a == b); + assert_op!(c % a == Zero::zero()); + assert_assign_op!(c /= a == b); + assert_assign_op!(c %= a == Zero::zero()); + assert_eq!(c.div_rem(&a), (b.clone(), Zero::zero())); + } + if !b.is_zero() { + assert_op!(c / b == a); + assert_op!(c % b == Zero::zero()); + assert_assign_op!(c /= b == a); + assert_assign_op!(c %= b == Zero::zero()); + assert_eq!(c.div_rem(&b), (a.clone(), Zero::zero())); + } + } + + for elm in DIV_REM_QUADRUPLES.iter() { + let (a_vec, b_vec, c_vec, d_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + let d = BigUint::from_slice(d_vec); + + if !b.is_zero() { + assert_op!(a / b == c); + assert_op!(a % b == d); + assert_assign_op!(a /= b == c); + assert_assign_op!(a %= b == d); + assert!(a.div_rem(&b) == (c, d)); + } + } +} + +#[test] +fn test_checked_add() { + for elm in SUM_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + assert!(a.checked_add(&b).unwrap() == c); + assert!(b.checked_add(&a).unwrap() == c); + } +} + +#[test] +fn test_checked_sub() { + for elm in SUM_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + assert!(c.checked_sub(&a).unwrap() == b); + assert!(c.checked_sub(&b).unwrap() == a); + + if a > c { + assert!(a.checked_sub(&c).is_none()); + } + if b > c { + assert!(b.checked_sub(&c).is_none()); + } + } +} + +#[test] +fn test_checked_mul() { + for elm in MUL_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + assert!(a.checked_mul(&b).unwrap() == c); + assert!(b.checked_mul(&a).unwrap() == c); + } + + for elm in DIV_REM_QUADRUPLES.iter() { + let (a_vec, b_vec, c_vec, d_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + let d = BigUint::from_slice(d_vec); + + assert!(a == b.checked_mul(&c).unwrap() + &d); + assert!(a == c.checked_mul(&b).unwrap() + &d); + } +} + +#[test] +fn test_mul_overflow() { + /* Test for issue #187 - overflow due to mac3 incorrectly sizing temporary */ + let s = "531137992816767098689588206552468627329593117727031923199444138200403559860852242739162502232636710047537552105951370000796528760829212940754539968588340162273730474622005920097370111"; + let a: BigUint = s.parse().unwrap(); + let b = a.clone(); + let _ = a.checked_mul(&b); +} + +#[test] +fn test_checked_div() { + for elm in MUL_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + if !a.is_zero() { + assert!(c.checked_div(&a).unwrap() == b); + } + if !b.is_zero() { + assert!(c.checked_div(&b).unwrap() == a); + } + + assert!(c.checked_div(&Zero::zero()).is_none()); + } +} + +#[test] +fn test_gcd() { + fn check(a: usize, b: usize, c: usize) { + let big_a: BigUint = FromPrimitive::from_usize(a).unwrap(); + let big_b: BigUint = FromPrimitive::from_usize(b).unwrap(); + let big_c: BigUint = FromPrimitive::from_usize(c).unwrap(); + + assert_eq!(big_a.gcd(&big_b), big_c); + } + + check(10, 2, 2); + check(10, 3, 1); + check(0, 3, 3); + check(3, 3, 3); + check(56, 42, 14); +} + +#[test] +fn test_lcm() { + fn check(a: usize, b: usize, c: usize) { + let big_a: BigUint = FromPrimitive::from_usize(a).unwrap(); + let big_b: BigUint = FromPrimitive::from_usize(b).unwrap(); + let big_c: BigUint = FromPrimitive::from_usize(c).unwrap(); + + assert_eq!(big_a.lcm(&big_b), big_c); + } + + check(0, 0, 0); + check(1, 0, 0); + check(0, 1, 0); + check(1, 1, 1); + check(8, 9, 72); + check(11, 5, 55); + check(99, 17, 1683); +} + +#[test] +fn test_is_even() { + let one: BigUint = FromStr::from_str("1").unwrap(); + let two: BigUint = FromStr::from_str("2").unwrap(); + let thousand: BigUint = FromStr::from_str("1000").unwrap(); + let big: BigUint = FromStr::from_str("1000000000000000000000").unwrap(); + let bigger: BigUint = FromStr::from_str("1000000000000000000001").unwrap(); + assert!(one.is_odd()); + assert!(two.is_even()); + assert!(thousand.is_even()); + assert!(big.is_even()); + assert!(bigger.is_odd()); + assert!((&one << 64).is_even()); + assert!(((&one << 64) + one).is_odd()); +} + +fn to_str_pairs() -> Vec<(BigUint, Vec<(u32, String)>)> { + let bits = 32; + vec![ + ( + Zero::zero(), + vec![(2, "0".to_string()), (3, "0".to_string())], + ), + ( + BigUint::from_slice(&[0xff]), + vec![ + (2, "11111111".to_string()), + (3, "100110".to_string()), + (4, "3333".to_string()), + (5, "2010".to_string()), + (6, "1103".to_string()), + (7, "513".to_string()), + (8, "377".to_string()), + (9, "313".to_string()), + (10, "255".to_string()), + (11, "212".to_string()), + (12, "193".to_string()), + (13, "168".to_string()), + (14, "143".to_string()), + (15, "120".to_string()), + (16, "ff".to_string()), + ], + ), + ( + BigUint::from_slice(&[0xfff]), + vec![ + (2, "111111111111".to_string()), + (4, "333333".to_string()), + (16, "fff".to_string()), + ], + ), + ( + BigUint::from_slice(&[1, 2]), + vec![ + ( + 2, + format!("10{}1", repeat("0").take(bits - 1).collect::<String>()), + ), + ( + 4, + format!("2{}1", repeat("0").take(bits / 2 - 1).collect::<String>()), + ), + ( + 10, + match bits { + 64 => "36893488147419103233".to_string(), + 32 => "8589934593".to_string(), + 16 => "131073".to_string(), + _ => panic!(), + }, + ), + ( + 16, + format!("2{}1", repeat("0").take(bits / 4 - 1).collect::<String>()), + ), + ], + ), + ( + BigUint::from_slice(&[1, 2, 3]), + vec![ + ( + 2, + format!( + "11{}10{}1", + repeat("0").take(bits - 2).collect::<String>(), + repeat("0").take(bits - 1).collect::<String>() + ), + ), + ( + 4, + format!( + "3{}2{}1", + repeat("0").take(bits / 2 - 1).collect::<String>(), + repeat("0").take(bits / 2 - 1).collect::<String>() + ), + ), + ( + 8, + match bits { + 64 => "14000000000000000000004000000000000000000001".to_string(), + 32 => "6000000000100000000001".to_string(), + 16 => "140000400001".to_string(), + _ => panic!(), + }, + ), + ( + 10, + match bits { + 64 => "1020847100762815390427017310442723737601".to_string(), + 32 => "55340232229718589441".to_string(), + 16 => "12885032961".to_string(), + _ => panic!(), + }, + ), + ( + 16, + format!( + "3{}2{}1", + repeat("0").take(bits / 4 - 1).collect::<String>(), + repeat("0").take(bits / 4 - 1).collect::<String>() + ), + ), + ], + ), + ] +} + +#[test] +fn test_to_str_radix() { + let r = to_str_pairs(); + for num_pair in r.iter() { + let &(ref n, ref rs) = num_pair; + for str_pair in rs.iter() { + let &(ref radix, ref str) = str_pair; + assert_eq!(n.to_str_radix(*radix), *str); + } + } +} + +#[test] +fn test_from_and_to_radix() { + const GROUND_TRUTH: &'static [(&'static [u8], u32, &'static [u8])] = &[ + (b"0", 42, &[0]), + ( + b"ffffeeffbb", + 2, + &[ + 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + ], + ), + ( + b"ffffeeffbb", + 3, + &[ + 2, 2, 1, 1, 2, 1, 1, 2, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 1, 0, 0, 2, 2, 0, 1, + ], + ), + ( + b"ffffeeffbb", + 4, + &[3, 2, 3, 2, 3, 3, 3, 3, 2, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3], + ), + ( + b"ffffeeffbb", + 5, + &[0, 4, 3, 3, 1, 4, 2, 4, 1, 4, 4, 2, 3, 0, 0, 1, 2, 1], + ), + ( + b"ffffeeffbb", + 6, + &[5, 5, 4, 5, 5, 0, 0, 1, 2, 5, 3, 0, 1, 0, 2, 2], + ), + ( + b"ffffeeffbb", + 7, + &[4, 2, 3, 6, 0, 1, 6, 1, 6, 2, 0, 3, 2, 4, 1], + ), + ( + b"ffffeeffbb", + 8, + &[3, 7, 6, 7, 7, 5, 3, 7, 7, 7, 7, 7, 7, 1], + ), + (b"ffffeeffbb", 9, &[8, 4, 5, 7, 0, 0, 3, 2, 0, 3, 0, 8, 3]), + (b"ffffeeffbb", 10, &[5, 9, 5, 3, 1, 5, 0, 1, 5, 9, 9, 0, 1]), + (b"ffffeeffbb", 11, &[10, 7, 6, 5, 2, 0, 3, 3, 3, 4, 9, 3]), + (b"ffffeeffbb", 12, &[11, 8, 5, 10, 1, 10, 3, 1, 1, 9, 5, 1]), + (b"ffffeeffbb", 13, &[0, 5, 7, 4, 6, 5, 6, 11, 8, 12, 7]), + (b"ffffeeffbb", 14, &[11, 4, 4, 11, 8, 4, 6, 0, 3, 11, 3]), + (b"ffffeeffbb", 15, &[5, 11, 13, 2, 1, 10, 2, 0, 9, 13, 1]), + (b"ffffeeffbb", 16, &[11, 11, 15, 15, 14, 14, 15, 15, 15, 15]), + (b"ffffeeffbb", 17, &[0, 2, 14, 12, 2, 14, 8, 10, 4, 9]), + (b"ffffeeffbb", 18, &[17, 15, 5, 13, 10, 16, 16, 13, 9, 5]), + (b"ffffeeffbb", 19, &[14, 13, 2, 8, 9, 0, 1, 14, 7, 3]), + (b"ffffeeffbb", 20, &[15, 19, 3, 14, 0, 17, 19, 18, 2, 2]), + (b"ffffeeffbb", 21, &[11, 5, 4, 13, 5, 18, 9, 1, 8, 1]), + (b"ffffeeffbb", 22, &[21, 3, 7, 21, 15, 12, 17, 0, 20]), + (b"ffffeeffbb", 23, &[21, 21, 6, 9, 10, 7, 21, 0, 14]), + (b"ffffeeffbb", 24, &[11, 10, 19, 14, 22, 11, 17, 23, 9]), + (b"ffffeeffbb", 25, &[20, 18, 21, 22, 21, 14, 3, 5, 7]), + (b"ffffeeffbb", 26, &[13, 15, 24, 11, 17, 6, 23, 6, 5]), + (b"ffffeeffbb", 27, &[17, 16, 7, 0, 21, 0, 3, 24, 3]), + (b"ffffeeffbb", 28, &[11, 16, 11, 15, 14, 18, 13, 25, 2]), + (b"ffffeeffbb", 29, &[6, 8, 7, 19, 14, 13, 21, 5, 2]), + (b"ffffeeffbb", 30, &[5, 13, 18, 11, 10, 7, 8, 20, 1]), + (b"ffffeeffbb", 31, &[22, 26, 15, 19, 8, 27, 29, 8, 1]), + (b"ffffeeffbb", 32, &[27, 29, 31, 29, 30, 31, 31, 31]), + (b"ffffeeffbb", 33, &[32, 20, 27, 12, 1, 12, 26, 25]), + (b"ffffeeffbb", 34, &[17, 9, 16, 33, 13, 25, 31, 20]), + (b"ffffeeffbb", 35, &[25, 32, 2, 25, 11, 4, 3, 17]), + (b"ffffeeffbb", 36, &[35, 34, 5, 6, 32, 3, 1, 14]), + (b"ffffeeffbb", 37, &[16, 21, 18, 4, 33, 19, 21, 11]), + (b"ffffeeffbb", 38, &[33, 25, 19, 29, 20, 6, 23, 9]), + (b"ffffeeffbb", 39, &[26, 27, 29, 23, 16, 18, 0, 8]), + (b"ffffeeffbb", 40, &[35, 39, 30, 11, 16, 17, 28, 6]), + (b"ffffeeffbb", 41, &[36, 30, 9, 18, 12, 19, 26, 5]), + (b"ffffeeffbb", 42, &[11, 34, 37, 27, 1, 13, 32, 4]), + (b"ffffeeffbb", 43, &[3, 24, 11, 2, 10, 40, 1, 4]), + (b"ffffeeffbb", 44, &[43, 12, 40, 32, 3, 23, 19, 3]), + (b"ffffeeffbb", 45, &[35, 38, 44, 18, 22, 18, 42, 2]), + (b"ffffeeffbb", 46, &[21, 45, 18, 41, 17, 2, 24, 2]), + (b"ffffeeffbb", 47, &[37, 37, 11, 12, 6, 0, 8, 2]), + (b"ffffeeffbb", 48, &[11, 41, 40, 43, 5, 43, 41, 1]), + (b"ffffeeffbb", 49, &[18, 45, 7, 13, 20, 21, 30, 1]), + (b"ffffeeffbb", 50, &[45, 21, 5, 34, 21, 18, 20, 1]), + (b"ffffeeffbb", 51, &[17, 6, 26, 22, 38, 24, 11, 1]), + (b"ffffeeffbb", 52, &[39, 33, 38, 30, 46, 31, 3, 1]), + (b"ffffeeffbb", 53, &[31, 7, 44, 23, 9, 32, 49]), + (b"ffffeeffbb", 54, &[17, 35, 8, 37, 31, 18, 44]), + (b"ffffeeffbb", 55, &[10, 52, 9, 48, 36, 39, 39]), + (b"ffffeeffbb", 56, &[11, 50, 51, 22, 25, 36, 35]), + (b"ffffeeffbb", 57, &[14, 55, 12, 43, 20, 3, 32]), + (b"ffffeeffbb", 58, &[35, 18, 45, 56, 9, 51, 28]), + (b"ffffeeffbb", 59, &[51, 28, 20, 26, 55, 3, 26]), + (b"ffffeeffbb", 60, &[35, 6, 27, 46, 58, 33, 23]), + (b"ffffeeffbb", 61, &[58, 7, 6, 54, 49, 20, 21]), + (b"ffffeeffbb", 62, &[53, 59, 3, 14, 10, 22, 19]), + (b"ffffeeffbb", 63, &[53, 50, 23, 4, 56, 36, 17]), + (b"ffffeeffbb", 64, &[59, 62, 47, 59, 63, 63, 15]), + (b"ffffeeffbb", 65, &[0, 53, 39, 4, 40, 37, 14]), + (b"ffffeeffbb", 66, &[65, 59, 39, 1, 64, 19, 13]), + (b"ffffeeffbb", 67, &[35, 14, 19, 16, 25, 10, 12]), + (b"ffffeeffbb", 68, &[51, 38, 63, 50, 15, 8, 11]), + (b"ffffeeffbb", 69, &[44, 45, 18, 58, 68, 12, 10]), + (b"ffffeeffbb", 70, &[25, 51, 0, 60, 13, 24, 9]), + (b"ffffeeffbb", 71, &[54, 30, 9, 65, 28, 41, 8]), + (b"ffffeeffbb", 72, &[35, 35, 55, 54, 17, 64, 7]), + (b"ffffeeffbb", 73, &[34, 4, 48, 40, 27, 19, 7]), + (b"ffffeeffbb", 74, &[53, 47, 4, 56, 36, 51, 6]), + (b"ffffeeffbb", 75, &[20, 56, 10, 72, 24, 13, 6]), + (b"ffffeeffbb", 76, &[71, 31, 52, 60, 48, 53, 5]), + (b"ffffeeffbb", 77, &[32, 73, 14, 63, 15, 21, 5]), + (b"ffffeeffbb", 78, &[65, 13, 17, 32, 64, 68, 4]), + (b"ffffeeffbb", 79, &[37, 56, 2, 56, 25, 41, 4]), + (b"ffffeeffbb", 80, &[75, 59, 37, 41, 43, 15, 4]), + (b"ffffeeffbb", 81, &[44, 68, 0, 21, 27, 72, 3]), + (b"ffffeeffbb", 82, &[77, 35, 2, 74, 46, 50, 3]), + (b"ffffeeffbb", 83, &[52, 51, 19, 76, 10, 30, 3]), + (b"ffffeeffbb", 84, &[11, 80, 19, 19, 76, 10, 3]), + (b"ffffeeffbb", 85, &[0, 82, 20, 14, 68, 77, 2]), + (b"ffffeeffbb", 86, &[3, 12, 78, 37, 62, 61, 2]), + (b"ffffeeffbb", 87, &[35, 12, 20, 8, 52, 46, 2]), + (b"ffffeeffbb", 88, &[43, 6, 54, 42, 30, 32, 2]), + (b"ffffeeffbb", 89, &[49, 52, 85, 21, 80, 18, 2]), + (b"ffffeeffbb", 90, &[35, 64, 78, 24, 18, 6, 2]), + (b"ffffeeffbb", 91, &[39, 17, 83, 63, 17, 85, 1]), + (b"ffffeeffbb", 92, &[67, 22, 85, 79, 75, 74, 1]), + (b"ffffeeffbb", 93, &[53, 60, 39, 29, 4, 65, 1]), + (b"ffffeeffbb", 94, &[37, 89, 2, 72, 76, 55, 1]), + (b"ffffeeffbb", 95, &[90, 74, 89, 9, 9, 47, 1]), + (b"ffffeeffbb", 96, &[59, 20, 46, 35, 81, 38, 1]), + (b"ffffeeffbb", 97, &[94, 87, 60, 71, 3, 31, 1]), + (b"ffffeeffbb", 98, &[67, 22, 63, 50, 62, 23, 1]), + (b"ffffeeffbb", 99, &[98, 6, 69, 12, 61, 16, 1]), + (b"ffffeeffbb", 100, &[95, 35, 51, 10, 95, 9, 1]), + (b"ffffeeffbb", 101, &[87, 27, 7, 8, 62, 3, 1]), + (b"ffffeeffbb", 102, &[17, 3, 32, 79, 59, 99]), + (b"ffffeeffbb", 103, &[30, 22, 90, 0, 87, 94]), + (b"ffffeeffbb", 104, &[91, 68, 87, 68, 38, 90]), + (b"ffffeeffbb", 105, &[95, 80, 54, 73, 15, 86]), + (b"ffffeeffbb", 106, &[31, 30, 24, 16, 17, 82]), + (b"ffffeeffbb", 107, &[51, 50, 10, 12, 42, 78]), + (b"ffffeeffbb", 108, &[71, 71, 96, 78, 89, 74]), + (b"ffffeeffbb", 109, &[33, 18, 93, 22, 50, 71]), + (b"ffffeeffbb", 110, &[65, 53, 57, 88, 29, 68]), + (b"ffffeeffbb", 111, &[53, 93, 67, 90, 27, 65]), + (b"ffffeeffbb", 112, &[11, 109, 96, 65, 43, 62]), + (b"ffffeeffbb", 113, &[27, 23, 106, 56, 76, 59]), + (b"ffffeeffbb", 114, &[71, 84, 31, 112, 11, 57]), + (b"ffffeeffbb", 115, &[90, 22, 1, 56, 76, 54]), + (b"ffffeeffbb", 116, &[35, 38, 98, 57, 40, 52]), + (b"ffffeeffbb", 117, &[26, 113, 115, 62, 17, 50]), + (b"ffffeeffbb", 118, &[51, 14, 5, 18, 7, 48]), + (b"ffffeeffbb", 119, &[102, 31, 110, 108, 8, 46]), + (b"ffffeeffbb", 120, &[35, 93, 96, 50, 22, 44]), + (b"ffffeeffbb", 121, &[87, 61, 2, 36, 47, 42]), + (b"ffffeeffbb", 122, &[119, 64, 1, 22, 83, 40]), + (b"ffffeeffbb", 123, &[77, 119, 32, 90, 6, 39]), + (b"ffffeeffbb", 124, &[115, 122, 31, 79, 62, 37]), + (b"ffffeeffbb", 125, &[95, 108, 47, 74, 3, 36]), + (b"ffffeeffbb", 126, &[53, 25, 116, 39, 78, 34]), + (b"ffffeeffbb", 127, &[22, 23, 125, 67, 35, 33]), + (b"ffffeeffbb", 128, &[59, 127, 59, 127, 127, 31]), + (b"ffffeeffbb", 129, &[89, 36, 1, 59, 100, 30]), + (b"ffffeeffbb", 130, &[65, 91, 123, 89, 79, 29]), + (b"ffffeeffbb", 131, &[58, 72, 39, 63, 65, 28]), + (b"ffffeeffbb", 132, &[131, 62, 92, 82, 57, 27]), + (b"ffffeeffbb", 133, &[109, 31, 51, 123, 55, 26]), + (b"ffffeeffbb", 134, &[35, 74, 21, 27, 60, 25]), + (b"ffffeeffbb", 135, &[125, 132, 49, 37, 70, 24]), + (b"ffffeeffbb", 136, &[51, 121, 117, 133, 85, 23]), + (b"ffffeeffbb", 137, &[113, 60, 135, 22, 107, 22]), + (b"ffffeeffbb", 138, &[113, 91, 73, 93, 133, 21]), + (b"ffffeeffbb", 139, &[114, 75, 102, 51, 26, 21]), + (b"ffffeeffbb", 140, &[95, 25, 35, 16, 62, 20]), + (b"ffffeeffbb", 141, &[131, 137, 16, 110, 102, 19]), + (b"ffffeeffbb", 142, &[125, 121, 108, 34, 6, 19]), + (b"ffffeeffbb", 143, &[65, 78, 138, 55, 55, 18]), + (b"ffffeeffbb", 144, &[107, 125, 121, 15, 109, 17]), + (b"ffffeeffbb", 145, &[35, 13, 122, 42, 22, 17]), + (b"ffffeeffbb", 146, &[107, 38, 103, 123, 83, 16]), + (b"ffffeeffbb", 147, &[116, 96, 71, 98, 2, 16]), + (b"ffffeeffbb", 148, &[127, 23, 75, 99, 71, 15]), + (b"ffffeeffbb", 149, &[136, 110, 53, 114, 144, 14]), + (b"ffffeeffbb", 150, &[95, 140, 133, 130, 71, 14]), + (b"ffffeeffbb", 151, &[15, 50, 29, 137, 0, 14]), + (b"ffffeeffbb", 152, &[147, 15, 89, 121, 83, 13]), + (b"ffffeeffbb", 153, &[17, 87, 93, 72, 17, 13]), + (b"ffffeeffbb", 154, &[109, 113, 3, 133, 106, 12]), + (b"ffffeeffbb", 155, &[115, 141, 120, 139, 44, 12]), + (b"ffffeeffbb", 156, &[143, 45, 4, 82, 140, 11]), + (b"ffffeeffbb", 157, &[149, 92, 15, 106, 82, 11]), + (b"ffffeeffbb", 158, &[37, 107, 79, 46, 26, 11]), + (b"ffffeeffbb", 159, &[137, 37, 146, 51, 130, 10]), + (b"ffffeeffbb", 160, &[155, 69, 29, 115, 77, 10]), + (b"ffffeeffbb", 161, &[67, 98, 46, 68, 26, 10]), + (b"ffffeeffbb", 162, &[125, 155, 60, 63, 138, 9]), + (b"ffffeeffbb", 163, &[96, 43, 118, 93, 90, 9]), + (b"ffffeeffbb", 164, &[159, 99, 123, 152, 43, 9]), + (b"ffffeeffbb", 165, &[65, 17, 1, 69, 163, 8]), + (b"ffffeeffbb", 166, &[135, 108, 25, 165, 119, 8]), + (b"ffffeeffbb", 167, &[165, 116, 164, 103, 77, 8]), + (b"ffffeeffbb", 168, &[11, 166, 67, 44, 36, 8]), + (b"ffffeeffbb", 169, &[65, 59, 71, 149, 164, 7]), + (b"ffffeeffbb", 170, &[85, 83, 26, 76, 126, 7]), + (b"ffffeeffbb", 171, &[71, 132, 140, 157, 88, 7]), + (b"ffffeeffbb", 172, &[3, 6, 127, 47, 52, 7]), + (b"ffffeeffbb", 173, &[122, 66, 53, 83, 16, 7]), + (b"ffffeeffbb", 174, &[35, 6, 5, 88, 155, 6]), + (b"ffffeeffbb", 175, &[95, 20, 84, 56, 122, 6]), + (b"ffffeeffbb", 176, &[43, 91, 57, 159, 89, 6]), + (b"ffffeeffbb", 177, &[110, 127, 54, 40, 58, 6]), + (b"ffffeeffbb", 178, &[49, 115, 43, 47, 27, 6]), + (b"ffffeeffbb", 179, &[130, 91, 4, 178, 175, 5]), + (b"ffffeeffbb", 180, &[35, 122, 109, 70, 147, 5]), + (b"ffffeeffbb", 181, &[94, 94, 4, 79, 119, 5]), + (b"ffffeeffbb", 182, &[39, 54, 66, 19, 92, 5]), + (b"ffffeeffbb", 183, &[119, 2, 143, 69, 65, 5]), + (b"ffffeeffbb", 184, &[67, 57, 90, 44, 39, 5]), + (b"ffffeeffbb", 185, &[90, 63, 141, 123, 13, 5]), + (b"ffffeeffbb", 186, &[53, 123, 172, 119, 174, 4]), + (b"ffffeeffbb", 187, &[153, 21, 68, 28, 151, 4]), + (b"ffffeeffbb", 188, &[131, 138, 94, 32, 128, 4]), + (b"ffffeeffbb", 189, &[179, 121, 156, 130, 105, 4]), + (b"ffffeeffbb", 190, &[185, 179, 164, 131, 83, 4]), + (b"ffffeeffbb", 191, &[118, 123, 37, 31, 62, 4]), + (b"ffffeeffbb", 192, &[59, 106, 83, 16, 41, 4]), + (b"ffffeeffbb", 193, &[57, 37, 47, 86, 20, 4]), + (b"ffffeeffbb", 194, &[191, 140, 63, 45, 0, 4]), + (b"ffffeeffbb", 195, &[65, 169, 83, 84, 175, 3]), + (b"ffffeeffbb", 196, &[67, 158, 64, 6, 157, 3]), + (b"ffffeeffbb", 197, &[121, 26, 167, 3, 139, 3]), + (b"ffffeeffbb", 198, &[197, 151, 165, 75, 121, 3]), + (b"ffffeeffbb", 199, &[55, 175, 36, 22, 104, 3]), + (b"ffffeeffbb", 200, &[195, 167, 162, 38, 87, 3]), + (b"ffffeeffbb", 201, &[35, 27, 136, 124, 70, 3]), + (b"ffffeeffbb", 202, &[87, 64, 153, 76, 54, 3]), + (b"ffffeeffbb", 203, &[151, 191, 14, 94, 38, 3]), + (b"ffffeeffbb", 204, &[119, 103, 135, 175, 22, 3]), + (b"ffffeeffbb", 205, &[200, 79, 123, 115, 7, 3]), + (b"ffffeeffbb", 206, &[133, 165, 202, 115, 198, 2]), + (b"ffffeeffbb", 207, &[44, 153, 193, 175, 184, 2]), + (b"ffffeeffbb", 208, &[91, 190, 125, 86, 171, 2]), + (b"ffffeeffbb", 209, &[109, 151, 34, 53, 158, 2]), + (b"ffffeeffbb", 210, &[95, 40, 171, 74, 145, 2]), + (b"ffffeeffbb", 211, &[84, 195, 162, 150, 132, 2]), + (b"ffffeeffbb", 212, &[31, 15, 59, 68, 120, 2]), + (b"ffffeeffbb", 213, &[125, 57, 127, 36, 108, 2]), + (b"ffffeeffbb", 214, &[51, 132, 2, 55, 96, 2]), + (b"ffffeeffbb", 215, &[175, 133, 177, 122, 84, 2]), + (b"ffffeeffbb", 216, &[179, 35, 78, 23, 73, 2]), + (b"ffffeeffbb", 217, &[53, 101, 208, 186, 61, 2]), + (b"ffffeeffbb", 218, &[33, 9, 214, 179, 50, 2]), + (b"ffffeeffbb", 219, &[107, 147, 175, 217, 39, 2]), + (b"ffffeeffbb", 220, &[175, 81, 179, 79, 29, 2]), + (b"ffffeeffbb", 221, &[0, 76, 95, 204, 18, 2]), + (b"ffffeeffbb", 222, &[53, 213, 16, 150, 8, 2]), + (b"ffffeeffbb", 223, &[158, 161, 42, 136, 221, 1]), + (b"ffffeeffbb", 224, &[123, 54, 52, 162, 212, 1]), + (b"ffffeeffbb", 225, &[170, 43, 151, 2, 204, 1]), + (b"ffffeeffbb", 226, &[27, 68, 224, 105, 195, 1]), + (b"ffffeeffbb", 227, &[45, 69, 157, 20, 187, 1]), + (b"ffffeeffbb", 228, &[71, 213, 64, 199, 178, 1]), + (b"ffffeeffbb", 229, &[129, 203, 66, 186, 170, 1]), + (b"ffffeeffbb", 230, &[205, 183, 57, 208, 162, 1]), + (b"ffffeeffbb", 231, &[32, 50, 164, 33, 155, 1]), + (b"ffffeeffbb", 232, &[35, 135, 53, 123, 147, 1]), + (b"ffffeeffbb", 233, &[209, 47, 89, 13, 140, 1]), + (b"ffffeeffbb", 234, &[143, 56, 175, 168, 132, 1]), + (b"ffffeeffbb", 235, &[225, 157, 216, 121, 125, 1]), + (b"ffffeeffbb", 236, &[51, 66, 119, 105, 118, 1]), + (b"ffffeeffbb", 237, &[116, 150, 26, 119, 111, 1]), + (b"ffffeeffbb", 238, &[221, 15, 87, 162, 104, 1]), + (b"ffffeeffbb", 239, &[234, 155, 214, 234, 97, 1]), + (b"ffffeeffbb", 240, &[155, 46, 84, 96, 91, 1]), + (b"ffffeeffbb", 241, &[187, 48, 90, 225, 84, 1]), + (b"ffffeeffbb", 242, &[87, 212, 151, 140, 78, 1]), + (b"ffffeeffbb", 243, &[206, 22, 189, 81, 72, 1]), + (b"ffffeeffbb", 244, &[119, 93, 122, 48, 66, 1]), + (b"ffffeeffbb", 245, &[165, 224, 117, 40, 60, 1]), + (b"ffffeeffbb", 246, &[77, 121, 100, 57, 54, 1]), + (b"ffffeeffbb", 247, &[52, 128, 242, 98, 48, 1]), + (b"ffffeeffbb", 248, &[115, 247, 224, 164, 42, 1]), + (b"ffffeeffbb", 249, &[218, 127, 223, 5, 37, 1]), + (b"ffffeeffbb", 250, &[95, 54, 168, 118, 31, 1]), + (b"ffffeeffbb", 251, &[121, 204, 240, 3, 26, 1]), + (b"ffffeeffbb", 252, &[179, 138, 123, 162, 20, 1]), + (b"ffffeeffbb", 253, &[21, 50, 1, 91, 15, 1]), + (b"ffffeeffbb", 254, &[149, 11, 63, 40, 10, 1]), + (b"ffffeeffbb", 255, &[170, 225, 247, 9, 5, 1]), + (b"ffffeeffbb", 256, &[187, 255, 238, 255, 255]), + ]; + + for &(bigint, radix, inbaseradix_le) in GROUND_TRUTH.iter() { + let bigint = BigUint::parse_bytes(bigint, 16).unwrap(); + // to_radix_le + assert_eq!(bigint.to_radix_le(radix), inbaseradix_le); + // to_radix_be + let mut inbase_be = bigint.to_radix_be(radix); + inbase_be.reverse(); // now le + assert_eq!(inbase_be, inbaseradix_le); + // from_radix_le + assert_eq!( + BigUint::from_radix_le(inbaseradix_le, radix).unwrap(), + bigint + ); + // from_radix_be + let mut inbaseradix_be = Vec::from(inbaseradix_le); + inbaseradix_be.reverse(); + assert_eq!( + BigUint::from_radix_be(&inbaseradix_be, radix).unwrap(), + bigint + ); + } + + assert!(BigUint::from_radix_le(&[10, 100, 10], 50).is_none()); +} + +#[test] +fn test_from_str_radix() { + let r = to_str_pairs(); + for num_pair in r.iter() { + let &(ref n, ref rs) = num_pair; + for str_pair in rs.iter() { + let &(ref radix, ref str) = str_pair; + assert_eq!(n, &BigUint::from_str_radix(str, *radix).unwrap()); + } + } + + let zed = BigUint::from_str_radix("Z", 10).ok(); + assert_eq!(zed, None); + let blank = BigUint::from_str_radix("_", 2).ok(); + assert_eq!(blank, None); + let blank_one = BigUint::from_str_radix("_1", 2).ok(); + assert_eq!(blank_one, None); + let plus_one = BigUint::from_str_radix("+1", 10).ok(); + assert_eq!(plus_one, Some(BigUint::from_slice(&[1]))); + let plus_plus_one = BigUint::from_str_radix("++1", 10).ok(); + assert_eq!(plus_plus_one, None); + let minus_one = BigUint::from_str_radix("-1", 10).ok(); + assert_eq!(minus_one, None); + let zero_plus_two = BigUint::from_str_radix("0+2", 10).ok(); + assert_eq!(zero_plus_two, None); + let three = BigUint::from_str_radix("1_1", 2).ok(); + assert_eq!(three, Some(BigUint::from_slice(&[3]))); + let ff = BigUint::from_str_radix("1111_1111", 2).ok(); + assert_eq!(ff, Some(BigUint::from_slice(&[0xff]))); +} + +#[test] +fn test_all_str_radix() { + #[allow(deprecated, unused_imports)] + use std::ascii::AsciiExt; + + let n = BigUint::new((0..10).collect()); + for radix in 2..37 { + let s = n.to_str_radix(radix); + let x = BigUint::from_str_radix(&s, radix); + assert_eq!(x.unwrap(), n); + + let s = s.to_ascii_uppercase(); + let x = BigUint::from_str_radix(&s, radix); + assert_eq!(x.unwrap(), n); + } +} + +#[test] +fn test_lower_hex() { + let a = BigUint::parse_bytes(b"A", 16).unwrap(); + let hello = BigUint::parse_bytes("22405534230753963835153736737".as_bytes(), 10).unwrap(); + + assert_eq!(format!("{:x}", a), "a"); + assert_eq!(format!("{:x}", hello), "48656c6c6f20776f726c6421"); + assert_eq!(format!("{:♥>+#8x}", a), "♥♥♥♥+0xa"); +} + +#[test] +fn test_upper_hex() { + let a = BigUint::parse_bytes(b"A", 16).unwrap(); + let hello = BigUint::parse_bytes("22405534230753963835153736737".as_bytes(), 10).unwrap(); + + assert_eq!(format!("{:X}", a), "A"); + assert_eq!(format!("{:X}", hello), "48656C6C6F20776F726C6421"); + assert_eq!(format!("{:♥>+#8X}", a), "♥♥♥♥+0xA"); +} + +#[test] +fn test_binary() { + let a = BigUint::parse_bytes(b"A", 16).unwrap(); + let hello = BigUint::parse_bytes("224055342307539".as_bytes(), 10).unwrap(); + + assert_eq!(format!("{:b}", a), "1010"); + assert_eq!( + format!("{:b}", hello), + "110010111100011011110011000101101001100011010011" + ); + assert_eq!(format!("{:♥>+#8b}", a), "♥+0b1010"); +} + +#[test] +fn test_octal() { + let a = BigUint::parse_bytes(b"A", 16).unwrap(); + let hello = BigUint::parse_bytes("22405534230753963835153736737".as_bytes(), 10).unwrap(); + + assert_eq!(format!("{:o}", a), "12"); + assert_eq!(format!("{:o}", hello), "22062554330674403566756233062041"); + assert_eq!(format!("{:♥>+#8o}", a), "♥♥♥+0o12"); +} + +#[test] +fn test_display() { + let a = BigUint::parse_bytes(b"A", 16).unwrap(); + let hello = BigUint::parse_bytes("22405534230753963835153736737".as_bytes(), 10).unwrap(); + + assert_eq!(format!("{}", a), "10"); + assert_eq!(format!("{}", hello), "22405534230753963835153736737"); + assert_eq!(format!("{:♥>+#8}", a), "♥♥♥♥♥+10"); +} + +#[test] +fn test_factor() { + fn factor(n: usize) -> BigUint { + let mut f: BigUint = One::one(); + for i in 2..n + 1 { + // FIXME(#5992): assignment operator overloads + // f *= FromPrimitive::from_usize(i); + let bu: BigUint = FromPrimitive::from_usize(i).unwrap(); + f = f * bu; + } + return f; + } + + fn check(n: usize, s: &str) { + let n = factor(n); + let ans = match BigUint::from_str_radix(s, 10) { + Ok(x) => x, + Err(_) => panic!(), + }; + assert_eq!(n, ans); + } + + check(3, "6"); + check(10, "3628800"); + check(20, "2432902008176640000"); + check(30, "265252859812191058636308480000000"); +} + +#[test] +fn test_bits() { + assert_eq!(BigUint::new(vec![0, 0, 0, 0]).bits(), 0); + let n: BigUint = FromPrimitive::from_usize(0).unwrap(); + assert_eq!(n.bits(), 0); + let n: BigUint = FromPrimitive::from_usize(1).unwrap(); + assert_eq!(n.bits(), 1); + let n: BigUint = FromPrimitive::from_usize(3).unwrap(); + assert_eq!(n.bits(), 2); + let n: BigUint = BigUint::from_str_radix("4000000000", 16).unwrap(); + assert_eq!(n.bits(), 39); + let one: BigUint = One::one(); + assert_eq!((one << 426).bits(), 427); +} + +#[test] +fn test_iter_sum() { + let result: BigUint = FromPrimitive::from_isize(1234567).unwrap(); + let data: Vec<BigUint> = vec![ + FromPrimitive::from_u32(1000000).unwrap(), + FromPrimitive::from_u32(200000).unwrap(), + FromPrimitive::from_u32(30000).unwrap(), + FromPrimitive::from_u32(4000).unwrap(), + FromPrimitive::from_u32(500).unwrap(), + FromPrimitive::from_u32(60).unwrap(), + FromPrimitive::from_u32(7).unwrap(), + ]; + + assert_eq!(result, data.iter().sum()); + assert_eq!(result, data.into_iter().sum()); +} + +#[test] +fn test_iter_product() { + let data: Vec<BigUint> = vec![ + FromPrimitive::from_u32(1001).unwrap(), + FromPrimitive::from_u32(1002).unwrap(), + FromPrimitive::from_u32(1003).unwrap(), + FromPrimitive::from_u32(1004).unwrap(), + FromPrimitive::from_u32(1005).unwrap(), + ]; + let result = data.get(0).unwrap() + * data.get(1).unwrap() + * data.get(2).unwrap() + * data.get(3).unwrap() + * data.get(4).unwrap(); + + assert_eq!(result, data.iter().product()); + assert_eq!(result, data.into_iter().product()); +} + +#[test] +fn test_iter_sum_generic() { + let result: BigUint = FromPrimitive::from_isize(1234567).unwrap(); + let data = vec![1000000_u32, 200000, 30000, 4000, 500, 60, 7]; + + assert_eq!(result, data.iter().sum()); + assert_eq!(result, data.into_iter().sum()); +} + +#[test] +fn test_iter_product_generic() { + let data = vec![1001_u32, 1002, 1003, 1004, 1005]; + let result = data[0].to_biguint().unwrap() + * data[1].to_biguint().unwrap() + * data[2].to_biguint().unwrap() + * data[3].to_biguint().unwrap() + * data[4].to_biguint().unwrap(); + + assert_eq!(result, data.iter().product()); + assert_eq!(result, data.into_iter().product()); +} + +#[test] +fn test_pow() { + let one = BigUint::from(1u32); + let two = BigUint::from(2u32); + let four = BigUint::from(4u32); + let eight = BigUint::from(8u32); + let tentwentyfour = BigUint::from(1024u32); + let twentyfourtyeight = BigUint::from(2048u32); + macro_rules! check { + ($t:ty) => { + assert_eq!(two.pow(0 as $t), one); + assert_eq!(two.pow(1 as $t), two); + assert_eq!(two.pow(2 as $t), four); + assert_eq!(two.pow(3 as $t), eight); + assert_eq!(two.pow(10 as $t), tentwentyfour); + assert_eq!(two.pow(11 as $t), twentyfourtyeight); + assert_eq!(two.pow(&(11 as $t)), twentyfourtyeight); + }; + } + check!(u8); + check!(u16); + check!(u32); + check!(u64); + check!(usize); + #[cfg(has_i128)] + check!(u128); +} diff --git a/third_party/rust/num-bigint/tests/biguint_scalar.rs b/third_party/rust/num-bigint/tests/biguint_scalar.rs new file mode 100644 index 0000000000..fb8fbf0357 --- /dev/null +++ b/third_party/rust/num-bigint/tests/biguint_scalar.rs @@ -0,0 +1,109 @@ +extern crate num_bigint; +extern crate num_traits; + +use num_bigint::BigUint; +use num_traits::{ToPrimitive, Zero}; + +mod consts; +use consts::*; + +#[macro_use] +mod macros; + +#[test] +fn test_scalar_add() { + fn check(x: &BigUint, y: &BigUint, z: &BigUint) { + let (x, y, z) = (x.clone(), y.clone(), z.clone()); + assert_unsigned_scalar_op!(x + y == z); + } + + for elm in SUM_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + check(&a, &b, &c); + check(&b, &a, &c); + } +} + +#[test] +fn test_scalar_sub() { + fn check(x: &BigUint, y: &BigUint, z: &BigUint) { + let (x, y, z) = (x.clone(), y.clone(), z.clone()); + assert_unsigned_scalar_op!(x - y == z); + } + + for elm in SUM_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + check(&c, &a, &b); + check(&c, &b, &a); + } +} + +#[test] +fn test_scalar_mul() { + fn check(x: &BigUint, y: &BigUint, z: &BigUint) { + let (x, y, z) = (x.clone(), y.clone(), z.clone()); + assert_unsigned_scalar_op!(x * y == z); + } + + for elm in MUL_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + check(&a, &b, &c); + check(&b, &a, &c); + } +} + +#[test] +fn test_scalar_rem_noncommutative() { + assert_eq!(5u8 % BigUint::from(7u8), 5u8.into()); + assert_eq!(BigUint::from(5u8) % 7u8, 5u8.into()); +} + +#[test] +fn test_scalar_div_rem() { + fn check(x: &BigUint, y: &BigUint, z: &BigUint, r: &BigUint) { + let (x, y, z, r) = (x.clone(), y.clone(), z.clone(), r.clone()); + assert_unsigned_scalar_op!(x / y == z); + assert_unsigned_scalar_op!(x % y == r); + } + + for elm in MUL_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + if !a.is_zero() { + check(&c, &a, &b, &Zero::zero()); + } + + if !b.is_zero() { + check(&c, &b, &a, &Zero::zero()); + } + } + + for elm in DIV_REM_QUADRUPLES.iter() { + let (a_vec, b_vec, c_vec, d_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + let d = BigUint::from_slice(d_vec); + + if !b.is_zero() { + check(&a, &b, &c, &d); + assert_unsigned_scalar_op!(a / b == c); + assert_unsigned_scalar_op!(a % b == d); + } + } +} diff --git a/third_party/rust/num-bigint/tests/consts/mod.rs b/third_party/rust/num-bigint/tests/consts/mod.rs new file mode 100644 index 0000000000..87805d5e24 --- /dev/null +++ b/third_party/rust/num-bigint/tests/consts/mod.rs @@ -0,0 +1,56 @@ +#![allow(unused)] + +pub const N1: u32 = -1i32 as u32; +pub const N2: u32 = -2i32 as u32; + +pub const SUM_TRIPLES: &'static [(&'static [u32], &'static [u32], &'static [u32])] = &[ + (&[], &[], &[]), + (&[], &[1], &[1]), + (&[1], &[1], &[2]), + (&[1], &[1, 1], &[2, 1]), + (&[1], &[N1], &[0, 1]), + (&[1], &[N1, N1], &[0, 0, 1]), + (&[N1, N1], &[N1, N1], &[N2, N1, 1]), + (&[1, 1, 1], &[N1, N1], &[0, 1, 2]), + (&[2, 2, 1], &[N1, N2], &[1, 1, 2]), + (&[1, 2, 2, 1], &[N1, N2], &[0, 1, 3, 1]), +]; + +pub const M: u32 = ::std::u32::MAX; +pub const MUL_TRIPLES: &'static [(&'static [u32], &'static [u32], &'static [u32])] = &[ + (&[], &[], &[]), + (&[], &[1], &[]), + (&[2], &[], &[]), + (&[1], &[1], &[1]), + (&[2], &[3], &[6]), + (&[1], &[1, 1, 1], &[1, 1, 1]), + (&[1, 2, 3], &[3], &[3, 6, 9]), + (&[1, 1, 1], &[N1], &[N1, N1, N1]), + (&[1, 2, 3], &[N1], &[N1, N2, N2, 2]), + (&[1, 2, 3, 4], &[N1], &[N1, N2, N2, N2, 3]), + (&[N1], &[N1], &[1, N2]), + (&[N1, N1], &[N1], &[1, N1, N2]), + (&[N1, N1, N1], &[N1], &[1, N1, N1, N2]), + (&[N1, N1, N1, N1], &[N1], &[1, N1, N1, N1, N2]), + (&[M / 2 + 1], &[2], &[0, 1]), + (&[0, M / 2 + 1], &[2], &[0, 0, 1]), + (&[1, 2], &[1, 2, 3], &[1, 4, 7, 6]), + (&[N1, N1], &[N1, N1, N1], &[1, 0, N1, N2, N1]), + (&[N1, N1, N1], &[N1, N1, N1, N1], &[1, 0, 0, N1, N2, N1, N1]), + (&[0, 0, 1], &[1, 2, 3], &[0, 0, 1, 2, 3]), + (&[0, 0, 1], &[0, 0, 0, 1], &[0, 0, 0, 0, 0, 1]), +]; + +pub const DIV_REM_QUADRUPLES: &'static [( + &'static [u32], + &'static [u32], + &'static [u32], + &'static [u32], +)] = &[ + (&[1], &[2], &[], &[1]), + (&[3], &[2], &[1], &[1]), + (&[1, 1], &[2], &[M / 2 + 1], &[1]), + (&[1, 1, 1], &[2], &[M / 2 + 1, M / 2 + 1], &[1]), + (&[0, 1], &[N1], &[1], &[1]), + (&[N1, N1], &[N2], &[2, 1], &[3]), +]; diff --git a/third_party/rust/num-bigint/tests/macros/mod.rs b/third_party/rust/num-bigint/tests/macros/mod.rs new file mode 100644 index 0000000000..d848b29b35 --- /dev/null +++ b/third_party/rust/num-bigint/tests/macros/mod.rs @@ -0,0 +1,70 @@ +#![allow(unused)] + +/// Assert that an op works for all val/ref combinations +macro_rules! assert_op { + ($left:ident $op:tt $right:ident == $expected:expr) => { + assert_eq!((&$left) $op (&$right), $expected); + assert_eq!((&$left) $op $right.clone(), $expected); + assert_eq!($left.clone() $op (&$right), $expected); + assert_eq!($left.clone() $op $right.clone(), $expected); + }; +} + +/// Assert that an assign-op works for all val/ref combinations +macro_rules! assert_assign_op { + ($left:ident $op:tt $right:ident == $expected:expr) => {{ + let mut left = $left.clone(); + assert_eq!({ left $op &$right; left}, $expected); + + let mut left = $left.clone(); + assert_eq!({ left $op $right.clone(); left}, $expected); + }}; +} + +/// Assert that an op works for scalar left or right +macro_rules! assert_scalar_op { + (($($to:ident),*) $left:ident $op:tt $right:ident == $expected:expr) => { + $( + if let Some(left) = $left.$to() { + assert_op!(left $op $right == $expected); + } + if let Some(right) = $right.$to() { + assert_op!($left $op right == $expected); + } + )* + }; +} + +#[cfg(not(has_i128))] +macro_rules! assert_unsigned_scalar_op { + ($left:ident $op:tt $right:ident == $expected:expr) => { + assert_scalar_op!((to_u8, to_u16, to_u32, to_u64, to_usize) + $left $op $right == $expected); + }; +} + +#[cfg(has_i128)] +macro_rules! assert_unsigned_scalar_op { + ($left:ident $op:tt $right:ident == $expected:expr) => { + assert_scalar_op!((to_u8, to_u16, to_u32, to_u64, to_usize, to_u128) + $left $op $right == $expected); + }; +} + +#[cfg(not(has_i128))] +macro_rules! assert_signed_scalar_op { + ($left:ident $op:tt $right:ident == $expected:expr) => { + assert_scalar_op!((to_u8, to_u16, to_u32, to_u64, to_usize, + to_i8, to_i16, to_i32, to_i64, to_isize) + $left $op $right == $expected); + }; +} + +#[cfg(has_i128)] +macro_rules! assert_signed_scalar_op { + ($left:ident $op:tt $right:ident == $expected:expr) => { + assert_scalar_op!((to_u8, to_u16, to_u32, to_u64, to_usize, to_u128, + to_i8, to_i16, to_i32, to_i64, to_isize, to_i128) + $left $op $right == $expected); + }; +} diff --git a/third_party/rust/num-bigint/tests/modpow.rs b/third_party/rust/num-bigint/tests/modpow.rs new file mode 100644 index 0000000000..b7a992c863 --- /dev/null +++ b/third_party/rust/num-bigint/tests/modpow.rs @@ -0,0 +1,150 @@ +extern crate num_bigint; +extern crate num_integer; +extern crate num_traits; + +static BIG_B: &'static str = "\ + efac3c0a_0de55551_fee0bfe4_67fa017a_1a898fa1_6ca57cb1\ + ca9e3248_cacc09a9_b99d6abc_38418d0f_82ae4238_d9a68832\ + aadec7c1_ac5fed48_7a56a71b_67ac59d5_afb28022_20d9592d\ + 247c4efc_abbd9b75_586088ee_1dc00dc4_232a8e15_6e8191dd\ + 675b6ae0_c80f5164_752940bc_284b7cee_885c1e10_e495345b\ + 8fbe9cfd_e5233fe1_19459d0b_d64be53c_27de5a02_a829976b\ + 33096862_82dad291_bd38b6a9_be396646_ddaf8039_a2573c39\ + 1b14e8bc_2cb53e48_298c047e_d9879e9c_5a521076_f0e27df3\ + 990e1659_d3d8205b_6443ebc0_9918ebee_6764f668_9f2b2be3\ + b59cbc76_d76d0dfc_d737c3ec_0ccf9c00_ad0554bf_17e776ad\ + b4edf9cc_6ce540be_76229093_5c53893b"; + +static BIG_E: &'static str = "\ + be0e6ea6_08746133_e0fbc1bf_82dba91e_e2b56231_a81888d2\ + a833a1fc_f7ff002a_3c486a13_4f420bf3_a5435be9_1a5c8391\ + 774d6e6c_085d8357_b0c97d4d_2bb33f7c_34c68059_f78d2541\ + eacc8832_426f1816_d3be001e_b69f9242_51c7708e_e10efe98\ + 449c9a4a_b55a0f23_9d797410_515da00d_3ea07970_4478a2ca\ + c3d5043c_bd9be1b4_6dce479d_4302d344_84a939e6_0ab5ada7\ + 12ae34b2_30cc473c_9f8ee69d_2cac5970_29f5bf18_bc8203e4\ + f3e895a2_13c94f1e_24c73d77_e517e801_53661fdd_a2ce9e47\ + a73dd7f8_2f2adb1e_3f136bf7_8ae5f3b8_08730de1_a4eff678\ + e77a06d0_19a522eb_cbefba2a_9caf7736_b157c5c6_2d192591\ + 17946850_2ddb1822_117b68a0_32f7db88"; + +// This modulus is the prime from the 2048-bit MODP DH group: +// https://tools.ietf.org/html/rfc3526#section-3 +static BIG_M: &'static str = "\ + FFFFFFFF_FFFFFFFF_C90FDAA2_2168C234_C4C6628B_80DC1CD1\ + 29024E08_8A67CC74_020BBEA6_3B139B22_514A0879_8E3404DD\ + EF9519B3_CD3A431B_302B0A6D_F25F1437_4FE1356D_6D51C245\ + E485B576_625E7EC6_F44C42E9_A637ED6B_0BFF5CB6_F406B7ED\ + EE386BFB_5A899FA5_AE9F2411_7C4B1FE6_49286651_ECE45B3D\ + C2007CB8_A163BF05_98DA4836_1C55D39A_69163FA8_FD24CF5F\ + 83655D23_DCA3AD96_1C62F356_208552BB_9ED52907_7096966D\ + 670C354E_4ABC9804_F1746C08_CA18217C_32905E46_2E36CE3B\ + E39E772C_180E8603_9B2783A2_EC07A28F_B5C55DF0_6F4C52C9\ + DE2BCBF6_95581718_3995497C_EA956AE5_15D22618_98FA0510\ + 15728E5A_8AACAA68_FFFFFFFF_FFFFFFFF"; + +static BIG_R: &'static str = "\ + a1468311_6e56edc9_7a98228b_5e924776_0dd7836e_caabac13\ + eda5373b_4752aa65_a1454850_40dc770e_30aa8675_6be7d3a8\ + 9d3085e4_da5155cf_b451ef62_54d0da61_cf2b2c87_f495e096\ + 055309f7_77802bbb_37271ba8_1313f1b5_075c75d1_024b6c77\ + fdb56f17_b05bce61_e527ebfd_2ee86860_e9907066_edd526e7\ + 93d289bf_6726b293_41b0de24_eff82424_8dfd374b_4ec59542\ + 35ced2b2_6b195c90_10042ffb_8f58ce21_bc10ec42_64fda779\ + d352d234_3d4eaea6_a86111ad_a37e9555_43ca78ce_2885bed7\ + 5a30d182_f1cf6834_dc5b6e27_1a41ac34_a2e91e11_33363ff0\ + f88a7b04_900227c9_f6e6d06b_7856b4bb_4e354d61_060db6c8\ + 109c4735_6e7db425_7b5d74c7_0b709508"; + +mod biguint { + use num_bigint::BigUint; + use num_integer::Integer; + use num_traits::Num; + + fn check_modpow<T: Into<BigUint>>(b: T, e: T, m: T, r: T) { + let b: BigUint = b.into(); + let e: BigUint = e.into(); + let m: BigUint = m.into(); + let r: BigUint = r.into(); + + assert_eq!(b.modpow(&e, &m), r); + + let even_m = &m << 1; + let even_modpow = b.modpow(&e, &even_m); + assert!(even_modpow < even_m); + assert_eq!(even_modpow.mod_floor(&m), r); + } + + #[test] + fn test_modpow() { + check_modpow::<u32>(1, 0, 11, 1); + check_modpow::<u32>(0, 15, 11, 0); + check_modpow::<u32>(3, 7, 11, 9); + check_modpow::<u32>(5, 117, 19, 1); + } + + #[test] + fn test_modpow_big() { + let b = BigUint::from_str_radix(super::BIG_B, 16).unwrap(); + let e = BigUint::from_str_radix(super::BIG_E, 16).unwrap(); + let m = BigUint::from_str_radix(super::BIG_M, 16).unwrap(); + let r = BigUint::from_str_radix(super::BIG_R, 16).unwrap(); + + assert_eq!(b.modpow(&e, &m), r); + + let even_m = &m << 1; + let even_modpow = b.modpow(&e, &even_m); + assert!(even_modpow < even_m); + assert_eq!(even_modpow % m, r); + } +} + +mod bigint { + use num_bigint::BigInt; + use num_integer::Integer; + use num_traits::{Num, One, Signed, Zero}; + + fn check_modpow<T: Into<BigInt>>(b: T, e: T, m: T, r: T) { + fn check(b: &BigInt, e: &BigInt, m: &BigInt, r: &BigInt) { + assert_eq!(&b.modpow(e, m), r); + + let even_m = m << 1; + let even_modpow = b.modpow(e, m); + assert!(even_modpow.abs() < even_m.abs()); + assert_eq!(&even_modpow.mod_floor(&m), r); + + // the sign of the result follows the modulus like `mod_floor`, not `rem` + assert_eq!(b.modpow(&BigInt::one(), m), b.mod_floor(m)); + } + + let b: BigInt = b.into(); + let e: BigInt = e.into(); + let m: BigInt = m.into(); + let r: BigInt = r.into(); + + let neg_r = if r.is_zero() { BigInt::zero() } else { &m - &r }; + + check(&b, &e, &m, &r); + check(&-&b, &e, &m, &neg_r); + check(&b, &e, &-&m, &-neg_r); + check(&-b, &e, &-m, &-r); + } + + #[test] + fn test_modpow() { + check_modpow(1, 0, 11, 1); + check_modpow(0, 15, 11, 0); + check_modpow(3, 7, 11, 9); + check_modpow(5, 117, 19, 1); + } + + #[test] + fn test_modpow_big() { + let b = BigInt::from_str_radix(super::BIG_B, 16).unwrap(); + let e = BigInt::from_str_radix(super::BIG_E, 16).unwrap(); + let m = BigInt::from_str_radix(super::BIG_M, 16).unwrap(); + let r = BigInt::from_str_radix(super::BIG_R, 16).unwrap(); + + check_modpow(b, e, m, r); + } +} diff --git a/third_party/rust/num-bigint/tests/quickcheck.rs b/third_party/rust/num-bigint/tests/quickcheck.rs new file mode 100644 index 0000000000..6bb251fa90 --- /dev/null +++ b/third_party/rust/num-bigint/tests/quickcheck.rs @@ -0,0 +1,317 @@ +#![cfg(feature = "quickcheck")] +#![cfg(feature = "quickcheck_macros")] + +extern crate num_bigint; +extern crate num_integer; +extern crate num_traits; + +extern crate quickcheck; +#[macro_use] +extern crate quickcheck_macros; + +use num_bigint::{BigInt, BigUint}; +use num_traits::{Num, One, Pow, Zero}; +use quickcheck::{QuickCheck, StdThreadGen, TestResult}; + +#[quickcheck] +fn quickcheck_unsigned_eq_reflexive(a: BigUint) -> bool { + a == a +} + +#[quickcheck] +fn quickcheck_signed_eq_reflexive(a: BigInt) -> bool { + a == a +} + +#[quickcheck] +fn quickcheck_unsigned_eq_symmetric(a: BigUint, b: BigUint) -> bool { + if a == b { + b == a + } else { + b != a + } +} + +#[quickcheck] +fn quickcheck_signed_eq_symmetric(a: BigInt, b: BigInt) -> bool { + if a == b { + b == a + } else { + b != a + } +} + +#[test] +fn quickcheck_arith_primitive() { + let gen = StdThreadGen::new(usize::max_value()); + let mut qc = QuickCheck::with_gen(gen); + + fn test_unsigned_add_primitive(a: usize, b: usize) -> TestResult { + let actual = BigUint::from(a) + BigUint::from(b); + match a.checked_add(b) { + None => TestResult::discard(), + Some(expected) => TestResult::from_bool(BigUint::from(expected) == actual), + } + } + + fn test_signed_add_primitive(a: isize, b: isize) -> TestResult { + let actual = BigInt::from(a) + BigInt::from(b); + match a.checked_add(b) { + None => TestResult::discard(), + Some(expected) => TestResult::from_bool(BigInt::from(expected) == actual), + } + } + + fn test_unsigned_mul_primitive(a: u64, b: u64) -> bool { + //maximum value of u64 means no overflow + BigUint::from(a as u128 * b as u128) == BigUint::from(a) * BigUint::from(b) + } + + fn test_signed_mul_primitive(a: i64, b: i64) -> bool { + //maximum value of i64 means no overflow + BigInt::from(a as i128 * b as i128) == BigInt::from(a) * BigInt::from(b) + } + + fn test_unsigned_sub_primitive(a: u128, b: u128) -> bool { + if b < a { + BigUint::from(a - b) == BigUint::from(a) - BigUint::from(b) + } else { + BigUint::from(b - a) == BigUint::from(b) - BigUint::from(a) + } + } + + fn test_signed_sub_primitive(a: i128, b: i128) -> bool { + if b < a { + BigInt::from(a - b) == BigInt::from(a) - BigInt::from(b) + } else { + BigInt::from(b - a) == BigInt::from(b) - BigInt::from(a) + } + } + + fn test_unsigned_div_primitive(a: u128, b: u128) -> TestResult { + if b == 0 { + TestResult::discard() + } else { + TestResult::from_bool(BigUint::from(a / b) == BigUint::from(a) / BigUint::from(b)) + } + } + + fn test_signed_div_primitive(a: i128, b: i128) -> TestResult { + if b == 0 { + TestResult::discard() + } else { + TestResult::from_bool(BigInt::from(a / b) == BigInt::from(a) / BigInt::from(b)) + } + } + + qc.quickcheck(test_unsigned_add_primitive as fn(usize, usize) -> TestResult); + qc.quickcheck(test_signed_add_primitive as fn(isize, isize) -> TestResult); + qc.quickcheck(test_unsigned_mul_primitive as fn(u64, u64) -> bool); + qc.quickcheck(test_signed_mul_primitive as fn(i64, i64) -> bool); + qc.quickcheck(test_unsigned_sub_primitive as fn(u128, u128) -> bool); + qc.quickcheck(test_signed_sub_primitive as fn(i128, i128) -> bool); + qc.quickcheck(test_unsigned_div_primitive as fn(u128, u128) -> TestResult); + qc.quickcheck(test_signed_div_primitive as fn(i128, i128) -> TestResult); +} + +#[quickcheck] +fn quickcheck_unsigned_add_commutative(a: BigUint, b: BigUint) -> bool { + &a + &b == b + a +} + +#[quickcheck] +fn quickcheck_signed_add_commutative(a: BigInt, b: BigInt) -> bool { + &a + &b == b + a +} + +#[quickcheck] +fn quickcheck_unsigned_add_zero(a: BigUint) -> bool { + a == &a + BigUint::zero() +} + +#[quickcheck] +fn quickcheck_signed_add_zero(a: BigInt) -> bool { + a == &a + BigInt::zero() +} + +#[quickcheck] +fn quickcheck_unsigned_add_associative(a: BigUint, b: BigUint, c: BigUint) -> bool { + (&a + &b) + &c == a + (b + c) +} + +#[quickcheck] +fn quickcheck_signed_add_associative(a: BigInt, b: BigInt, c: BigInt) -> bool { + (&a + &b) + &c == a + (b + c) +} + +#[quickcheck] +fn quickcheck_unsigned_mul_zero(a: BigUint) -> bool { + a * BigUint::zero() == BigUint::zero() +} + +#[quickcheck] +fn quickcheck_signed_mul_zero(a: BigInt) -> bool { + a * BigInt::zero() == BigInt::zero() +} + +#[quickcheck] +fn quickcheck_unsigned_mul_one(a: BigUint) -> bool { + &a * BigUint::one() == a +} + +#[quickcheck] +fn quickcheck_signed_mul_one(a: BigInt) -> bool { + &a * BigInt::one() == a +} + +#[quickcheck] +fn quickcheck_unsigned_mul_commutative(a: BigUint, b: BigUint) -> bool { + &a * &b == b * a +} + +#[quickcheck] +fn quickcheck_signed_mul_commutative(a: BigInt, b: BigInt) -> bool { + &a * &b == b * a +} + +#[quickcheck] +fn quickcheck_unsigned_mul_associative(a: BigUint, b: BigUint, c: BigUint) -> bool { + (&a * &b) * &c == a * (b * c) +} + +#[quickcheck] +fn quickcheck_signed_mul_associative(a: BigInt, b: BigInt, c: BigInt) -> bool { + (&a * &b) * &c == a * (b * c) +} + +#[quickcheck] +fn quickcheck_unsigned_distributive(a: BigUint, b: BigUint, c: BigUint) -> bool { + &a * (&b + &c) == &a * b + a * c +} + +#[quickcheck] +fn quickcheck_signed_distributive(a: BigInt, b: BigInt, c: BigInt) -> bool { + &a * (&b + &c) == &a * b + a * c +} + +#[quickcheck] +///Tests that exactly one of a<b a>b a=b is true +fn quickcheck_unsigned_ge_le_eq_mut_exclusive(a: BigUint, b: BigUint) -> bool { + let gt_lt_eq = vec![a > b, a < b, a == b]; + gt_lt_eq + .iter() + .fold(0, |acc, e| if *e { acc + 1 } else { acc }) + == 1 +} + +#[quickcheck] +///Tests that exactly one of a<b a>b a=b is true +fn quickcheck_signed_ge_le_eq_mut_exclusive(a: BigInt, b: BigInt) -> bool { + let gt_lt_eq = vec![a > b, a < b, a == b]; + gt_lt_eq + .iter() + .fold(0, |acc, e| if *e { acc + 1 } else { acc }) + == 1 +} + +#[quickcheck] +/// Tests correctness of subtraction assuming addition is correct +fn quickcheck_unsigned_sub(a: BigUint, b: BigUint) -> bool { + if b < a { + &a - &b + b == a + } else { + &b - &a + a == b + } +} + +#[quickcheck] +/// Tests correctness of subtraction assuming addition is correct +fn quickcheck_signed_sub(a: BigInt, b: BigInt) -> bool { + if b < a { + &a - &b + b == a + } else { + &b - &a + a == b + } +} + +#[quickcheck] +fn quickcheck_unsigned_pow_zero(a: BigUint) -> bool { + a.pow(0_u32) == BigUint::one() +} + +#[quickcheck] +fn quickcheck_unsigned_pow_one(a: BigUint) -> bool { + a.pow(1_u32) == a +} + +#[quickcheck] +fn quickcheck_unsigned_sqrt(a: BigUint) -> bool { + (&a * &a).sqrt() == a +} + +#[quickcheck] +fn quickcheck_unsigned_cbrt(a: BigUint) -> bool { + (&a * &a * &a).cbrt() == a +} + +#[quickcheck] +fn quickcheck_signed_cbrt(a: BigInt) -> bool { + (&a * &a * &a).cbrt() == a +} + +#[quickcheck] +fn quickcheck_unsigned_conversion(a: BigUint, radix: u8) -> TestResult { + let radix = radix as u32; + if radix > 36 || radix < 2 { + return TestResult::discard(); + } + let string = a.to_str_radix(radix); + TestResult::from_bool(a == BigUint::from_str_radix(&string, radix).unwrap()) +} + +#[quickcheck] +fn quickcheck_signed_conversion(a: BigInt, radix: u8) -> TestResult { + let radix = radix as u32; + if radix > 36 || radix < 2 { + return TestResult::discard(); + } + let string = a.to_str_radix(radix); + TestResult::from_bool(a == BigInt::from_str_radix(&string, radix).unwrap()) +} + +#[test] +fn quicktest_shift() { + let gen = StdThreadGen::new(usize::max_value()); + let mut qc = QuickCheck::with_gen(gen); + + fn test_shr_unsigned(a: u64, shift: u8) -> TestResult { + let shift = (shift % 64) as usize; //shift at most 64 bits + let big_a = BigUint::from(a); + TestResult::from_bool(BigUint::from(a >> shift) == big_a >> shift) + } + + fn test_shr_signed(a: i64, shift: u8) -> TestResult { + let shift = (shift % 64) as usize; //shift at most 64 bits + let big_a = BigInt::from(a); + TestResult::from_bool(BigInt::from(a >> shift) == big_a >> shift) + } + + fn test_shl_unsigned(a: u32, shift: u8) -> TestResult { + let shift = (shift % 32) as usize; //shift at most 32 bits + let a = a as u64; //leave room for the shifted bits + let big_a = BigUint::from(a); + TestResult::from_bool(BigUint::from(a >> shift) == big_a >> shift) + } + + fn test_shl_signed(a: i32, shift: u8) -> TestResult { + let shift = (shift % 32) as usize; + let a = a as u64; //leave room for the shifted bits + let big_a = BigInt::from(a); + TestResult::from_bool(BigInt::from(a >> shift) == big_a >> shift) + } + + qc.quickcheck(test_shr_unsigned as fn(u64, u8) -> TestResult); + qc.quickcheck(test_shr_signed as fn(i64, u8) -> TestResult); + qc.quickcheck(test_shl_unsigned as fn(u32, u8) -> TestResult); + qc.quickcheck(test_shl_signed as fn(i32, u8) -> TestResult); +} diff --git a/third_party/rust/num-bigint/tests/rand.rs b/third_party/rust/num-bigint/tests/rand.rs new file mode 100644 index 0000000000..666b764d79 --- /dev/null +++ b/third_party/rust/num-bigint/tests/rand.rs @@ -0,0 +1,324 @@ +#![cfg(feature = "rand")] + +extern crate num_bigint; +extern crate num_traits; +extern crate rand; + +mod biguint { + use num_bigint::{BigUint, RandBigInt, RandomBits}; + use num_traits::Zero; + use rand::distributions::Uniform; + use rand::thread_rng; + use rand::{Rng, SeedableRng}; + + #[test] + fn test_rand() { + let mut rng = thread_rng(); + let n: BigUint = rng.gen_biguint(137); + assert!(n.bits() <= 137); + assert!(rng.gen_biguint(0).is_zero()); + } + + #[test] + fn test_rand_bits() { + let mut rng = thread_rng(); + let n: BigUint = rng.sample(&RandomBits::new(137)); + assert!(n.bits() <= 137); + let z: BigUint = rng.sample(&RandomBits::new(0)); + assert!(z.is_zero()); + } + + #[test] + fn test_rand_range() { + let mut rng = thread_rng(); + + for _ in 0..10 { + assert_eq!( + rng.gen_biguint_range(&BigUint::from(236u32), &BigUint::from(237u32)), + BigUint::from(236u32) + ); + } + + let l = BigUint::from(403469000u32 + 2352); + let u = BigUint::from(403469000u32 + 3513); + for _ in 0..1000 { + let n: BigUint = rng.gen_biguint_below(&u); + assert!(n < u); + + let n: BigUint = rng.gen_biguint_range(&l, &u); + assert!(n >= l); + assert!(n < u); + } + } + + #[test] + #[should_panic] + fn test_zero_rand_range() { + thread_rng().gen_biguint_range(&BigUint::from(54u32), &BigUint::from(54u32)); + } + + #[test] + #[should_panic] + fn test_negative_rand_range() { + let mut rng = thread_rng(); + let l = BigUint::from(2352u32); + let u = BigUint::from(3513u32); + // Switching u and l should fail: + let _n: BigUint = rng.gen_biguint_range(&u, &l); + } + + #[test] + fn test_rand_uniform() { + let mut rng = thread_rng(); + + let tiny = Uniform::new(BigUint::from(236u32), BigUint::from(237u32)); + for _ in 0..10 { + assert_eq!(rng.sample(&tiny), BigUint::from(236u32)); + } + + let l = BigUint::from(403469000u32 + 2352); + let u = BigUint::from(403469000u32 + 3513); + let below = Uniform::new(BigUint::zero(), u.clone()); + let range = Uniform::new(l.clone(), u.clone()); + for _ in 0..1000 { + let n: BigUint = rng.sample(&below); + assert!(n < u); + + let n: BigUint = rng.sample(&range); + assert!(n >= l); + assert!(n < u); + } + } + + fn seeded_value_stability<R: SeedableRng + RandBigInt>(expected: &[&str]) { + let mut seed = <R::Seed>::default(); + for (i, x) in seed.as_mut().iter_mut().enumerate() { + *x = (i as u8).wrapping_mul(191); + } + let mut rng = R::from_seed(seed); + for (i, &s) in expected.iter().enumerate() { + let n: BigUint = s.parse().unwrap(); + let r = rng.gen_biguint((1 << i) + i); + assert_eq!(n, r); + } + } + + #[test] + fn test_chacha_value_stability() { + const EXPECTED: &[&str] = &[ + "0", + "0", + "52", + "84", + "23780", + "86502865016", + "187057847319509867386", + "34045731223080904464438757488196244981910", + "23813754422987836414755953516143692594193066497413249270287126597896871975915808", + "57401636903146945411652549098818446911814352529449356393690984105383482703074355\ + 67088360974672291353736011718191813678720755501317478656550386324355699624671", + ]; + use rand::prng::ChaChaRng; + seeded_value_stability::<ChaChaRng>(EXPECTED); + } + + #[test] + fn test_isaac_value_stability() { + const EXPECTED: &[&str] = &[ + "1", + "4", + "3", + "649", + "89116", + "7730042024", + "20773149082453254949", + "35999009049239918667571895439206839620281", + "10191757312714088681302309313551624007714035309632506837271600807524767413673006", + "37805949268912387809989378008822038725134260145886913321084097194957861133272558\ + 43458183365174899239251448892645546322463253898288141861183340823194379722556", + ]; + use rand::prng::IsaacRng; + seeded_value_stability::<IsaacRng>(EXPECTED); + } + + #[test] + fn test_xorshift_value_stability() { + const EXPECTED: &[&str] = &[ + "1", + "0", + "37", + "395", + "181116", + "122718231117", + "1068467172329355695001", + "28246925743544411614293300167064395633287", + "12750053187017853048648861493745244146555950255549630854523304068318587267293038", + "53041498719137109355568081064978196049094604705283682101683207799515709404788873\ + 53417136457745727045473194367732849819278740266658219147356315674940229288531", + ]; + use rand::prng::XorShiftRng; + seeded_value_stability::<XorShiftRng>(EXPECTED); + } +} + +mod bigint { + use num_bigint::{BigInt, RandBigInt, RandomBits}; + use num_traits::Zero; + use rand::distributions::Uniform; + use rand::thread_rng; + use rand::{Rng, SeedableRng}; + + #[test] + fn test_rand() { + let mut rng = thread_rng(); + let n: BigInt = rng.gen_bigint(137); + assert!(n.bits() <= 137); + assert!(rng.gen_bigint(0).is_zero()); + } + + #[test] + fn test_rand_bits() { + let mut rng = thread_rng(); + let n: BigInt = rng.sample(&RandomBits::new(137)); + assert!(n.bits() <= 137); + let z: BigInt = rng.sample(&RandomBits::new(0)); + assert!(z.is_zero()); + } + + #[test] + fn test_rand_range() { + let mut rng = thread_rng(); + + for _ in 0..10 { + assert_eq!( + rng.gen_bigint_range(&BigInt::from(236), &BigInt::from(237)), + BigInt::from(236) + ); + } + + fn check(l: BigInt, u: BigInt) { + let mut rng = thread_rng(); + for _ in 0..1000 { + let n: BigInt = rng.gen_bigint_range(&l, &u); + assert!(n >= l); + assert!(n < u); + } + } + let l: BigInt = BigInt::from(403469000 + 2352); + let u: BigInt = BigInt::from(403469000 + 3513); + check(l.clone(), u.clone()); + check(-l.clone(), u.clone()); + check(-u.clone(), -l.clone()); + } + + #[test] + #[should_panic] + fn test_zero_rand_range() { + thread_rng().gen_bigint_range(&BigInt::from(54), &BigInt::from(54)); + } + + #[test] + #[should_panic] + fn test_negative_rand_range() { + let mut rng = thread_rng(); + let l = BigInt::from(2352); + let u = BigInt::from(3513); + // Switching u and l should fail: + let _n: BigInt = rng.gen_bigint_range(&u, &l); + } + + #[test] + fn test_rand_uniform() { + let mut rng = thread_rng(); + + let tiny = Uniform::new(BigInt::from(236u32), BigInt::from(237u32)); + for _ in 0..10 { + assert_eq!(rng.sample(&tiny), BigInt::from(236u32)); + } + + fn check(l: BigInt, u: BigInt) { + let mut rng = thread_rng(); + let range = Uniform::new(l.clone(), u.clone()); + for _ in 0..1000 { + let n: BigInt = rng.sample(&range); + assert!(n >= l); + assert!(n < u); + } + } + let l: BigInt = BigInt::from(403469000 + 2352); + let u: BigInt = BigInt::from(403469000 + 3513); + check(l.clone(), u.clone()); + check(-l.clone(), u.clone()); + check(-u.clone(), -l.clone()); + } + + fn seeded_value_stability<R: SeedableRng + RandBigInt>(expected: &[&str]) { + let mut seed = <R::Seed>::default(); + for (i, x) in seed.as_mut().iter_mut().enumerate() { + *x = (i as u8).wrapping_mul(191); + } + let mut rng = R::from_seed(seed); + for (i, &s) in expected.iter().enumerate() { + let n: BigInt = s.parse().unwrap(); + let r = rng.gen_bigint((1 << i) + i); + assert_eq!(n, r); + } + } + + #[test] + fn test_chacha_value_stability() { + const EXPECTED: &[&str] = &[ + "0", + "-6", + "-1", + "1321", + "-147247", + "8486373526", + "-272736656290199720696", + "2731152629387534140535423510744221288522", + "-28820024790651190394679732038637785320661450462089347915910979466834461433196572", + "501454570554170484799723603981439288209930393334472085317977614690773821680884844\ + 8530978478667288338327570972869032358120588620346111979053742269317702532328", + ]; + use rand::prng::ChaChaRng; + seeded_value_stability::<ChaChaRng>(EXPECTED); + } + + #[test] + fn test_isaac_value_stability() { + const EXPECTED: &[&str] = &[ + "1", + "0", + "5", + "113", + "-132240", + "-36348760761", + "-365690596708430705434", + "-14090753008246284277803606722552430292432", + "-26313941628626248579319341019368550803676255307056857978955881718727601479436059", + "-14563174552421101848999036239003801073335703811160945137332228646111920972691151\ + 88341090358094331641182310792892459091016794928947242043358702692294695845817", + ]; + use rand::prng::IsaacRng; + seeded_value_stability::<IsaacRng>(EXPECTED); + } + + #[test] + fn test_xorshift_value_stability() { + const EXPECTED: &[&str] = &[ + "-1", + "-4", + "11", + "-1802", + "966495", + "-62592045703", + "-602281783447192077116", + "-34335811410223060575607987996861632509125", + "29156580925282215857325937227200350542000244609280383263289720243118706105351199", + "49920038676141573457451407325930326489996232208489690499754573826911037849083623\ + 24546142615325187412887314466195222441945661833644117700809693098722026764846", + ]; + use rand::prng::XorShiftRng; + seeded_value_stability::<XorShiftRng>(EXPECTED); + } +} diff --git a/third_party/rust/num-bigint/tests/roots.rs b/third_party/rust/num-bigint/tests/roots.rs new file mode 100644 index 0000000000..39201fa928 --- /dev/null +++ b/third_party/rust/num-bigint/tests/roots.rs @@ -0,0 +1,186 @@ +extern crate num_bigint; +extern crate num_integer; +extern crate num_traits; + +#[cfg(feature = "rand")] +extern crate rand; + +mod biguint { + use num_bigint::BigUint; + use num_traits::{One, Pow, Zero}; + use std::{i32, u32}; + + fn check<T: Into<BigUint>>(x: T, n: u32) { + let x: BigUint = x.into(); + let root = x.nth_root(n); + println!("check {}.nth_root({}) = {}", x, n, root); + + if n == 2 { + assert_eq!(root, x.sqrt()) + } else if n == 3 { + assert_eq!(root, x.cbrt()) + } + + let lo = root.pow(n); + assert!(lo <= x); + assert_eq!(lo.nth_root(n), root); + if !lo.is_zero() { + assert_eq!((&lo - 1u32).nth_root(n), &root - 1u32); + } + + let hi = (&root + 1u32).pow(n); + assert!(hi > x); + assert_eq!(hi.nth_root(n), &root + 1u32); + assert_eq!((&hi - 1u32).nth_root(n), root); + } + + #[test] + fn test_sqrt() { + check(99u32, 2); + check(100u32, 2); + check(120u32, 2); + } + + #[test] + fn test_cbrt() { + check(8u32, 3); + check(26u32, 3); + } + + #[test] + fn test_nth_root() { + check(0u32, 1); + check(10u32, 1); + check(100u32, 4); + } + + #[test] + #[should_panic] + fn test_nth_root_n_is_zero() { + check(4u32, 0); + } + + #[test] + fn test_nth_root_big() { + let x = BigUint::from(123_456_789_u32); + let expected = BigUint::from(6u32); + + assert_eq!(x.nth_root(10), expected); + check(x, 10); + } + + #[test] + fn test_nth_root_googol() { + let googol = BigUint::from(10u32).pow(100u32); + + // perfect divisors of 100 + for &n in &[2, 4, 5, 10, 20, 25, 50, 100] { + let expected = BigUint::from(10u32).pow(100u32 / n); + assert_eq!(googol.nth_root(n), expected); + check(googol.clone(), n); + } + } + + #[test] + fn test_nth_root_twos() { + const EXP: u32 = 12; + const LOG2: usize = 1 << EXP; + let x = BigUint::one() << LOG2; + + // the perfect divisors are just powers of two + for exp in 1..EXP + 1 { + let n = 2u32.pow(exp); + let expected = BigUint::one() << (LOG2 / n as usize); + assert_eq!(x.nth_root(n), expected); + check(x.clone(), n); + } + + // degenerate cases should return quickly + assert!(x.nth_root(x.bits() as u32).is_one()); + assert!(x.nth_root(i32::MAX as u32).is_one()); + assert!(x.nth_root(u32::MAX).is_one()); + } + + #[cfg(feature = "rand")] + #[test] + fn test_roots_rand() { + use num_bigint::RandBigInt; + use rand::distributions::Uniform; + use rand::{thread_rng, Rng}; + + let mut rng = thread_rng(); + let bit_range = Uniform::new(0, 2048); + let sample_bits: Vec<_> = rng.sample_iter(&bit_range).take(100).collect(); + for bits in sample_bits { + let x = rng.gen_biguint(bits); + for n in 2..11 { + check(x.clone(), n); + } + check(x.clone(), 100); + } + } + + #[test] + fn test_roots_rand1() { + // A random input that found regressions + let s = "575981506858479247661989091587544744717244516135539456183849\ + 986593934723426343633698413178771587697273822147578889823552\ + 182702908597782734558103025298880194023243541613924361007059\ + 353344183590348785832467726433749431093350684849462759540710\ + 026019022227591412417064179299354183441181373862905039254106\ + 4781867"; + let x: BigUint = s.parse().unwrap(); + + check(x.clone(), 2); + check(x.clone(), 3); + check(x.clone(), 10); + check(x.clone(), 100); + } +} + +mod bigint { + use num_bigint::BigInt; + use num_traits::{Pow, Signed}; + + fn check(x: i64, n: u32) { + let big_x = BigInt::from(x); + let res = big_x.nth_root(n); + + if n == 2 { + assert_eq!(&res, &big_x.sqrt()) + } else if n == 3 { + assert_eq!(&res, &big_x.cbrt()) + } + + if big_x.is_negative() { + assert!(res.pow(n) >= big_x); + assert!((res - 1u32).pow(n) < big_x); + } else { + assert!(res.pow(n) <= big_x); + assert!((res + 1u32).pow(n) > big_x); + } + } + + #[test] + fn test_nth_root() { + check(-100, 3); + } + + #[test] + #[should_panic] + fn test_nth_root_x_neg_n_even() { + check(-100, 4); + } + + #[test] + #[should_panic] + fn test_sqrt_x_neg() { + check(-4, 2); + } + + #[test] + fn test_cbrt() { + check(8, 3); + check(-8, 3); + } +} diff --git a/third_party/rust/num-bigint/tests/serde.rs b/third_party/rust/num-bigint/tests/serde.rs new file mode 100644 index 0000000000..0f3d4868ed --- /dev/null +++ b/third_party/rust/num-bigint/tests/serde.rs @@ -0,0 +1,103 @@ +//! Test serialization and deserialization of `BigUint` and `BigInt` +//! +//! The serialized formats should not change, even if we change our +//! internal representation, because we want to preserve forward and +//! backward compatibility of serialized data! + +#![cfg(feature = "serde")] + +extern crate num_bigint; +extern crate num_traits; +extern crate serde_test; + +use num_bigint::{BigInt, BigUint}; +use num_traits::{One, Zero}; +use serde_test::{assert_tokens, Token}; + +#[test] +fn biguint_zero() { + let tokens = [Token::Seq { len: Some(0) }, Token::SeqEnd]; + assert_tokens(&BigUint::zero(), &tokens); +} + +#[test] +fn bigint_zero() { + let tokens = [ + Token::Tuple { len: 2 }, + Token::I8(0), + Token::Seq { len: Some(0) }, + Token::SeqEnd, + Token::TupleEnd, + ]; + assert_tokens(&BigInt::zero(), &tokens); +} + +#[test] +fn biguint_one() { + let tokens = [Token::Seq { len: Some(1) }, Token::U32(1), Token::SeqEnd]; + assert_tokens(&BigUint::one(), &tokens); +} + +#[test] +fn bigint_one() { + let tokens = [ + Token::Tuple { len: 2 }, + Token::I8(1), + Token::Seq { len: Some(1) }, + Token::U32(1), + Token::SeqEnd, + Token::TupleEnd, + ]; + assert_tokens(&BigInt::one(), &tokens); +} + +#[test] +fn bigint_negone() { + let tokens = [ + Token::Tuple { len: 2 }, + Token::I8(-1), + Token::Seq { len: Some(1) }, + Token::U32(1), + Token::SeqEnd, + Token::TupleEnd, + ]; + assert_tokens(&-BigInt::one(), &tokens); +} + +// Generated independently from python `hex(factorial(100))` +const FACTORIAL_100: &'static [u32] = &[ + 0x00000000, 0x00000000, 0x00000000, 0x2735c61a, 0xee8b02ea, 0xb3b72ed2, 0x9420c6ec, 0x45570cca, + 0xdf103917, 0x943a321c, 0xeb21b5b2, 0x66ef9a70, 0xa40d16e9, 0x28d54bbd, 0xdc240695, 0x964ec395, + 0x1b30, +]; + +#[test] +fn biguint_factorial_100() { + let n: BigUint = (1u8..101).product(); + + let mut tokens = vec![]; + tokens.push(Token::Seq { + len: Some(FACTORIAL_100.len()), + }); + tokens.extend(FACTORIAL_100.iter().map(|&u| Token::U32(u))); + tokens.push(Token::SeqEnd); + + assert_tokens(&n, &tokens); +} + +#[test] +fn bigint_factorial_100() { + let n: BigInt = (1i8..101).product(); + + let mut tokens = vec![]; + tokens.push(Token::Tuple { len: 2 }); + tokens.push(Token::I8(1)); + tokens.push(Token::Seq { + len: Some(FACTORIAL_100.len()), + }); + tokens.extend(FACTORIAL_100.iter().map(|&u| Token::U32(u))); + tokens.push(Token::SeqEnd); + tokens.push(Token::TupleEnd); + + assert_tokens(&n, &tokens); +} diff --git a/third_party/rust/num-bigint/tests/torture.rs b/third_party/rust/num-bigint/tests/torture.rs new file mode 100644 index 0000000000..4f073d31d9 --- /dev/null +++ b/third_party/rust/num-bigint/tests/torture.rs @@ -0,0 +1,43 @@ +#![cfg(feature = "rand")] + +extern crate num_bigint; +extern crate num_traits; +extern crate rand; + +use num_bigint::RandBigInt; +use num_traits::Zero; +use rand::prelude::*; + +fn test_mul_divide_torture_count(count: usize) { + let bits_max = 1 << 12; + let seed = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; + let mut rng = SmallRng::from_seed(seed); + + for _ in 0..count { + // Test with numbers of random sizes: + let xbits = rng.gen_range(0, bits_max); + let ybits = rng.gen_range(0, bits_max); + + let x = rng.gen_biguint(xbits); + let y = rng.gen_biguint(ybits); + + if x.is_zero() || y.is_zero() { + continue; + } + + let prod = &x * &y; + assert_eq!(&prod / &x, y); + assert_eq!(&prod / &y, x); + } +} + +#[test] +fn test_mul_divide_torture() { + test_mul_divide_torture_count(1000); +} + +#[test] +#[ignore] +fn test_mul_divide_torture_long() { + test_mul_divide_torture_count(1000000); +} |