chore: checkpoint before Python removal

This commit is contained in:
2026-03-26 22:33:59 +00:00
parent 683cec9307
commit e568ddf82a
29972 changed files with 11269302 additions and 2 deletions

View File

@@ -0,0 +1 @@
{"files":{".cargo_vcs_info.json":"7e84809a4d490368972e5ce46e7d00dc766ecc89719d0ff5c905151cc04f7f87",".travis.yml":"9691176250a106f1eac704985ce15a31d2e56f135e4a853383ea83bea9011bfc","Cargo.lock":"41104ce3db9343a1d38e589511cc9db8e4b7e8c69b61ec8907143f9751111671","Cargo.toml":"04a7ed71706ef6637f12982772ee3772074df403647e74c4c5830fc823555257","Cargo.toml.orig":"5a82a7d0e59fde3cc49427253e70e1a347c545a307f5f9b2cf34c9ccc5d2d1f8","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"b0845c5abc7b86e1b475d3102bc899ea33a56f7addac7bc700e06bc133d5bc04","RELEASES.md":"81b5fcac6dd5c7aed114c6ae4359d4cfed0cadf13c5667e291ac06b4bb114a4b","build.rs":"bf1b914225d60b380be17ef123c023549e0a4924a85852e8830fb0d1c7bcbb36","ci/rustup.sh":"c976bb2756da3876363b01fdbf06c13de20df421e5add45e4017c4df42ed06a6","ci/test_full.sh":"6934f41bfdc6bbc4e4e9b70745872892c869d57bb92c9c143e0c1ce0348d7fb9","src/algorithms/add.rs":"d499dc0a84c573fc2b5cb6a11fcaa31442cb79edab8949f43e3fd552f7a6dac9","src/algorithms/bits.rs":"4fc4047e8ee2ecba93dadca1c661c47244068f209a0896980e2cd01804f6ad32","src/algorithms/cmp.rs":"d2e855f37671c4ec66adaf2273799f2190b63e7c3c82493e1d213a9f95880e65","src/algorithms/div.rs":"a45f4e943936f78106517884f8853c09e79328b48e67e92fda17a4b74bcb5ffb","src/algorithms/gcd.rs":"49acad46acdc7444e300f319fc7d3c3508d5aeb20218ccff5874e2336213c2ab","src/algorithms/jacobi.rs":"d23083f1e91a1332df2482946c36114b535e9ed5b5299d6e3b1a80fed9348a67","src/algorithms/mac.rs":"398ddb16f79077da647c78655eb52b945208bf2364e6e07310c8bdbc50ff7e2b","src/algorithms/mod.rs":"691c54c0d79fe16eac5fc93df93e8f5cddfb2213eadc1ee04192fbf0722a9a22","src/algorithms/mod_inverse.rs":"28e3f8216e2c20d9826f25a35f65139d271a67f60712def19ad2d043e39d5127","src/algorithms/mul.rs":"c41bbebedd8b97a2a88314a9169a5ec0a7c62b7be3bc682f909e3a0b740a7a13","src/algorithms/shl.rs":"15cb609f57be538ffd771665fdd02cecf914371c7e3e8d3ec7fd37dd97a4dc28","src/algorithms/shr.rs":"4d77115e4ee9c02c99884e4f0e244a76a83658c6cd749f7191db716d90ea09ee","src/algorithms/sub.rs":"131f1ea479805a8f8219f3ee3e187eb012e18e1c26dac2af1f70b49ab5bed633","src/bigint.rs":"368d580b870577e58f2c6e6704f8437b258ecfcd4843a3aff6304a28d2262d5c","src/bigrand.rs":"1573ac01895e80f8c07704ae5e5bf2238540fbcc10990eca2c8669cb79bd2abc","src/biguint.rs":"75544e5ec3ebfb899109d7a1ebd281fa43fde997659329abf32e6e54865f5d13","src/lib.rs":"85a07c898613dc6ea8dc100f3c58798b47b1a622a211f15629712fa9fca95fad","src/macro.rs":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","src/macros.rs":"cba8549abeefdc999706ea87072b983033247099a6862b23d0022e70ef252996","src/monty.rs":"b7a6b3a1493e2b5be499f718da4de57e81321b8c88088ceec275f40b568544a6","src/prime.rs":"71e93ddc05099f5c737bffc1b5873e45d9a8fa9f2a675d9b3e4c82c414f56835","src/traits.rs":"96905addc17fc60a07db9f310a11702f855267ac910fbdf2066868482793979e","tests/bigint.rs":"7be015e36d6bef6e2037993c2ba76c5f42bd510fa5f60f6de5ae98674cb7a0b4","tests/bigint_bitwise.rs":"8de4bf70f1f1f75c3e404fd7958672106c02f37ccd8968afd7664ea3e75993ff","tests/bigint_scalar.rs":"6847c00352f263bb3a7e73c93293f4afc82d1f58f68a0d13f41bdc719c5826a4","tests/biguint.rs":"60710fda2937c8f0d859b37ab0f0c39d0a082c9b81a6e472e3e23a0f43f5119d","tests/biguint_scalar.rs":"d1c896c3ebb064124ff310a8ec8b0622e9cc75154130ff0aacb4ae8286df54f4","tests/consts/mod.rs":"f9ea5f40733e2f5f432803d830be9db929d91e5e5efd8510b07c6ced2fe554be","tests/macros/mod.rs":"2789b680dd14a770d5ceef430018be0ada85098d69e218c61c17214084c4f763","tests/modpow.rs":"0431b2867e03af87f16d0dcbf6e0cdc4fca8c97f3d492d00c5907161ad1b98a0","tests/rand.rs":"47b758e806b4ff48dd04fcad946751793e5b73b25a7dfa9d1996ba45a3227549","tests/roots.rs":"839838d7d04c61cdc97600b330db05b9dd02eaa8231a1af2b7c8c30c73b4138f","tests/serde.rs":"d24b6ea52179bf7f099beeee76b77d5e9332e7f8a63cb74401c6c7fbdaf3820d","tests/torture.rs":"cb416b37ba50587ba97a0bc9cdcd18a060853761baba0bf28742ba072f0a3179"},"package":"e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7"}

View File

@@ -0,0 +1,6 @@
{
"git": {
"sha1": "1eb690d9170870c186a2795071482cfa472a170a"
},
"path_in_vcs": ""
}

19
vendor/num-bigint-dig/.travis.yml vendored Normal file
View File

@@ -0,0 +1,19 @@
language: rust
rust:
- 1.56.0
- stable
- beta
- nightly
sudo: false
script:
- cargo build --verbose
- ./ci/test_full.sh
notifications:
email:
on_success: never
branches:
only:
- master
- next
- staging
- trying

277
vendor/num-bigint-dig/Cargo.lock generated vendored Normal file
View File

@@ -0,0 +1,277 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "arbitrary"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dde20b3d026af13f561bdd0f15edf01fc734f0dafcedbaf42bba506a9517f223"
[[package]]
name = "autocfg"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
[[package]]
name = "byteorder"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "getrandom"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "lazy_static"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
dependencies = [
"spin",
]
[[package]]
name = "libc"
version = "0.2.169"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a"
[[package]]
name = "libm"
version = "0.2.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8355be11b20d696c8f18f6cc018c4e372165b1fa8126cef092399c9951984ffa"
[[package]]
name = "num-bigint-dig"
version = "0.8.6"
dependencies = [
"arbitrary",
"lazy_static",
"libm",
"num-integer",
"num-iter",
"num-traits",
"rand",
"rand_chacha",
"rand_isaac",
"rand_xorshift",
"serde",
"serde_test",
"smallvec",
"zeroize",
]
[[package]]
name = "num-integer"
version = "0.1.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
dependencies = [
"num-traits",
]
[[package]]
name = "num-iter"
version = "0.1.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf"
dependencies = [
"autocfg",
"num-integer",
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "ppv-lite86"
version = "0.2.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77957b295656769bb8ad2b6a6b09d897d94f05c41b069aede1fcdaa675eaea04"
dependencies = [
"zerocopy",
]
[[package]]
name = "proc-macro2"
version = "1.0.92"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rand"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
dependencies = [
"libc",
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
dependencies = [
"getrandom",
]
[[package]]
name = "rand_isaac"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fac4373cd91b4f55722c553fb0f286edbb81ef3ff6eec7b99d1898a4110a0b28"
dependencies = [
"rand_core",
]
[[package]]
name = "rand_xorshift"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d25bf25ec5ae4a3f1b92f929810509a2f53d7dca2f50b794ff57e3face536c8f"
dependencies = [
"rand_core",
]
[[package]]
name = "serde"
version = "1.0.217"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02fc4265df13d6fa1d00ecff087228cc0a2b5f3c0e87e258d8b94a156e984c70"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.217"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a9bf7cf98d04a2b28aead066b7496853d4779c9cc183c440dbac457641e19a0"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_test"
version = "1.0.177"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f901ee573cab6b3060453d2d5f0bae4e6d628c23c0a962ff9b5f1d7c8d4f1ed"
dependencies = [
"serde",
]
[[package]]
name = "smallvec"
version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
dependencies = [
"arbitrary",
]
[[package]]
name = "spin"
version = "0.9.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
[[package]]
name = "syn"
version = "2.0.94"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "987bc0be1cdea8b10216bd06e2ca407d40b9543468fafd3ddfb02f36e77f71f3"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83"
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "zerocopy"
version = "0.7.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0"
dependencies = [
"byteorder",
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.7.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "zeroize"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde"

177
vendor/num-bigint-dig/Cargo.toml vendored Normal file
View File

@@ -0,0 +1,177 @@
# 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 are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2021"
rust-version = "1.56"
name = "num-bigint-dig"
version = "0.8.6"
authors = [
"dignifiedquire <dignifiedquire@gmail.com>",
"The Rust Project Developers",
]
build = "build.rs"
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Big integer implementation for Rust"
homepage = "https://github.com/dignifiedquire/num-bigint"
documentation = "https://docs.rs/num-bigint-dig"
readme = "README.md"
keywords = [
"mathematics",
"numerics",
"bignum",
]
categories = [
"algorithms",
"data-structures",
"science",
]
license = "MIT/Apache-2.0"
repository = "https://github.com/dignifiedquire/num-bigint"
[package.metadata.docs.rs]
features = [
"std",
"serde",
"rand",
"prime",
]
[features]
default = [
"std",
"u64_digit",
]
fuzz = [
"arbitrary",
"smallvec/arbitrary",
]
i128 = []
nightly = []
prime = ["rand/std_rng"]
std = [
"num-integer/std",
"num-traits/std",
"smallvec/write",
"rand/std",
"serde/std",
]
u64_digit = []
[lib]
name = "num_bigint_dig"
path = "src/lib.rs"
[[test]]
name = "bigint"
path = "tests/bigint.rs"
[[test]]
name = "bigint_bitwise"
path = "tests/bigint_bitwise.rs"
[[test]]
name = "bigint_scalar"
path = "tests/bigint_scalar.rs"
[[test]]
name = "biguint"
path = "tests/biguint.rs"
[[test]]
name = "biguint_scalar"
path = "tests/biguint_scalar.rs"
[[test]]
name = "modpow"
path = "tests/modpow.rs"
[[test]]
name = "rand"
path = "tests/rand.rs"
[[test]]
name = "roots"
path = "tests/roots.rs"
[[test]]
name = "serde"
path = "tests/serde.rs"
[[test]]
name = "torture"
path = "tests/torture.rs"
[dependencies.arbitrary]
version = "1.1.0"
optional = true
[dependencies.lazy_static]
version = "1.2.0"
features = ["spin_no_std"]
default-features = false
[dependencies.libm]
version = "0.2.1"
[dependencies.num-integer]
version = "0.1.39"
features = ["i128"]
default-features = false
[dependencies.num-iter]
version = "0.1.37"
default-features = false
[dependencies.num-traits]
version = "0.2.4"
features = ["i128"]
default-features = false
[dependencies.rand]
version = "0.8.3"
optional = true
default-features = false
[dependencies.serde]
version = "1.0"
features = ["alloc"]
optional = true
default-features = false
[dependencies.smallvec]
version = "1.10.0"
default-features = false
[dependencies.zeroize]
version = "1.5"
optional = true
default-features = false
[dev-dependencies.rand]
version = "0.8"
features = ["small_rng"]
[dev-dependencies.rand_chacha]
version = "0.3"
[dev-dependencies.rand_isaac]
version = "0.3"
[dev-dependencies.rand_xorshift]
version = "0.3"
[dev-dependencies.serde_test]
version = "1.0"

201
vendor/num-bigint-dig/LICENSE-APACHE vendored Normal file
View File

@@ -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.

25
vendor/num-bigint-dig/LICENSE-MIT vendored Normal file
View File

@@ -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.

82
vendor/num-bigint-dig/README.md vendored Normal file
View File

@@ -0,0 +1,82 @@
# num-bigint-dig
[![crate](https://img.shields.io/crates/v/num-bigint-dig.svg)](https://crates.io/crates/num-bigint-dig)
[![documentation](https://docs.rs/num-bigint-dig/badge.svg)](https://docs.rs/num-bigint-dig)
![minimum rustc 1.56](https://img.shields.io/badge/rustc-1.56+-red.svg)
[![Travis status](https://travis-ci.org/dignifiedquire/num-bigint.svg?branch=master)](https://travis-ci.org/dignifiedquire/num-bigint)
Big integer types for Rust, `BigInt` and `BigUint`.
> **Warning** This is a fork of [`rust-num/num-bigint`](https://github.com/rust-num/num-bigint) with a focus on providing functionality, needed to implement cryptographic operations.
## Usage
Add this to your `Cargo.toml`:
```toml
[dependencies]
num-bigint-dig = "^0.7"
```
and this to your crate root:
```rust
extern crate num_bigint_dig as num_bigint;
```
## Features
The `std` feature is enabled by default and mandatory to compile on older rust
version.
It is possible to use this crate on no_std target. If
you wish to compile for a target that does not have an `std` crate, you should
use `num-bigint` with `default-features = false`. All other sub-features should
be compatible with no_std. Note that in this mode, `num-bigint` still relies on
the alloc crate, so make sure you define a `global_allocator`.
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.
The `u64_digit` feature enables usage of larger internal "digits" (or otherwise known as "limbs"). Speeeding up almost all operations on architectures that have native support for it.
The `prime` feature gate enables algorithms and support for dealing with large primes.
## Releases
Release notes are available in [RELEASES.md](RELEASES.md).
## Compatibility
The `num-bigint` crate is tested for rustc 1.56 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-dig`** | MIT/Apache-2.0 | 1.56 | pure rust |
| [`num-bigint`] | MIT/Apache-2.0 | 1.15 | pure rust |
| [`ramp`] | Apache-2.0 | nightly | rust and inline assembly |
| [`rug`] | LGPL-3.0+ | 1.18 | bundles [GMP] via [`gmp-mpfr-sys`] |
| [`rust-gmp`] | MIT | stable? | links to [GMP] |
| [`apint`] | MIT/Apache-2.0 | 1.26 | pure rust (unfinished) |
[`num-bigint`]: https://crates.io/crates/num-bigint
[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
## Benchmarks
```
cargo bench --features prime
```

121
vendor/num-bigint-dig/RELEASES.md vendored Normal file
View File

@@ -0,0 +1,121 @@
# 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!

3
vendor/num-bigint-dig/build.rs vendored Normal file
View File

@@ -0,0 +1,3 @@
fn main() {
println!("cargo:rustc-cfg=has_i128");
}

12
vendor/num-bigint-dig/ci/rustup.sh vendored Executable file
View File

@@ -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

50
vendor/num-bigint-dig/ci/test_full.sh vendored Executable file
View File

@@ -0,0 +1,50 @@
#!/bin/bash
set -ex
echo Testing num-bigint on rustc ${TRAVIS_RUST_VERSION}
FEATURES="serde i128 u64_digit prime"
export RUST_BACKTRACE=1
# 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"
# It should build in no_std
if [[ "$TRAVIS_RUST_VERSION" == "nightly" ]]; then
rustup target add thumbv7m-none-eabi
cargo build --no-default-features --target=thumbv7m-none-eabi
# It should work in no_std on nightly.
# Note: Doctest might show an error: https://github.com/rust-lang/rust/issues/54010
# The "error" is wrong however, the doctests still run.
cargo test --no-default-features
fi
# 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"
# Ensure that feature also works in nostd context on nightly.
if [[ "$TRAVIS_RUST_VERSION" == "nightly" ]]; then
cargo build --verbose --no-default-features --features="$feature"
cargo test --verbose --no-default-features --features="$feature"
fi
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
cd benchmark_crate
cargo bench --all-features --no-run
fi

View File

@@ -0,0 +1,46 @@
use crate::big_digit::{BigDigit, DoubleBigDigit, BITS};
// Add with carry:
#[inline]
pub fn adc(a: BigDigit, b: BigDigit, acc: &mut DoubleBigDigit) -> BigDigit {
*acc += a as DoubleBigDigit;
*acc += b as DoubleBigDigit;
let lo = *acc as BigDigit;
*acc >>= BITS;
lo
}
// 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);
}

View File

@@ -0,0 +1,20 @@
use core::mem;
/// Find last set bit
/// fls(0) == 0, fls(u32::MAX) == 32
pub fn fls<T: num_traits::PrimInt>(v: T) -> usize {
mem::size_of::<T>() * 8 - v.leading_zeros() as usize
}
pub fn ilog2<T: num_traits::PrimInt>(v: T) -> usize {
fls(v) - 1
}
/// Divide two integers, and ceil the result.
pub fn idiv_ceil<T: num_traits::PrimInt>(a: T, b: T) -> T {
if a % b != T::zero() {
a / b + T::one()
} else {
a / b
}
}

View File

@@ -0,0 +1,49 @@
use core::cmp::Ordering::{self, Equal, Greater, Less};
use crate::big_digit::BigDigit;
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;
}
}
Equal
}
#[cfg(test)]
mod tests {
use crate::BigUint;
use num_traits::Num;
#[test]
fn test_eq() {
let a = BigUint::from_str_radix("265252859812191058636308480000000", 10).unwrap();
let b = BigUint::from_str_radix("26525285981219105863630848000000", 10).unwrap();
assert!(a != b);
assert_ne!(a, b);
let a = BigUint::from_str_radix("138995801145388806366366393471481216294", 10).unwrap();
let b = BigUint::from_str_radix("168653801169012228514850424976871974699", 10).unwrap();
assert!(a != b);
assert_ne!(a, b);
assert!(&a != &b);
assert_ne!(&a, &b);
}
}

View File

@@ -0,0 +1,139 @@
use core::cmp::Ordering;
use num_traits::{One, Zero};
use smallvec::SmallVec;
use crate::algorithms::{add2, cmp_slice, sub2};
use crate::big_digit::{self, BigDigit, DoubleBigDigit};
use crate::BigUint;
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)
}
/// 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]
pub 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 = divisor as DoubleBigDigit;
((lhs / rhs) as BigDigit, (lhs % rhs) as BigDigit)
}
pub fn div_rem(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[0] == 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) {
Ordering::Less => return (Zero::zero(), u.clone()),
Ordering::Equal => return (One::one(), Zero::zero()),
Ordering::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 mut a = u << shift;
let b = d << shift;
// 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: smallvec![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: SmallVec::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..]) == Ordering::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 >> shift)
}

View File

@@ -0,0 +1,751 @@
use crate::big_digit::{BigDigit, DoubleBigDigit, BITS};
use crate::bigint::Sign::*;
use crate::bigint::{BigInt, ToBigInt};
use crate::biguint::{BigUint, IntDigits};
use crate::integer::Integer;
use alloc::borrow::Cow;
use core::ops::Neg;
use num_traits::{One, Signed, Zero};
/// XGCD sets z to the greatest common divisor of a and b and returns z.
/// If extended is true, XGCD returns their value such that z = a*x + b*y.
///
/// Allow the inputs a and b to be zero or negative to GCD
/// with the following definitions.
///
/// If x or y are not nil, GCD sets their value such that z = a*x + b*y.
/// Regardless of the signs of a and b, z is always >= 0.
/// If a == b == 0, GCD sets z = x = y = 0.
/// If a == 0 and b != 0, GCD sets z = |b|, x = 0, y = sign(b) * 1.
/// If a != 0 and b == 0, GCD sets z = |a|, x = sign(a) * 1, y = 0.
pub fn xgcd(
a_in: &BigInt,
b_in: &BigInt,
extended: bool,
) -> (BigInt, Option<BigInt>, Option<BigInt>) {
//If a == b == 0, GCD sets z = x = y = 0.
if a_in.is_zero() && b_in.is_zero() {
if extended {
return (0.into(), Some(0.into()), Some(0.into()));
} else {
return (0.into(), None, None);
}
}
//If a == 0 and b != 0, GCD sets z = |b|, x = 0, y = sign(b) * 1.
// if a_in.is_zero() && !b_in.is_zero() {
if a_in.is_zero() {
if extended {
let mut y = BigInt::one();
if b_in.sign == Minus {
y.sign = Minus;
}
return (b_in.abs(), Some(0.into()), Some(y));
} else {
return (b_in.abs(), None, None);
}
}
//If a != 0 and b == 0, GCD sets z = |a|, x = sign(a) * 1, y = 0.
//if !a_in.is_zero() && b_in.is_zero() {
if b_in.is_zero() {
if extended {
let mut x = BigInt::one();
if a_in.sign == Minus {
x.sign = Minus;
}
return (a_in.abs(), Some(x), Some(0.into()));
} else {
return (a_in.abs(), None, None);
}
}
lehmer_gcd(a_in, b_in, extended)
}
/// lehmerGCD sets z to the greatest common divisor of a and b,
/// which both must be != 0, and returns z.
/// If x or y are not nil, their values are set such that z = a*x + b*y.
/// See Knuth, The Art of Computer Programming, Vol. 2, Section 4.5.2, Algorithm L.
/// This implementation uses the improved condition by Collins requiring only one
/// quotient and avoiding the possibility of single Word overflow.
/// See Jebelean, "Improving the multiprecision Euclidean algorithm",
/// Design and Implementation of Symbolic Computation Systems, pp 45-58.
/// The cosequences are updated according to Algorithm 10.45 from
/// Cohen et al. "Handbook of Elliptic and Hyperelliptic Curve Cryptography" pp 192.
fn lehmer_gcd(
a_in: &BigInt,
b_in: &BigInt,
extended: bool,
) -> (BigInt, Option<BigInt>, Option<BigInt>) {
let mut a = a_in.clone();
let mut b = b_in.clone();
//essential absolute value on both a & b
a.sign = Plus;
b.sign = Plus;
// `ua` (`ub`) tracks how many times input `a_in` has beeen accumulated into `a` (`b`).
let mut ua = if extended { Some(1.into()) } else { None };
let mut ub = if extended { Some(0.into()) } else { None };
// temp variables for multiprecision update
let mut q: BigInt = 0.into();
let mut r: BigInt = 0.into();
let mut s: BigInt = 0.into();
let mut t: BigInt = 0.into();
// Ensure that a >= b
if a < b {
core::mem::swap(&mut a, &mut b);
core::mem::swap(&mut ua, &mut ub);
}
// loop invariant A >= B
while b.len() > 1 {
// Attempt to calculate in single-precision using leading words of a and b.
let (u0, u1, v0, v1, even) = lehmer_simulate(&a, &b);
// multiprecision step
if v0 != 0 {
// Simulate the effect of the single-precision steps using cosequences.
// a = u0 * a + v0 * b
// b = u1 * a + v1 * b
lehmer_update(
&mut a, &mut b, &mut q, &mut r, &mut s, &mut t, u0, u1, v0, v1, even,
);
if extended {
// ua = u0 * ua + v0 * ub
// ub = u1 * ua + v1 * ub
lehmer_update(
ua.as_mut().unwrap(),
ub.as_mut().unwrap(),
&mut q,
&mut r,
&mut s,
&mut t,
u0,
u1,
v0,
v1,
even,
);
}
} else {
// Single-digit calculations failed to simulate any quotients.
euclid_udpate(
&mut a, &mut b, &mut ua, &mut ub, &mut q, &mut r, &mut s, &mut t, extended,
);
}
}
if b.len() > 0 {
// base case if b is a single digit
if a.len() > 1 {
// a is longer than a single word, so one update is needed
euclid_udpate(
&mut a, &mut b, &mut ua, &mut ub, &mut q, &mut r, &mut s, &mut t, extended,
);
}
if b.len() > 0 {
// a and b are both single word
let mut a_word = a.digits()[0];
let mut b_word = b.digits()[0];
if extended {
let mut ua_word: BigDigit = 1;
let mut ub_word: BigDigit = 0;
let mut va: BigDigit = 0;
let mut vb: BigDigit = 1;
let mut even = true;
while b_word != 0 {
let q = a_word / b_word;
let r = a_word % b_word;
a_word = b_word;
b_word = r;
let k = ua_word.wrapping_add(q.wrapping_mul(ub_word));
ua_word = ub_word;
ub_word = k;
let k = va.wrapping_add(q.wrapping_mul(vb));
va = vb;
vb = k;
even = !even;
}
t.data.set_digit(ua_word);
s.data.set_digit(va);
t.sign = if even { Plus } else { Minus };
s.sign = if even { Minus } else { Plus };
if let Some(ua) = ua.as_mut() {
t *= &*ua;
s *= ub.unwrap();
*ua = &t + &s;
}
} else {
while b_word != 0 {
let quotient = a_word % b_word;
a_word = b_word;
b_word = quotient;
}
}
a.digits_mut()[0] = a_word;
}
}
a.normalize();
//Sign fixing
let mut neg_a: bool = false;
if a_in.sign == Minus {
neg_a = true;
}
let y = if let Some(ref mut ua) = ua {
// y = (z - a * x) / b
//a_in*x
let mut tmp = a_in * &*ua;
if neg_a {
tmp.sign = tmp.sign.neg();
ua.sign = ua.sign.neg();
}
//z - (a_in * x)
tmp = &a - &tmp;
tmp = &tmp / b_in;
Some(tmp)
} else {
None
};
a.sign = Plus;
(a, ua, y)
}
/// Uses the lehemer algorithm.
/// Based on https://github.com/golang/go/blob/master/src/math/big/int.go#L612
/// If `extended` is set, the Bezout coefficients are calculated, otherwise they are `None`.
pub fn extended_gcd(
a_in: Cow<BigUint>,
b_in: Cow<BigUint>,
extended: bool,
) -> (BigInt, Option<BigInt>, Option<BigInt>) {
if a_in.is_zero() && b_in.is_zero() {
if extended {
return (b_in.to_bigint().unwrap(), Some(0.into()), Some(0.into()));
} else {
return (b_in.to_bigint().unwrap(), None, None);
}
}
if a_in.is_zero() {
if extended {
return (b_in.to_bigint().unwrap(), Some(0.into()), Some(1.into()));
} else {
return (b_in.to_bigint().unwrap(), None, None);
}
}
if b_in.is_zero() {
if extended {
return (a_in.to_bigint().unwrap(), Some(1.into()), Some(0.into()));
} else {
return (a_in.to_bigint().unwrap(), None, None);
}
}
let a_in = a_in.to_bigint().unwrap();
let b_in = b_in.to_bigint().unwrap();
let mut a = a_in.clone();
let mut b = b_in.clone();
// `ua` (`ub`) tracks how many times input `a_in` has beeen accumulated into `a` (`b`).
let mut ua = if extended { Some(1.into()) } else { None };
let mut ub = if extended { Some(0.into()) } else { None };
// Ensure that a >= b
if a < b {
core::mem::swap(&mut a, &mut b);
core::mem::swap(&mut ua, &mut ub);
}
let mut q: BigInt = 0.into();
let mut r: BigInt = 0.into();
let mut s: BigInt = 0.into();
let mut t: BigInt = 0.into();
while b.len() > 1 {
// Attempt to calculate in single-precision using leading words of a and b.
let (u0, u1, v0, v1, even) = lehmer_simulate(&a, &b);
// multiprecision step
if v0 != 0 {
// Simulate the effect of the single-precision steps using cosequences.
// a = u0 * a + v0 * b
// b = u1 * a + v1 * b
lehmer_update(
&mut a, &mut b, &mut q, &mut r, &mut s, &mut t, u0, u1, v0, v1, even,
);
if extended {
// ua = u0 * ua + v0 * ub
// ub = u1 * ua + v1 * ub
lehmer_update(
ua.as_mut().unwrap(),
ub.as_mut().unwrap(),
&mut q,
&mut r,
&mut s,
&mut t,
u0,
u1,
v0,
v1,
even,
);
}
} else {
// Single-digit calculations failed to simulate any quotients.
euclid_udpate(
&mut a, &mut b, &mut ua, &mut ub, &mut q, &mut r, &mut s, &mut t, extended,
);
}
}
if b.len() > 0 {
// base case if b is a single digit
if a.len() > 1 {
// a is longer than a single word, so one update is needed
euclid_udpate(
&mut a, &mut b, &mut ua, &mut ub, &mut q, &mut r, &mut s, &mut t, extended,
);
}
if b.len() > 0 {
// a and b are both single word
let mut a_word = a.digits()[0];
let mut b_word = b.digits()[0];
if extended {
let mut ua_word: BigDigit = 1;
let mut ub_word: BigDigit = 0;
let mut va: BigDigit = 0;
let mut vb: BigDigit = 1;
let mut even = true;
while b_word != 0 {
let q = a_word / b_word;
let r = a_word % b_word;
a_word = b_word;
b_word = r;
let k = ua_word.wrapping_add(q.wrapping_mul(ub_word));
ua_word = ub_word;
ub_word = k;
let k = va.wrapping_add(q.wrapping_mul(vb));
va = vb;
vb = k;
even = !even;
}
t.data.set_digit(ua_word);
s.data.set_digit(va);
t.sign = if even { Plus } else { Minus };
s.sign = if even { Minus } else { Plus };
if let Some(ua) = ua.as_mut() {
t *= &*ua;
s *= ub.unwrap();
*ua = &t + &s;
}
} else {
while b_word != 0 {
let quotient = a_word % b_word;
a_word = b_word;
b_word = quotient;
}
}
a.digits_mut()[0] = a_word;
}
}
a.normalize();
let y = if let Some(ref ua) = ua {
// y = (z - a * x) / b
Some((&a - (&a_in * ua)) / &b_in)
} else {
None
};
(a, ua, y)
}
/// Attempts to simulate several Euclidean update steps using leading digits of `a` and `b`.
/// It returns `u0`, `u1`, `v0`, `v1` such that `a` and `b` can be updated as:
/// a = u0 * a + v0 * b
/// b = u1 * a + v1 * b
///
/// Requirements: `a >= b` and `b.len() > 2`.
/// Since we are calculating with full words to avoid overflow, `even` (the returned bool)
/// is used to track the sign of cosequences.
/// For even iterations: `u0, v1 >= 0 && u1, v0 <= 0`
/// For odd iterations: `u0, v1 <= && u1, v0 >= 0`
#[inline]
fn lehmer_simulate(a: &BigInt, b: &BigInt) -> (BigDigit, BigDigit, BigDigit, BigDigit, bool) {
// m >= 2
let m = b.len();
// n >= m >= 2
let n = a.len();
// println!("a len is {:?}", a.len());
// println!("b len is {:?}", b.len());
// debug_assert!(m >= 2);
// debug_assert!(n >= m);
// extract the top word of bits from a and b
let h = a.digits()[n - 1].leading_zeros();
let mut a1: BigDigit = a.digits()[n - 1] << h
| ((a.digits()[n - 2] as DoubleBigDigit) >> (BITS as u32 - h)) as BigDigit;
// b may have implicit zero words in the high bits if the lengths differ
let mut a2: BigDigit = if n == m {
b.digits()[n - 1] << h
| ((b.digits()[n - 2] as DoubleBigDigit) >> (BITS as u32 - h)) as BigDigit
} else if n == m + 1 {
((b.digits()[n - 2] as DoubleBigDigit) >> (BITS as u32 - h)) as BigDigit
} else {
0
};
// odd, even tracking
let mut even = false;
let mut u0 = 0;
let mut u1 = 1;
let mut u2 = 0;
let mut v0 = 0;
let mut v1 = 0;
let mut v2 = 1;
// Calculate the quotient and cosequences using Collins' stoppting condition.
while a2 >= v2 && a1.wrapping_sub(a2) >= v1 + v2 {
let q = a1 / a2;
let r = a1 % a2;
a1 = a2;
a2 = r;
let k = u1 + q * u2;
u0 = u1;
u1 = u2;
u2 = k;
let k = v1 + q * v2;
v0 = v1;
v1 = v2;
v2 = k;
even = !even;
}
(u0, u1, v0, v1, even)
}
fn lehmer_update(
a: &mut BigInt,
b: &mut BigInt,
q: &mut BigInt,
r: &mut BigInt,
s: &mut BigInt,
t: &mut BigInt,
u0: BigDigit,
u1: BigDigit,
v0: BigDigit,
v1: BigDigit,
even: bool,
) {
t.data.set_digit(u0);
s.data.set_digit(v0);
if even {
t.sign = Plus;
s.sign = Minus
} else {
t.sign = Minus;
s.sign = Plus;
}
*t *= &*a;
*s *= &*b;
r.data.set_digit(u1);
q.data.set_digit(v1);
if even {
q.sign = Plus;
r.sign = Minus
} else {
q.sign = Minus;
r.sign = Plus;
}
*r *= &*a;
*q *= &*b;
*a = t + s;
*b = r + q;
}
fn euclid_udpate(
a: &mut BigInt,
b: &mut BigInt,
ua: &mut Option<BigInt>,
ub: &mut Option<BigInt>,
q: &mut BigInt,
r: &mut BigInt,
s: &mut BigInt,
t: &mut BigInt,
extended: bool,
) {
let (q_new, r_new) = a.div_rem(b);
*q = q_new;
*r = r_new;
core::mem::swap(a, b);
core::mem::swap(b, r);
if extended {
// ua, ub = ub, ua - q * ub
if let Some(ub) = ub.as_mut() {
if let Some(ua) = ua.as_mut() {
*t = ub.clone();
*s = &*ub * &*q;
*ub = &*ua - &*s;
*ua = t.clone();
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use core::str::FromStr;
use num_traits::FromPrimitive;
#[cfg(feature = "rand")]
use crate::bigrand::RandBigInt;
#[cfg(feature = "rand")]
use num_traits::{One, Zero};
#[cfg(feature = "rand")]
use rand::SeedableRng;
#[cfg(feature = "rand")]
use rand_xorshift::XorShiftRng;
#[cfg(feature = "rand")]
fn extended_gcd_euclid(a: Cow<BigUint>, b: Cow<BigUint>) -> (BigInt, BigInt, BigInt) {
// use crate::bigint::ToBigInt;
if a.is_zero() && b.is_zero() {
return (0.into(), 0.into(), 0.into());
}
let (mut s, mut old_s) = (BigInt::zero(), BigInt::one());
let (mut t, mut old_t) = (BigInt::one(), BigInt::zero());
let (mut r, mut old_r) = (b.to_bigint().unwrap(), a.to_bigint().unwrap());
while !r.is_zero() {
let quotient = &old_r / &r;
old_r = old_r - &quotient * &r;
core::mem::swap(&mut old_r, &mut r);
old_s = old_s - &quotient * &s;
core::mem::swap(&mut old_s, &mut s);
old_t = old_t - quotient * &t;
core::mem::swap(&mut old_t, &mut t);
}
(old_r, old_s, old_t)
}
#[test]
#[cfg(feature = "rand")]
fn test_extended_gcd_assumptions() {
let mut rng = XorShiftRng::from_seed([1u8; 16]);
for i in 1usize..100 {
for j in &[1usize, 64, 128] {
//println!("round {} - {}", i, j);
let a = rng.gen_biguint(i * j);
let b = rng.gen_biguint(i * j);
let (q, s_k, t_k) = extended_gcd(Cow::Borrowed(&a), Cow::Borrowed(&b), true);
let lhs = BigInt::from_biguint(Plus, a) * &s_k.unwrap();
let rhs = BigInt::from_biguint(Plus, b) * &t_k.unwrap();
assert_eq!(q.clone(), &lhs + &rhs, "{} = {} + {}", q, lhs, rhs);
}
}
}
#[test]
fn test_extended_gcd_example() {
// simple example for wikipedia
let a = BigUint::from_u32(240).unwrap();
let b = BigUint::from_u32(46).unwrap();
let (q, s_k, t_k) = extended_gcd(Cow::Owned(a), Cow::Owned(b), true);
assert_eq!(q, BigInt::from_i32(2).unwrap());
assert_eq!(s_k.unwrap(), BigInt::from_i32(-9).unwrap());
assert_eq!(t_k.unwrap(), BigInt::from_i32(47).unwrap());
}
#[test]
fn test_extended_gcd_example_not_extended() {
// simple example for wikipedia
let a = BigUint::from_u32(240).unwrap();
let b = BigUint::from_u32(46).unwrap();
let (q, s_k, t_k) = extended_gcd(Cow::Owned(a), Cow::Owned(b), false);
assert_eq!(q, BigInt::from_i32(2).unwrap());
assert_eq!(s_k, None);
assert_eq!(t_k, None);
}
#[test]
fn test_extended_gcd_example_wolfram() {
// https://www.wolframalpha.com/input/?i=ExtendedGCD%5B-565721958+,+4486780496%5D
// https://github.com/Chia-Network/oldvdf-competition/blob/master/tests/test_classgroup.py#L109
let a = BigInt::from_str("-565721958").unwrap();
let b = BigInt::from_str("4486780496").unwrap();
let (q, _s_k, _t_k) = xgcd(&a, &b, true);
assert_eq!(q, BigInt::from(2));
assert_eq!(_s_k, Some(BigInt::from(-1090996795)));
assert_eq!(_t_k, Some(BigInt::from(-137559848)));
}
#[test]
fn test_golang_bignum_negative() {
// a <= 0 || b <= 0
//d, x, y, a, b string
let gcd_test_cases = [
["0", "0", "0", "0", "0"],
["7", "0", "1", "0", "7"],
["7", "0", "-1", "0", "-7"],
["11", "1", "0", "11", "0"],
["7", "-1", "-2", "-77", "35"],
["935", "-3", "8", "64515", "24310"],
["935", "-3", "-8", "64515", "-24310"],
["935", "3", "-8", "-64515", "-24310"],
["1", "-9", "47", "120", "23"],
["7", "1", "-2", "77", "35"],
["935", "-3", "8", "64515", "24310"],
[
"935000000000000000",
"-3",
"8",
"64515000000000000000",
"24310000000000000000",
],
[
"1",
"-221",
"22059940471369027483332068679400581064239780177629666810348940098015901108344",
"98920366548084643601728869055592650835572950932266967461790948584315647051443",
"991",
],
];
for t in 0..gcd_test_cases.len() {
//d, x, y, a, b string
let d_case = BigInt::from_str(gcd_test_cases[t][0]).unwrap();
let x_case = BigInt::from_str(gcd_test_cases[t][1]).unwrap();
let y_case = BigInt::from_str(gcd_test_cases[t][2]).unwrap();
let a_case = BigInt::from_str(gcd_test_cases[t][3]).unwrap();
let b_case = BigInt::from_str(gcd_test_cases[t][4]).unwrap();
// println!("round is {:?}", t);
// println!("a len is {:?}", a_case.len());
// println!("b len is {:?}", b_case.len());
// println!("a is {:?}", &a_case);
// println!("b is {:?}", &b_case);
//testGcd(d, nil, nil, a, b)
//testGcd(d, x, y, a, b)
let (_d, _x, _y) = xgcd(&a_case, &b_case, false);
assert_eq!(_d, d_case);
assert_eq!(_x, None);
assert_eq!(_y, None);
let (_d, _x, _y) = xgcd(&a_case, &b_case, true);
assert_eq!(_d, d_case);
assert_eq!(_x.unwrap(), x_case);
assert_eq!(_y.unwrap(), y_case);
}
}
#[test]
#[cfg(feature = "rand")]
fn test_gcd_lehmer_euclid_extended() {
let mut rng = XorShiftRng::from_seed([1u8; 16]);
for i in 1usize..80 {
for j in &[1usize, 16, 24, 64, 128] {
//println!("round {} - {}", i, j);
let a = rng.gen_biguint(i * j);
let b = rng.gen_biguint(i * j);
let (q, s_k, t_k) = extended_gcd(Cow::Borrowed(&a), Cow::Borrowed(&b), true);
let expected = extended_gcd_euclid(Cow::Borrowed(&a), Cow::Borrowed(&b));
assert_eq!(q, expected.0);
assert_eq!(s_k.unwrap(), expected.1);
assert_eq!(t_k.unwrap(), expected.2);
}
}
}
#[test]
#[cfg(feature = "rand")]
fn test_gcd_lehmer_euclid_not_extended() {
let mut rng = XorShiftRng::from_seed([1u8; 16]);
for i in 1usize..80 {
for j in &[1usize, 16, 24, 64, 128] {
//println!("round {} - {}", i, j);
let a = rng.gen_biguint(i * j);
let b = rng.gen_biguint(i * j);
let (q, s_k, t_k) = extended_gcd(Cow::Borrowed(&a), Cow::Borrowed(&b), false);
let expected = extended_gcd_euclid(Cow::Borrowed(&a), Cow::Borrowed(&b));
assert_eq!(
q, expected.0,
"gcd({}, {}) = {} != {}",
&a, &b, &q, expected.0
);
assert_eq!(s_k, None);
assert_eq!(t_k, None);
}
}
}
}

View File

@@ -0,0 +1,100 @@
use crate::integer::Integer;
use num_traits::{One, Signed, Zero};
use crate::BigInt;
/// Jacobi returns the Jacobi symbol (x/y), either +1, -1, or 0.
/// The y argument must be an odd integer.
pub fn jacobi(x: &BigInt, y: &BigInt) -> isize {
if !y.is_odd() {
panic!(
"invalid arguments, y must be an odd integer,but got {:?}",
y
);
}
let mut a = x.clone();
let mut b = y.clone();
let mut j = 1;
if b.is_negative() {
if a.is_negative() {
j = -1;
}
b = -b;
}
loop {
if b.is_one() {
return j;
}
if a.is_zero() {
return 0;
}
a = a.mod_floor(&b);
if a.is_zero() {
return 0;
}
// a > 0
// handle factors of 2 in a
let s = a.trailing_zeros().unwrap();
if s & 1 != 0 {
let bmod8 = b.get_limb(0) & 7;
if bmod8 == 3 || bmod8 == 5 {
j = -j;
}
}
let c = &a >> s; // a = 2^s*c
// swap numerator and denominator
if b.get_limb(0) & 3 == 3 && c.get_limb(0) & 3 == 3 {
j = -j
}
a = b;
b = c;
}
}
#[cfg(test)]
mod tests {
use super::*;
use num_traits::FromPrimitive;
use crate::BigInt;
#[test]
fn test_jacobi() {
let cases = [
[0, 1, 1],
[0, -1, 1],
[1, 1, 1],
[1, -1, 1],
[0, 5, 0],
[1, 5, 1],
[2, 5, -1],
[-2, 5, -1],
[2, -5, -1],
[-2, -5, 1],
[3, 5, -1],
[5, 5, 0],
[-5, 5, 0],
[6, 5, 1],
[6, -5, 1],
[-6, 5, 1],
[-6, -5, -1],
];
for case in cases.iter() {
let x = BigInt::from_i64(case[0]).unwrap();
let y = BigInt::from_i64(case[1]).unwrap();
assert_eq!(case[2] as isize, jacobi(&x, &y), "jacobi({}, {})", x, y);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,27 @@
#![allow(clippy::many_single_char_names)]
mod add;
mod bits;
mod cmp;
mod div;
mod gcd;
mod jacobi;
mod mac;
mod mod_inverse;
mod mul;
mod shl;
mod shr;
mod sub;
pub use self::add::*;
pub use self::bits::*;
pub use self::cmp::*;
pub use self::div::*;
pub use self::gcd::*;
pub use self::jacobi::*;
pub use self::mac::*;
pub use self::mod_inverse::*;
pub use self::mul::*;
pub use self::shl::*;
pub use self::shr::*;
pub use self::sub::*;

View File

@@ -0,0 +1,100 @@
use alloc::borrow::Cow;
use num_traits::{One, Signed};
use crate::algorithms::extended_gcd;
use crate::{BigInt, BigUint};
/// Calculate the modular inverse of `g`.
/// Implementation is based on the naive version from wikipedia.
#[inline]
pub fn mod_inverse(g: Cow<BigUint>, n: Cow<BigUint>) -> Option<BigInt> {
let (d, x, _) = extended_gcd(g, n.clone(), true);
if !d.is_one() {
return None;
}
let x = x.unwrap();
if x.is_negative() {
Some(x + n.as_ref())
} else {
Some(x)
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec;
use num_traits::FromPrimitive;
use crate::integer::Integer;
use crate::traits::ModInverse;
#[test]
fn test_mod_inverse() {
let tests = [
["1234567", "458948883992"],
[
"239487239847",
"2410312426921032588552076022197566074856950548502459942654116941958108831682612228890093858261341614673227141477904012196503648957050582631942730706805009223062734745341073406696246014589361659774041027169249453200378729434170325843778659198143763193776859869524088940195577346119843545301547043747207749969763750084308926339295559968882457872412993810129130294592999947926365264059284647209730384947211681434464714438488520940127459844288859336526896320919633919",
],
["-10", "13"],
["-6193420858199668535", "2881"],
];
for test in &tests {
let element = BigInt::parse_bytes(test[0].as_bytes(), 10).unwrap();
let modulus = BigInt::parse_bytes(test[1].as_bytes(), 10).unwrap();
//println!("{} modinv {}", element, modulus);
let inverse = element.clone().mod_inverse(&modulus).unwrap();
//println!("inverse: {}", &inverse);
let cmp = (inverse * &element).mod_floor(&modulus);
assert_eq!(
cmp,
BigInt::one(),
"mod_inverse({}, {}) * {} % {} = {}, not 1",
&element,
&modulus,
&element,
&modulus,
&cmp
);
}
// exhaustive tests for small numbers
for n in 2..100 {
let modulus = BigInt::from_u64(n).unwrap();
for x in 1..n {
for sign in vec![1i64, -1i64] {
let element = BigInt::from_i64(sign * x as i64).unwrap();
let gcd = element.gcd(&modulus);
if !gcd.is_one() {
continue;
}
let inverse = element.clone().mod_inverse(&modulus).unwrap();
let cmp = (&inverse * &element).mod_floor(&modulus);
//println!("inverse: {}", &inverse);
assert_eq!(
cmp,
BigInt::one(),
"mod_inverse({}, {}) * {} % {} = {}, not 1",
&element,
&modulus,
&element,
&modulus,
&cmp
);
}
}
}
}
}

View File

@@ -0,0 +1,29 @@
use crate::algorithms::mac3;
use crate::big_digit::{BigDigit, DoubleBigDigit, BITS};
use crate::BigUint;
#[inline]
pub fn mul_with_carry(a: BigDigit, b: BigDigit, acc: &mut DoubleBigDigit) -> BigDigit {
*acc += (a as DoubleBigDigit) * (b as DoubleBigDigit);
let lo = *acc as BigDigit;
*acc >>= BITS;
lo
}
pub fn mul3(x: &[BigDigit], y: &[BigDigit]) -> BigUint {
let len = x.len() + y.len() + 1;
let mut prod = BigUint {
data: smallvec![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
}

View File

@@ -0,0 +1,37 @@
use alloc::borrow::Cow;
use core::iter::repeat;
use smallvec::SmallVec;
use crate::big_digit::BITS;
use crate::BigUint;
#[inline]
pub fn biguint_shl(n: Cow<BigUint>, bits: usize) -> BigUint {
let n_unit = bits / BITS;
let mut data = match n_unit {
0 => n.into_owned().data,
_ => {
let len = n_unit + n.data.len() + 1;
let mut data = SmallVec::with_capacity(len);
data.extend(repeat(0).take(n_unit));
data.extend(n.data.iter().cloned());
data
}
};
let n_bits = bits % BITS;
if n_bits > 0 {
let mut carry = 0;
for elem in data[n_unit..].iter_mut() {
let new_carry = *elem >> (BITS - n_bits);
*elem = (*elem << n_bits) | carry;
carry = new_carry;
}
if carry != 0 {
data.push(carry);
}
}
BigUint::new_native(data)
}

View File

@@ -0,0 +1,32 @@
use alloc::borrow::Cow;
use num_traits::Zero;
use smallvec::SmallVec;
use crate::big_digit::{BigDigit, BITS};
use crate::BigUint;
use crate::VEC_SIZE;
#[inline]
pub fn biguint_shr(n: Cow<BigUint>, bits: usize) -> BigUint {
let n_unit = bits / BITS;
if n_unit >= n.data.len() {
return Zero::zero();
}
let mut data: SmallVec<[BigDigit; VEC_SIZE]> = match n {
Cow::Borrowed(n) => n.data[n_unit..].into(),
Cow::Owned(n) => n.data[n_unit..].into(),
};
let n_bits = bits % BITS;
if n_bits > 0 {
let mut borrow = 0;
for elem in data.iter_mut().rev() {
let new_borrow = *elem << (BITS - n_bits);
*elem = (*elem >> n_bits) | borrow;
borrow = new_borrow;
}
}
BigUint::new_native(data)
}

View File

@@ -0,0 +1,124 @@
use core::cmp;
use core::cmp::Ordering::*;
use num_traits::Zero;
use smallvec::SmallVec;
use crate::algorithms::cmp_slice;
use crate::big_digit::{BigDigit, SignedDoubleBigDigit, BITS};
use crate::bigint::Sign::{self, *};
use crate::{BigUint, VEC_SIZE};
/// Subtract with borrow:
#[inline]
pub fn sbb(a: BigDigit, b: BigDigit, acc: &mut SignedDoubleBigDigit) -> BigDigit {
*acc += a as SignedDoubleBigDigit;
*acc -= b as SignedDoubleBigDigit;
let lo = *acc as BigDigit;
*acc >>= BITS;
lo
}
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: SmallVec<[BigDigit; VEC_SIZE]> = a.into();
sub2(&mut a, b);
(Plus, BigUint::new_native(a))
}
Less => {
let mut b: SmallVec<[BigDigit; VEC_SIZE]> = b.into();
sub2(&mut b, a);
(Minus, BigUint::new_native(b))
}
_ => (NoSign, Zero::zero()),
}
}
#[cfg(test)]
mod tests {
use super::*;
use num_traits::Num;
use crate::BigInt;
#[test]
fn test_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);
}
}

3401
vendor/num-bigint-dig/src/bigint.rs vendored Normal file

File diff suppressed because it is too large Load Diff

370
vendor/num-bigint-dig/src/bigrand.rs vendored Normal file
View File

@@ -0,0 +1,370 @@
//! Randomization of big integers
use rand::Rng;
use rand::distributions::uniform::{SampleBorrow, SampleUniform, UniformSampler};
use rand::prelude::*;
use crate::BigInt;
use crate::BigUint;
use crate::Sign::*;
use crate::big_digit::BigDigit;
use crate::bigint::{into_magnitude, magnitude};
use crate::integer::Integer;
#[cfg(feature = "prime")]
use num_iter::range_step;
use num_traits::Zero;
#[cfg(feature = "prime")]
use num_traits::{FromPrimitive, ToPrimitive};
#[cfg(feature = "prime")]
use crate::prime::probably_prime;
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 = smallvec![BigDigit::default(); digits + (rem > 0) as usize];
// `fill` is faster than many `gen::<u32>` calls
// Internally this calls `SeedableRng` where implementors are responsible for adjusting endianness for reproducable values.
self.fill(data.as_mut_slice());
if rem > 0 {
data[digits] >>= BITS - rem;
}
BigUint::new_native(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.r#gen() {
continue;
} else {
NoSign
}
} else if self.r#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<B1, B2>(low_b: B1, high_b: B2) -> Self
where
B1: SampleBorrow<Self::X> + Sized,
B2: SampleBorrow<Self::X> + Sized,
{
let low = low_b.borrow();
let high = high_b.borrow();
assert!(low < high);
UniformBigUint {
len: high - low,
base: low.clone(),
}
}
#[inline]
fn new_inclusive<B1, B2>(low_b: B1, high_b: B2) -> Self
where
B1: SampleBorrow<Self::X> + Sized,
B2: SampleBorrow<Self::X> + Sized,
{
Self::new(low_b, high_b.borrow() + 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, B1, B2>(low_b: B1, high_b: B2, rng: &mut R) -> Self::X
where
B1: SampleBorrow<Self::X> + Sized,
B2: SampleBorrow<Self::X> + Sized,
{
let low = low_b.borrow();
let high = high_b.borrow();
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<B1, B2>(low_b: B1, high_b: B2) -> Self
where
B1: SampleBorrow<Self::X> + Sized,
B2: SampleBorrow<Self::X> + Sized,
{
let low = low_b.borrow();
let high = high_b.borrow();
assert!(low < high);
UniformBigInt {
len: into_magnitude(high - low),
base: low.clone(),
}
}
#[inline]
fn new_inclusive<B1, B2>(low_b: B1, high_b: B2) -> Self
where
B1: SampleBorrow<Self::X> + Sized,
B2: SampleBorrow<Self::X> + Sized,
{
let low = low_b.borrow();
let high = high_b.borrow();
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, B1, B2>(low_b: B1, high_b: B2, rng: &mut R) -> Self::X
where
B1: SampleBorrow<Self::X> + Sized,
B2: SampleBorrow<Self::X> + Sized,
{
let low = low_b.borrow();
let high = high_b.borrow();
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)
}
}
/// A generic trait for generating random primes.
///
/// *Warning*: This is highly dependend on the provided random number generator,
/// to provide actually random primes.
///
/// # Example
#[cfg_attr(feature = "std", doc = " ```")]
#[cfg_attr(not(feature = "std"), doc = " ```ignore")]
/// extern crate rand;
/// extern crate num_bigint_dig as num_bigint;
///
/// use rand::thread_rng;
/// use num_bigint::RandPrime;
///
/// let mut rng = thread_rng();
/// let p = rng.gen_prime(1024);
/// assert_eq!(p.bits(), 1024);
/// ```
///
#[cfg(feature = "prime")]
pub trait RandPrime {
/// Generate a random prime number with as many bits as given.
fn gen_prime(&mut self, bits: usize) -> BigUint;
}
/// A list of small, prime numbers that allows us to rapidly
/// exclude some fraction of composite candidates when searching for a random
/// prime. This list is truncated at the point where smallPrimesProduct exceeds
/// a u64. It does not include two because we ensure that the candidates are
/// odd by construction.
#[cfg(feature = "prime")]
const SMALL_PRIMES: [u8; 15] = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53];
#[cfg(feature = "prime")]
lazy_static! {
/// The product of the values in SMALL_PRIMES and allows us
/// to reduce a candidate prime by this number and then determine whether it's
/// coprime to all the elements of SMALL_PRIMES without further BigUint
/// operations.
static ref SMALL_PRIMES_PRODUCT: BigUint = BigUint::from_u64(16_294_579_238_595_022_365).unwrap();
}
#[cfg(feature = "prime")]
impl<R: Rng + ?Sized> RandPrime for R {
fn gen_prime(&mut self, bit_size: usize) -> BigUint {
if bit_size < 2 {
panic!("prime size must be at least 2-bit");
}
let mut b = bit_size % 8;
if b == 0 {
b = 8;
}
let bytes_len = (bit_size + 7) / 8;
let mut bytes = alloc::vec![0u8; bytes_len];
loop {
self.fill_bytes(&mut bytes);
// Clear bits in the first byte to make sure the candidate has a size <= bits.
bytes[0] &= ((1u32 << (b as u32)) - 1) as u8;
// Don't let the value be too small, i.e, set the most significant two bits.
// Setting the top two bits, rather than just the top bit,
// means that when two of these values are multiplied together,
// the result isn't ever one bit short.
if b >= 2 {
bytes[0] |= 3u8.wrapping_shl(b as u32 - 2);
} else {
// Here b==1, because b cannot be zero.
bytes[0] |= 1;
if bytes_len > 1 {
bytes[1] |= 0x80;
}
}
// Make the value odd since an even number this large certainly isn't prime.
bytes[bytes_len - 1] |= 1u8;
let mut p = BigUint::from_bytes_be(&bytes);
// must always be a u64, as the SMALL_PRIMES_PRODUCT is a u64
let rem = (&p % &*SMALL_PRIMES_PRODUCT).to_u64().unwrap();
'next: for delta in range_step(0, 1 << 20, 2) {
let m = rem + delta;
for prime in &SMALL_PRIMES {
if m % u64::from(*prime) == 0 && (bit_size > 6 || m != u64::from(*prime)) {
continue 'next;
}
}
if delta > 0 {
p += BigUint::from_u64(delta).unwrap();
}
break;
}
// There is a tiny possibility that, by adding delta, we caused
// the number to be one bit too long. Thus we check bit length here.
if p.bits() == bit_size && probably_prime(&p, 20) {
return p;
}
}
}
}

3397
vendor/num-bigint-dig/src/biguint.rs vendored Normal file

File diff suppressed because it is too large Load Diff

269
vendor/num-bigint-dig/src/lib.rs vendored Normal file
View File

@@ -0,0 +1,269 @@
// Copyright 2018 Stichting Organism
//
// Copyright 2018 Friedel Ziegelmayer
//
// 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_dig as 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:
//!
#![cfg_attr(feature = "std", doc = " ```")]
#![cfg_attr(not(feature = "std"), doc = " ```ignore")]
//!
//! # #[cfg(feature = "rand")]
//! extern crate rand;
//! extern crate num_bigint_dig 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-dig` crate is tested for rustc 1.56 and greater.
//!
//! ## `no_std` compatibility
//!
//! This crate is compatible with `no_std` environments.
//!
//! Note however that it still requires the `alloc` crate, so the user should
//! ensure that they set a `global_allocator`.
//!
//! To use in no_std environment, add the crate as such in your `Cargo.toml`
//! file:
//!
//! ```toml
//! [dependencies]
//! num-bigint-dig = { version = "0.8", default-features=false }
//! ```
//!
//! Every features should be compatible with no_std environment, so feel free to
//! add features like `prime`, `i128`, etc...
#![doc(html_root_url = "https://docs.rs/num-bigint/0.2")]
#![no_std]
extern crate alloc;
#[cfg(feature = "std")]
extern crate std;
#[macro_use]
extern crate smallvec;
#[cfg(feature = "prime")]
#[macro_use]
extern crate lazy_static;
extern crate num_integer as integer;
use core::fmt;
#[cfg(feature = "std")]
use std::error::Error;
#[macro_use]
mod macros;
mod bigint;
mod biguint;
#[cfg(feature = "prime")]
pub mod prime;
pub mod algorithms;
pub mod traits;
pub use crate::traits::*;
#[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 crate::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)
}
}
#[cfg(feature = "std")]
impl Error for ParseBigIntError {
fn description(&self) -> &str {
self.__description()
}
}
pub use crate::biguint::BigUint;
pub use crate::biguint::IntoBigUint;
pub use crate::biguint::ToBigUint;
pub use crate::bigint::negate_sign;
pub use crate::bigint::BigInt;
pub use crate::bigint::IntoBigInt;
pub use crate::bigint::Sign;
pub use crate::bigint::ToBigInt;
#[cfg(feature = "rand")]
pub use crate::bigrand::{RandBigInt, RandomBits, UniformBigInt, UniformBigUint};
#[cfg(feature = "prime")]
pub use bigrand::RandPrime;
#[cfg(not(feature = "u64_digit"))]
pub const VEC_SIZE: usize = 8;
#[cfg(feature = "u64_digit")]
pub const VEC_SIZE: usize = 4;
mod big_digit {
/// A `BigDigit` is a `BigUint`'s composing element.
#[cfg(not(feature = "u64_digit"))]
pub type BigDigit = u32;
#[cfg(feature = "u64_digit")]
pub type BigDigit = u64;
/// A `DoubleBigDigit` is the internal type used to do the computations. Its
/// size is the double of the size of `BigDigit`.
#[cfg(not(feature = "u64_digit"))]
pub type DoubleBigDigit = u64;
#[cfg(feature = "u64_digit")]
pub type DoubleBigDigit = u128;
/// A `SignedDoubleBigDigit` is the signed version of `DoubleBigDigit`.
#[cfg(not(feature = "u64_digit"))]
pub type SignedDoubleBigDigit = i64;
#[cfg(feature = "u64_digit")]
pub type SignedDoubleBigDigit = i128;
// `DoubleBigDigit` size dependent
#[cfg(not(feature = "u64_digit"))]
pub const BITS: usize = 32;
#[cfg(feature = "u64_digit")]
pub const BITS: usize = 64;
#[cfg(not(feature = "u64_digit"))]
const LO_MASK: DoubleBigDigit = (-1i32 as DoubleBigDigit) >> BITS;
#[cfg(feature = "u64_digit")]
const LO_MASK: DoubleBigDigit = (-1i64 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)
}
}

0
vendor/num-bigint-dig/src/macro.rs vendored Normal file
View File

362
vendor/num-bigint-dig/src/macros.rs vendored Normal file
View File

@@ -0,0 +1,362 @@
#![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);
}
}
};
}
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)
}
}
};
}
macro_rules! forward_scalar_val_ref_binop {
(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 {
(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 {
(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;
#[inline]
fn $method(self, other: $scalar) -> $res {
$imp::$method(self, other as $promo)
}
}
impl $imp<$res> for $scalar {
type Output = $res;
#[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 {
#[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_val_val {
(impl $imp:ident<$scalar:ty> for $res:ty, $method:ident) => {
forward_scalar_val_ref_binop!(impl $imp<$scalar> for $res, $method);
forward_scalar_ref_val_binop!(impl $imp<$scalar> for $res, $method);
forward_scalar_ref_ref_binop!(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)
}
}
};
}

225
vendor/num-bigint-dig/src/monty.rs vendored Normal file
View File

@@ -0,0 +1,225 @@
#![allow(clippy::many_single_char_names)]
use alloc::vec::Vec;
use core::ops::Shl;
use num_traits::{One, Zero};
use crate::big_digit::{self, BigDigit, DoubleBigDigit, SignedDoubleBigDigit};
use crate::biguint::BigUint;
struct MontyReducer {
n0inv: BigDigit,
}
// k0 = -m**-1 mod 2**BITS. Algorithm from: Dumas, J.G. "On NewtonRaphson
// Iteration for Multiplicative Inverses Modulo Prime Powers".
fn inv_mod_alt(b: BigDigit) -> BigDigit {
assert_ne!(b & 1, 0);
let mut k0 = 2 - b as SignedDoubleBigDigit;
let mut t = (b - 1) as SignedDoubleBigDigit;
let mut i = 1;
while i < big_digit::BITS {
t = t.wrapping_mul(t);
k0 = k0.wrapping_mul(t + 1);
i <<= 1;
}
-k0 as BigDigit
}
impl MontyReducer {
fn new(n: &BigUint) -> Self {
let n0inv = inv_mod_alt(n.data[0]);
MontyReducer { n0inv }
}
}
/// Computes z mod m = x * y * 2 ** (-n*_W) mod m
/// assuming k = -1/m mod 2**_W
/// See Gueron, "Efficient Software Implementations of Modular Exponentiation".
/// https://eprint.iacr.org/2011/239.pdf
/// In the terminology of that paper, this is an "Almost Montgomery Multiplication":
/// x and y are required to satisfy 0 <= z < 2**(n*_W) and then the result
/// z is guaranteed to satisfy 0 <= z < 2**(n*_W), but it may not be < m.
fn montgomery(z: &mut BigUint, x: &BigUint, y: &BigUint, m: &BigUint, k: BigDigit, n: usize) {
// This code assumes x, y, m are all the same length, n.
// (required by addMulVVW and the for loop).
// It also assumes that x, y are already reduced mod m,
// or else the result will not be properly reduced.
assert!(
x.data.len() == n && y.data.len() == n && m.data.len() == n,
"{:?} {:?} {:?} {}",
x,
y,
m,
n
);
z.data.clear();
z.data.resize(n * 2, 0);
let mut c: BigDigit = 0;
for i in 0..n {
let c2 = add_mul_vvw(&mut z.data[i..n + i], &x.data, y.data[i]);
let t = z.data[i].wrapping_mul(k);
let c3 = add_mul_vvw(&mut z.data[i..n + i], &m.data, t);
let cx = c.wrapping_add(c2);
let cy = cx.wrapping_add(c3);
z.data[n + i] = cy;
c = if cx < c2 || cy < c3 { 1 } else { 0 };
}
if c == 0 {
let (first, second) = z.data.split_at_mut(n);
first.swap_with_slice(&mut second[..]);
} else {
let (mut first, second) = z.data.split_at_mut(n);
sub_vv(&mut first, &second, &m.data);
}
z.data.truncate(n);
}
#[inline]
fn add_mul_vvw(z: &mut [BigDigit], x: &[BigDigit], y: BigDigit) -> BigDigit {
let mut c = 0;
for (zi, xi) in z.iter_mut().zip(x.iter()) {
let (z1, z0) = mul_add_www(*xi, y, *zi);
let (c_, zi_) = add_ww(z0, c, 0);
*zi = zi_;
c = c_ + z1;
}
c
}
/// The resulting carry c is either 0 or 1.
#[inline]
fn sub_vv(z: &mut [BigDigit], x: &[BigDigit], y: &[BigDigit]) -> BigDigit {
let mut c = 0;
for (i, (xi, yi)) in x.iter().zip(y.iter()).enumerate().take(z.len()) {
let zi = xi.wrapping_sub(*yi).wrapping_sub(c);
z[i] = zi;
// see "Hacker's Delight", section 2-12 (overflow detection)
c = ((yi & !xi) | ((yi | !xi) & zi)) >> (big_digit::BITS - 1)
}
c
}
/// z1<<_W + z0 = x+y+c, with c == 0 or 1
#[inline]
fn add_ww(x: BigDigit, y: BigDigit, c: BigDigit) -> (BigDigit, BigDigit) {
let yc = y.wrapping_add(c);
let z0 = x.wrapping_add(yc);
let z1 = if z0 < x || yc < y { 1 } else { 0 };
(z1, z0)
}
/// z1 << _W + z0 = x * y + c
#[inline]
fn mul_add_www(x: BigDigit, y: BigDigit, c: BigDigit) -> (BigDigit, BigDigit) {
let z = x as DoubleBigDigit * y as DoubleBigDigit + c as DoubleBigDigit;
((z >> big_digit::BITS) as BigDigit, z as BigDigit)
}
/// Calculates x ** y mod m using a fixed, 4-bit window.
pub fn monty_modpow(x: &BigUint, y: &BigUint, m: &BigUint) -> BigUint {
assert!(m.data[0] & 1 == 1);
let mr = MontyReducer::new(m);
let num_words = m.data.len();
let mut x = x.clone();
// We want the lengths of x and m to be equal.
// It is OK if x >= m as long as len(x) == len(m).
if x.data.len() > num_words {
x %= m;
// Note: now len(x) <= numWords, not guaranteed ==.
}
if x.data.len() < num_words {
x.data.resize(num_words, 0);
}
// rr = 2**(2*_W*len(m)) mod m
let mut rr = BigUint::one();
rr = (rr.shl(2 * num_words * big_digit::BITS)) % m;
if rr.data.len() < num_words {
rr.data.resize(num_words, 0);
}
// one = 1, with equal length to that of m
let mut one = BigUint::one();
one.data.resize(num_words, 0);
let n = 4;
// powers[i] contains x^i
let mut powers = Vec::with_capacity(1 << n);
let mut v1 = BigUint::zero();
montgomery(&mut v1, &one, &rr, m, mr.n0inv, num_words);
powers.push(v1);
let mut v2 = BigUint::zero();
montgomery(&mut v2, &x, &rr, m, mr.n0inv, num_words);
powers.push(v2);
for i in 2..1 << n {
let mut r = BigUint::zero();
montgomery(&mut r, &powers[i - 1], &powers[1], m, mr.n0inv, num_words);
powers.push(r);
}
// initialize z = 1 (Montgomery 1)
let mut z = powers[0].clone();
z.data.resize(num_words, 0);
let mut zz = BigUint::zero();
zz.data.resize(num_words, 0);
// same windowed exponent, but with Montgomery multiplications
for i in (0..y.data.len()).rev() {
let mut yi = y.data[i];
let mut j = 0;
while j < big_digit::BITS {
if i != y.data.len() - 1 || j != 0 {
montgomery(&mut zz, &z, &z, m, mr.n0inv, num_words);
montgomery(&mut z, &zz, &zz, m, mr.n0inv, num_words);
montgomery(&mut zz, &z, &z, m, mr.n0inv, num_words);
montgomery(&mut z, &zz, &zz, m, mr.n0inv, num_words);
}
montgomery(
&mut zz,
&z,
&powers[(yi >> (big_digit::BITS - n)) as usize],
m,
mr.n0inv,
num_words,
);
core::mem::swap(&mut z, &mut zz);
yi <<= n;
j += n;
}
}
// convert to regular number
montgomery(&mut zz, &z, &one, m, mr.n0inv, num_words);
zz.normalize();
// One last reduction, just in case.
// See golang.org/issue/13907.
if &zz >= m {
// Common case is m has high bit set; in that case,
// since zz is the same length as m, there can be just
// one multiple of m to remove. Just subtract.
// We think that the subtract should be sufficient in general,
// so do that unconditionally, but double-check,
// in case our beliefs are wrong.
// The div is not expected to be reached.
zz -= m;
if &zz >= m {
zz %= m;
}
}
zz.normalize();
zz
}

673
vendor/num-bigint-dig/src/prime.rs vendored Normal file
View File

@@ -0,0 +1,673 @@
// https://github.com/RustCrypto/RSA/blob/master/src/prime.rs
//! Implements probabilistic prime checkers.
use alloc::vec;
use integer::Integer;
use num_traits::{FromPrimitive, One, ToPrimitive, Zero};
use rand::rngs::StdRng;
use rand::SeedableRng;
use crate::algorithms::jacobi;
use crate::big_digit;
use crate::bigrand::RandBigInt;
use crate::Sign::Plus;
use crate::{BigInt, BigUint, IntoBigUint};
lazy_static! {
pub(crate) static ref BIG_1: BigUint = BigUint::one();
pub(crate) static ref BIG_2: BigUint = BigUint::from_u64(2).unwrap();
pub(crate) static ref BIG_3: BigUint = BigUint::from_u64(3).unwrap();
pub(crate) static ref BIG_64: BigUint = BigUint::from_u64(64).unwrap();
}
const PRIMES_A: u64 = 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23 * 37;
const PRIMES_B: u64 = 29 * 31 * 41 * 43 * 47 * 53;
/// Records the primes < 64.
const PRIME_BIT_MASK: u64 = 1 << 2
| 1 << 3
| 1 << 5
| 1 << 7
| 1 << 11
| 1 << 13
| 1 << 17
| 1 << 19
| 1 << 23
| 1 << 29
| 1 << 31
| 1 << 37
| 1 << 41
| 1 << 43
| 1 << 47
| 1 << 53
| 1 << 59
| 1 << 61;
/// ProbablyPrime reports whether x is probably prime,
/// applying the Miller-Rabin test with n pseudorandomly chosen bases
/// as well as a Baillie-PSW test.
///
/// If x is prime, ProbablyPrime returns true.
/// If x is chosen randomly and not prime, ProbablyPrime probably returns false.
/// The probability of returning true for a randomly chosen non-prime is at most ¼ⁿ.
///
/// ProbablyPrime is 100% accurate for inputs less than 2⁶⁴.
/// See Menezes et al., Handbook of Applied Cryptography, 1997, pp. 145-149,
/// and FIPS 186-4 Appendix F for further discussion of the error probabilities.
///
/// ProbablyPrime is not suitable for judging primes that an adversary may
/// have crafted to fool the test.
///
/// This is a port of `ProbablyPrime` from the go std lib.
pub fn probably_prime(x: &BigUint, n: usize) -> bool {
if x.is_zero() {
return false;
}
if x < &*BIG_64 {
return (PRIME_BIT_MASK & (1 << x.to_u64().unwrap())) != 0;
}
if x.is_even() {
return false;
}
let r_a = &(x % PRIMES_A);
let r_b = &(x % PRIMES_B);
if (r_a % 3u32).is_zero()
|| (r_a % 5u32).is_zero()
|| (r_a % 7u32).is_zero()
|| (r_a % 11u32).is_zero()
|| (r_a % 13u32).is_zero()
|| (r_a % 17u32).is_zero()
|| (r_a % 19u32).is_zero()
|| (r_a % 23u32).is_zero()
|| (r_a % 37u32).is_zero()
|| (r_b % 29u32).is_zero()
|| (r_b % 31u32).is_zero()
|| (r_b % 41u32).is_zero()
|| (r_b % 43u32).is_zero()
|| (r_b % 47u32).is_zero()
|| (r_b % 53u32).is_zero()
{
return false;
}
probably_prime_miller_rabin(x, n + 1, true) && probably_prime_lucas(x)
}
const NUMBER_OF_PRIMES: usize = 127;
const PRIME_GAP: [u64; 167] = [
2, 2, 4, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4, 2, 4, 14, 4, 6,
2, 10, 2, 6, 6, 4, 6, 6, 2, 10, 2, 4, 2, 12, 12, 4, 2, 4, 6, 2, 10, 6, 6, 6, 2, 6, 4, 2, 10,
14, 4, 2, 4, 14, 6, 10, 2, 4, 6, 8, 6, 6, 4, 6, 8, 4, 8, 10, 2, 10, 2, 6, 4, 6, 8, 4, 2, 4, 12,
8, 4, 8, 4, 6, 12, 2, 18, 6, 10, 6, 6, 2, 6, 10, 6, 6, 2, 6, 6, 4, 2, 12, 10, 2, 4, 6, 6, 2,
12, 4, 6, 8, 10, 8, 10, 8, 6, 6, 4, 8, 6, 4, 8, 4, 14, 10, 12, 2, 10, 2, 4, 2, 10, 14, 4, 2, 4,
14, 4, 2, 4, 20, 4, 8, 10, 8, 4, 6, 6, 14, 4, 6, 6, 8, 6, 12,
];
const INCR_LIMIT: usize = 0x10000;
/// Calculate the next larger prime, given a starting number `n`.
pub fn next_prime(n: &BigUint) -> BigUint {
if n < &*BIG_2 {
return 2u32.into_biguint().unwrap();
}
// We want something larger than our current number.
let mut res = n + &*BIG_1;
// Ensure we are odd.
res |= &*BIG_1;
// Handle values up to 7.
if let Some(val) = res.to_u64() {
if val < 7 {
return res;
}
}
let nbits = res.bits();
let prime_limit = if nbits / 2 >= NUMBER_OF_PRIMES {
NUMBER_OF_PRIMES - 1
} else {
nbits / 2
};
// Compute the residues modulo small odd primes
let mut moduli = vec![BigUint::zero(); prime_limit];
'outer: loop {
let mut prime = 3;
for i in 0..prime_limit {
moduli[i] = &res % prime;
prime += PRIME_GAP[i];
}
// Check residues
let mut difference: usize = 0;
for incr in (0..INCR_LIMIT as u64).step_by(2) {
let mut prime: u64 = 3;
let mut cancel = false;
for i in 0..prime_limit {
let r = (&moduli[i] + incr) % prime;
prime += PRIME_GAP[i];
if r.is_zero() {
cancel = true;
break;
}
}
if !cancel {
res += difference;
difference = 0;
if probably_prime(&res, 20) {
break 'outer;
}
}
difference += 2;
}
res += difference;
}
res
}
/// Reports whether n passes reps rounds of the Miller-Rabin primality test, using pseudo-randomly chosen bases.
/// If `force2` is true, one of the rounds is forced to use base 2.
///
/// See Handbook of Applied Cryptography, p. 139, Algorithm 4.24.
pub fn probably_prime_miller_rabin(n: &BigUint, reps: usize, force2: bool) -> bool {
// println!("miller-rabin: {}", n);
let nm1 = n - &*BIG_1;
// determine q, k such that nm1 = q << k
let k = nm1.trailing_zeros().unwrap() as usize;
let q = &nm1 >> k;
let nm3 = n - &*BIG_2;
let mut rng = StdRng::seed_from_u64(n.get_limb(0) as u64);
'nextrandom: for i in 0..reps {
let x = if i == reps - 1 && force2 {
BIG_2.clone()
} else {
rng.gen_biguint_below(&nm3) + &*BIG_2
};
let mut y = x.modpow(&q, n);
if y.is_one() || y == nm1 {
continue;
}
for _ in 1..k {
y = y.modpow(&*BIG_2, n);
if y == nm1 {
continue 'nextrandom;
}
if y.is_one() {
return false;
}
}
return false;
}
true
}
/// Reports whether n passes the "almost extra strong" Lucas probable prime test,
/// using Baillie-OEIS parameter selection. This corresponds to "AESLPSP" on Jacobsen's tables (link below).
/// The combination of this test and a Miller-Rabin/Fermat test with base 2 gives a Baillie-PSW test.
///
///
/// References:
///
/// Baillie and Wagstaff, "Lucas Pseudoprimes", Mathematics of Computation 35(152),
/// October 1980, pp. 1391-1417, especially page 1401.
/// http://www.ams.org/journals/mcom/1980-35-152/S0025-5718-1980-0583518-6/S0025-5718-1980-0583518-6.pdf
///
/// Grantham, "Frobenius Pseudoprimes", Mathematics of Computation 70(234),
/// March 2000, pp. 873-891.
/// http://www.ams.org/journals/mcom/2001-70-234/S0025-5718-00-01197-2/S0025-5718-00-01197-2.pdf
///
/// Baillie, "Extra strong Lucas pseudoprimes", OEIS A217719, https://oeis.org/A217719.
///
/// Jacobsen, "Pseudoprime Statistics, Tables, and Data", http://ntheory.org/pseudoprimes.html.
///
/// Nicely, "The Baillie-PSW Primality Test", http://www.trnicely.net/misc/bpsw.html.
/// (Note that Nicely's definition of the "extra strong" test gives the wrong Jacobi condition,
/// as pointed out by Jacobsen.)
///
/// Crandall and Pomerance, Prime Numbers: A Computational Perspective, 2nd ed.
/// Springer, 2005.
pub fn probably_prime_lucas(n: &BigUint) -> bool {
// println!("lucas: {}", n);
// Discard 0, 1.
if n.is_zero() || n.is_one() {
return false;
}
// Two is the only even prime.
if n.to_u64() == Some(2) {
return false;
}
// Baillie-OEIS "method C" for choosing D, P, Q,
// as in https://oeis.org/A217719/a217719.txt:
// try increasing P ≥ 3 such that D = P² - 4 (so Q = 1)
// until Jacobi(D, n) = -1.
// The search is expected to succeed for non-square n after just a few trials.
// After more than expected failures, check whether n is square
// (which would cause Jacobi(D, n) = 1 for all D not dividing n).
let mut p = 3u64;
let n_int = BigInt::from_biguint(Plus, n.clone());
loop {
if p > 10000 {
// This is widely believed to be impossible.
// If we get a report, we'll want the exact number n.
panic!("internal error: cannot find (D/n) = -1 for {:?}", n)
}
let d_int = BigInt::from_u64(p * p - 4).unwrap();
let j = jacobi(&d_int, &n_int);
if j == -1 {
break;
}
if j == 0 {
// d = p²-4 = (p-2)(p+2).
// If (d/n) == 0 then d shares a prime factor with n.
// Since the loop proceeds in increasing p and starts with p-2==1,
// the shared prime factor must be p+2.
// If p+2 == n, then n is prime; otherwise p+2 is a proper factor of n.
return n_int.to_i64() == Some(p as i64 + 2);
}
if p == 40 {
// We'll never find (d/n) = -1 if n is a square.
// If n is a non-square we expect to find a d in just a few attempts on average.
// After 40 attempts, take a moment to check if n is indeed a square.
let t1 = n.sqrt();
let t1 = &t1 * &t1;
if &t1 == n {
return false;
}
}
p += 1;
}
// Grantham definition of "extra strong Lucas pseudoprime", after Thm 2.3 on p. 876
// (D, P, Q above have become Δ, b, 1):
//
// Let U_n = U_n(b, 1), V_n = V_n(b, 1), and Δ = b²-4.
// An extra strong Lucas pseudoprime to base b is a composite n = 2^r s + Jacobi(Δ, n),
// where s is odd and gcd(n, 2*Δ) = 1, such that either (i) U_s ≡ 0 mod n and V_s ≡ ±2 mod n,
// or (ii) V_{2^t s} ≡ 0 mod n for some 0 ≤ t < r-1.
//
// We know gcd(n, Δ) = 1 or else we'd have found Jacobi(d, n) == 0 above.
// We know gcd(n, 2) = 1 because n is odd.
//
// Arrange s = (n - Jacobi(Δ, n)) / 2^r = (n+1) / 2^r.
let mut s = n + &*BIG_1;
let r = s.trailing_zeros().unwrap() as usize;
s = &s >> r;
let nm2 = n - &*BIG_2; // n - 2
// We apply the "almost extra strong" test, which checks the above conditions
// except for U_s ≡ 0 mod n, which allows us to avoid computing any U_k values.
// Jacobsen points out that maybe we should just do the full extra strong test:
// "It is also possible to recover U_n using Crandall and Pomerance equation 3.13:
// U_n = D^-1 (2V_{n+1} - PV_n) allowing us to run the full extra-strong test
// at the cost of a single modular inversion. This computation is easy and fast in GMP,
// so we can get the full extra-strong test at essentially the same performance as the
// almost extra strong test."
// Compute Lucas sequence V_s(b, 1), where:
//
// V(0) = 2
// V(1) = P
// V(k) = P V(k-1) - Q V(k-2).
//
// (Remember that due to method C above, P = b, Q = 1.)
//
// In general V(k) = α^k + β^k, where α and β are roots of x² - Px + Q.
// Crandall and Pomerance (p.147) observe that for 0 ≤ j ≤ k,
//
// V(j+k) = V(j)V(k) - V(k-j).
//
// So in particular, to quickly double the subscript:
//
// V(2k) = V(k)² - 2
// V(2k+1) = V(k) V(k+1) - P
//
// We can therefore start with k=0 and build up to k=s in log₂(s) steps.
let mut vk = BIG_2.clone();
let mut vk1 = BigUint::from_u64(p).unwrap();
for i in (0..s.bits()).rev() {
if is_bit_set(&s, i) {
// k' = 2k+1
// V(k') = V(2k+1) = V(k) V(k+1) - P
let t1 = (&vk * &vk1) + n - p;
vk = &t1 % n;
// V(k'+1) = V(2k+2) = V(k+1)² - 2
let t1 = (&vk1 * &vk1) + &nm2;
vk1 = &t1 % n;
} else {
// k' = 2k
// V(k'+1) = V(2k+1) = V(k) V(k+1) - P
let t1 = (&vk * &vk1) + n - p;
vk1 = &t1 % n;
// V(k') = V(2k) = V(k)² - 2
let t1 = (&vk * &vk) + &nm2;
vk = &t1 % n;
}
}
// Now k=s, so vk = V(s). Check V(s) ≡ ±2 (mod n).
if vk.to_u64() == Some(2) || vk == nm2 {
// Check U(s) ≡ 0.
// As suggested by Jacobsen, apply Crandall and Pomerance equation 3.13:
//
// U(k) = D⁻¹ (2 V(k+1) - P V(k))
//
// Since we are checking for U(k) == 0 it suffices to check 2 V(k+1) == P V(k) mod n,
// or P V(k) - 2 V(k+1) == 0 mod n.
let mut t1 = &vk * p;
let mut t2 = &vk1 << 1;
if t1 < t2 {
core::mem::swap(&mut t1, &mut t2);
}
t1 -= t2;
if (t1 % n).is_zero() {
return true;
}
}
// Check V(2^t s) ≡ 0 mod n for some 0 ≤ t < r-1.
for _ in 0..r - 1 {
if vk.is_zero() {
return true;
}
// Optimization: V(k) = 2 is a fixed point for V(k') = V(k)² - 2,
// so if V(k) = 2, we can stop: we will never find a future V(k) == 0.
if vk.to_u64() == Some(2) {
return false;
}
// k' = 2k
// V(k') = V(2k) = V(k)² - 2
let t1 = (&vk * &vk) - &*BIG_2;
vk = &t1 % n;
}
false
}
/// Checks if the i-th bit is set
#[inline]
fn is_bit_set(x: &BigUint, i: usize) -> bool {
get_bit(x, i) == 1
}
/// Returns the i-th bit.
#[inline]
fn get_bit(x: &BigUint, i: usize) -> u8 {
let j = i / big_digit::BITS;
// if is out of range of the set words, it is always false.
if i >= x.bits() {
return 0;
}
(x.get_limb(j) >> (i % big_digit::BITS) & 1) as u8
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec::Vec;
// use RandBigInt;
use crate::biguint::ToBigUint;
lazy_static! {
static ref PRIMES: Vec<&'static str> = vec![
"2",
"3",
"5",
"7",
"11",
"13756265695458089029",
"13496181268022124907",
"10953742525620032441",
"17908251027575790097",
// https://golang.org/issue/638
"18699199384836356663",
"98920366548084643601728869055592650835572950932266967461790948584315647051443",
"94560208308847015747498523884063394671606671904944666360068158221458669711639",
// http://primes.utm.edu/lists/small/small3.html
"449417999055441493994709297093108513015373787049558499205492347871729927573118262811508386655998299074566974373711472560655026288668094291699357843464363003144674940345912431129144354948751003607115263071543163",
"230975859993204150666423538988557839555560243929065415434980904258310530753006723857139742334640122533598517597674807096648905501653461687601339782814316124971547968912893214002992086353183070342498989426570593",
"5521712099665906221540423207019333379125265462121169655563495403888449493493629943498064604536961775110765377745550377067893607246020694972959780839151452457728855382113555867743022746090187341871655890805971735385789993",
"203956878356401977405765866929034577280193993314348263094772646453283062722701277632936616063144088173312372882677123879538709400158306567338328279154499698366071906766440037074217117805690872792848149112022286332144876183376326512083574821647933992961249917319836219304274280243803104015000563790123",
// ECC primes: http://tools.ietf.org/html/draft-ladd-safecurves-02
"3618502788666131106986593281521497120414687020801267626233049500247285301239", // Curve1174: 2^251-9
"57896044618658097711785492504343953926634992332820282019728792003956564819949", // Curve25519: 2^255-19
"9850501549098619803069760025035903451269934817616361666987073351061430442874302652853566563721228910201656997576599", // E-382: 2^382-105
"42307582002575910332922579714097346549017899709713998034217522897561970639123926132812109468141778230245837569601494931472367", // Curve41417: 2^414-17
"6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151", // E-521: 2^521-1
];
static ref COMPOSITES: Vec<&'static str> = vec![
"0",
"1",
"21284175091214687912771199898307297748211672914763848041968395774954376176754",
"6084766654921918907427900243509372380954290099172559290432744450051395395951",
"84594350493221918389213352992032324280367711247940675652888030554255915464401",
"82793403787388584738507275144194252681",
// Arnault, "Rabin-Miller Primality Test: Composite Numbers Which Pass It",
// Mathematics of Computation, 64(209) (January 1995), pp. 335-361.
"1195068768795265792518361315725116351898245581", // strong pseudoprime to prime bases 2 through 29
// strong pseudoprime to all prime bases up to 200
"8038374574536394912570796143419421081388376882875581458374889175222974273765333652186502336163960045457915042023603208766569966760987284043965408232928738791850869166857328267761771029389697739470167082304286871099974399765441448453411558724506334092790222752962294149842306881685404326457534018329786111298960644845216191652872597534901",
// Extra-strong Lucas pseudoprimes. https://oeis.org/A217719
"989",
"3239",
"5777",
"10877",
"27971",
"29681",
"30739",
"31631",
"39059",
"72389",
"73919",
"75077",
"100127",
"113573",
"125249",
"137549",
"137801",
"153931",
"155819",
"161027",
"162133",
"189419",
"218321",
"231703",
"249331",
"370229",
"429479",
"430127",
"459191",
"473891",
"480689",
"600059",
"621781",
"632249",
"635627",
"3673744903",
"3281593591",
"2385076987",
"2738053141",
"2009621503",
"1502682721",
"255866131",
"117987841",
"587861",
"6368689",
"8725753",
"80579735209",
"105919633",
];
// Test Cases from #51
static ref ISSUE_51: Vec<&'static str> = vec![
"1579751",
"1884791",
"3818929",
"4080359",
"4145951",
];
}
#[test]
fn test_primes() {
for prime in PRIMES.iter() {
let p = BigUint::parse_bytes(prime.as_bytes(), 10).unwrap();
for i in [0, 1, 20].iter() {
assert!(
probably_prime(&p, *i as usize),
"{} is a prime ({})",
prime,
i,
);
}
}
}
#[test]
fn test_composites() {
for comp in COMPOSITES.iter() {
let p = BigUint::parse_bytes(comp.as_bytes(), 10).unwrap();
for i in [0, 1, 20].iter() {
assert!(
!probably_prime(&p, *i as usize),
"{} is a composite ({})",
comp,
i,
);
}
}
}
#[test]
fn test_issue_51() {
for num in ISSUE_51.iter() {
let p = BigUint::parse_bytes(num.as_bytes(), 10).unwrap();
assert!(probably_prime(&p, 20), "{} is a prime number", num);
}
}
macro_rules! test_pseudo_primes {
($name:ident, $cond:expr, $want:expr) => {
#[test]
fn $name() {
let mut i = 3;
let mut want = $want;
while i < 100000 {
let n = BigUint::from_u64(i).unwrap();
let pseudo = $cond(&n);
if pseudo && (want.is_empty() || i != want[0]) {
panic!("cond({}) = true, want false", i);
} else if !pseudo && !want.is_empty() && i == want[0] {
panic!("cond({}) = false, want true", i);
}
if !want.is_empty() && i == want[0] {
want = want[1..].to_vec();
}
i += 2;
}
if !want.is_empty() {
panic!("forgot to test: {:?}", want);
}
}
};
}
test_pseudo_primes!(
test_probably_prime_miller_rabin,
|n| probably_prime_miller_rabin(n, 1, true) && !probably_prime_lucas(n),
vec![
2047, 3277, 4033, 4681, 8321, 15841, 29341, 42799, 49141, 52633, 65281, 74665, 80581,
85489, 88357, 90751,
]
);
test_pseudo_primes!(
test_probably_prime_lucas,
|n| probably_prime_lucas(n) && !probably_prime_miller_rabin(n, 1, true),
vec![989, 3239, 5777, 10877, 27971, 29681, 30739, 31631, 39059, 72389, 73919, 75077,]
);
#[test]
fn test_bit_set() {
let v = &vec![0b10101001];
let num = BigUint::from_slice(&v);
assert!(is_bit_set(&num, 0));
assert!(!is_bit_set(&num, 1));
assert!(!is_bit_set(&num, 2));
assert!(is_bit_set(&num, 3));
assert!(!is_bit_set(&num, 4));
assert!(is_bit_set(&num, 5));
assert!(!is_bit_set(&num, 6));
assert!(is_bit_set(&num, 7));
}
#[test]
fn test_next_prime_basics() {
let primes1 = (0..2048u32)
.map(|i| next_prime(&i.to_biguint().unwrap()))
.collect::<Vec<_>>();
let primes2 = (0..2048u32)
.map(|i| {
let i = i.to_biguint().unwrap();
let p = next_prime(&i);
assert!(&p > &i);
p
})
.collect::<Vec<_>>();
for (p1, p2) in primes1.iter().zip(&primes2) {
assert_eq!(p1, p2);
assert!(probably_prime(p1, 25));
}
}
#[test]
fn test_next_prime_bug_44() {
let i = 1032989.to_biguint().unwrap();
let next = next_prime(&i);
assert_eq!(1033001.to_biguint().unwrap(), next);
}
}

24
vendor/num-bigint-dig/src/traits.rs vendored Normal file
View File

@@ -0,0 +1,24 @@
use crate::BigInt;
/// Generic trait to implement modular inverse.
pub trait ModInverse<R: Sized>: Sized {
type Output: Sized;
/// Function to calculate the [modular multiplicative
/// inverse](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse) of an integer *a* modulo *m*.
///
/// TODO: references
/// Returns the modular inverse of `self`.
/// If none exists it returns `None`.
fn mod_inverse(self, m: R) -> Option<Self::Output>;
}
/// Generic trait to implement extended GCD.
/// Calculates the extended eucledian algorithm.
/// See https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm for details.
/// The returned values are
/// - greatest common divisor (1)
/// - Bezout coefficients (2)
pub trait ExtendedGcd<R: Sized>: Sized {
fn extended_gcd(self, other: R) -> (BigInt, BigInt, BigInt);
}

Binary file not shown.

View File

@@ -0,0 +1 @@
{"name":"num-bigint-dig","vers":"0.8.6","deps":[{"name":"arbitrary","req":"^1.1.0","features":[],"optional":true,"default_features":true,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"lazy_static","req":"^1.2.0","features":["spin_no_std"],"optional":false,"default_features":false,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"libm","req":"^0.2.1","features":[],"optional":false,"default_features":true,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"num-integer","req":"^0.1.39","features":["i128"],"optional":false,"default_features":false,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"num-iter","req":"^0.1.37","features":[],"optional":false,"default_features":false,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"num-traits","req":"^0.2.4","features":["i128"],"optional":false,"default_features":false,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"rand","req":"^0.8.3","features":[],"optional":true,"default_features":false,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"serde","req":"^1.0","features":["alloc"],"optional":true,"default_features":false,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"smallvec","req":"^1.10.0","features":[],"optional":false,"default_features":false,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"zeroize","req":"^1.5","features":[],"optional":true,"default_features":false,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"rand","req":"^0.8","features":["small_rng"],"optional":false,"default_features":true,"target":null,"kind":"dev","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"rand_chacha","req":"^0.3","features":[],"optional":false,"default_features":true,"target":null,"kind":"dev","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"rand_isaac","req":"^0.3","features":[],"optional":false,"default_features":true,"target":null,"kind":"dev","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"rand_xorshift","req":"^0.3","features":[],"optional":false,"default_features":true,"target":null,"kind":"dev","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"serde_test","req":"^1.0","features":[],"optional":false,"default_features":true,"target":null,"kind":"dev","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false}],"features":{"default":["std","u64_digit"],"fuzz":["arbitrary","smallvec/arbitrary"],"i128":[],"nightly":[],"prime":["rand/std_rng"],"std":["num-integer/std","num-traits/std","smallvec/write","rand/std","serde/std"],"u64_digit":[]},"features2":null,"cksum":"f90924d7f1e5b76e6f3257029e12924f76c6144a6095da92487e01d46c44017e","yanked":null,"links":null,"rust_version":null,"v":2}

1234
vendor/num-bigint-dig/tests/bigint.rs vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,181 @@
extern crate num_bigint_dig as num_bigint;
extern crate num_traits;
use crate::num_bigint::{BigInt, Sign, ToBigInt};
use num_traits::ToPrimitive;
use std::{i32, i64, u32};
enum ValueVec {
N,
P(&'static [u32]),
M(&'static [u32]),
}
use crate::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);
}
}
}

View File

@@ -0,0 +1,145 @@
extern crate num_bigint_dig as num_bigint;
extern crate num_traits;
use crate::num_bigint::BigInt;
use crate::num_bigint::Sign::Plus;
use num_traits::{Signed, ToPrimitive, Zero};
use std::ops::Neg;
mod consts;
use crate::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);
}
}
}

1714
vendor/num-bigint-dig/tests/biguint.rs vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,103 @@
extern crate num_bigint_dig as num_bigint;
extern crate num_traits;
use crate::num_bigint::BigUint;
use num_traits::{ToPrimitive, Zero};
mod consts;
use crate::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_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);
}
}
}

View File

@@ -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]),
];

View File

@@ -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);
};
}

160
vendor/num-bigint-dig/tests/modpow.rs vendored Normal file

File diff suppressed because one or more lines are too long

467
vendor/num-bigint-dig/tests/rand.rs vendored Normal file
View File

@@ -0,0 +1,467 @@
#![cfg(feature = "rand")]
extern crate num_bigint_dig as num_bigint;
extern crate num_traits;
extern crate rand;
extern crate rand_chacha;
extern crate rand_isaac;
extern crate rand_xorshift;
mod biguint {
use crate::num_bigint::{BigUint, RandBigInt, RandomBits};
use num_traits::Zero;
use rand::distributions::Uniform;
use rand::{Rng, SeedableRng};
#[cfg(feature = "std")]
fn thread_rng() -> impl Rng {
rand::thread_rng()
}
#[cfg(not(feature = "std"))]
fn thread_rng() -> impl Rng {
// Chosen by fair dice roll
rand::rngs::StdRng::seed_from_u64(4)
}
#[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, "expected {}, got {}", n, r);
}
}
#[cfg(not(feature = "u64_digit"))]
const EXPECTED_CHACHA: &[&str] = &[
"0",
"0",
"52",
"84",
"23780",
"86502865016",
"187057847319509867386",
"34045731223080904464438757488196244981910",
"23813754422987836414755953516143692594193066497413249270287126597896871975915808",
"57401636903146945411652549098818446911814352529449356393690984105383482703074355\
67088360974672291353736011718191813678720755501317478656550386324355699624671",
];
#[cfg(feature = "u64_digit")]
const EXPECTED_CHACHA: &[&str] = &[
"0",
"0",
"8",
"1861",
"172076",
"5194801951",
"259202797457072892019",
"2806086822955830608275100562233284760859",
"28771276448190704455825316568337256462972770861366848469339788407170414346460023",
"501572804396703231264118826164515310701005506447150057229826006447721882571235378\
4765127362270091441643338804096337494157874113908470083557122824480944132407",
];
#[test]
fn test_chacha_value_stability() {
use rand_chacha::ChaChaRng;
seeded_value_stability::<ChaChaRng>(EXPECTED_CHACHA);
}
#[cfg(not(feature = "u64_digit"))]
const EXPECTED_ISAAC: &[&str] = &[
"1",
"4",
"3",
"649",
"89116",
"7730042024",
"20773149082453254949",
"35999009049239918667571895439206839620281",
"10191757312714088681302309313551624007714035309632506837271600807524767413673006",
"37805949268912387809989378008822038725134260145886913321084097194957861133272558\
43458183365174899239251448892645546322463253898288141861183340823194379722556",
];
#[cfg(feature = "u64_digit")]
const EXPECTED_ISAAC: &[&str] = &[
"1",
"2",
"51",
"1198",
"29707",
"35688018574",
"365090200586541225112",
"14051533166427520604648370582738617763816",
"26319846996091585801307964353534339679417889504909644767909019559631059772127122",
"14567336733062747693583250833667292276083519237160662196899060257293814346680656\
30951609693408423310563908301065751714778956255122249041917698392245727713420",
];
#[test]
fn test_isaac_value_stability() {
use rand_isaac::IsaacRng;
seeded_value_stability::<IsaacRng>(EXPECTED_ISAAC);
}
#[cfg(not(feature = "u64_digit"))]
const EXPECTED_XOR: &[&str] = &[
"1",
"0",
"37",
"395",
"181116",
"122718231117",
"1068467172329355695001",
"28246925743544411614293300167064395633287",
"12750053187017853048648861493745244146555950255549630854523304068318587267293038",
"53041498719137109355568081064978196049094604705283682101683207799515709404788873\
53417136457745727045473194367732849819278740266658219147356315674940229288531",
];
#[cfg(feature = "u64_digit")]
const EXPECTED_XOR: &[&str] = &[
"0",
"1",
"36",
"970",
"940965",
"61158366130",
"590484965100191554896",
"34050066418951688801044382442803594076612",
"29147581645599998811521651062569705291155276949983132826461704326818089074318948",
"4990842894093964353439376569956547459232523176881032246435842690389845516810345611554402412893818283310117202233021355634125020654279500443420515862554775828",
];
#[test]
fn test_xorshift_value_stability() {
use rand_xorshift::XorShiftRng;
seeded_value_stability::<XorShiftRng>(EXPECTED_XOR);
}
}
mod bigint {
use crate::num_bigint::{BigInt, RandBigInt, RandomBits};
use num_traits::Zero;
use rand::distributions::Uniform;
use rand::{Rng, SeedableRng};
#[cfg(feature = "std")]
fn thread_rng() -> impl Rng {
rand::thread_rng()
}
#[cfg(not(feature = "std"))]
fn thread_rng() -> impl Rng {
// Chosen by fair dice roll
rand::rngs::StdRng::seed_from_u64(4)
}
#[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, "expected {}, got {}", n, r);
}
}
#[cfg(not(feature = "u64_digit"))]
const EXPECTED_CHACHA: &[&str] = &[
"0",
"-6",
"-1",
"1321",
"-147247",
"8486373526",
"-272736656290199720696",
"2731152629387534140535423510744221288522",
"-28820024790651190394679732038637785320661450462089347915910979466834461433196572",
"501454570554170484799723603981439288209930393334472085317977614690773821680884844\
8530978478667288338327570972869032358120588620346111979053742269317702532328",
];
#[cfg(feature = "u64_digit")]
const EXPECTED_CHACHA: &[&str] = &[
"0",
"-7",
"-62",
"105",
"13025",
"-33857814162",
"768483926407291599143",
"-42356168828789885585553598574661841382586",
"28813250216034838684899917677182169473483558650956121225920149068989083656174824",
"27056553770481404639717657695702187062015359344716548489861498121037858109133467\
99640556108506718020020878739044048067894089601665199172215093468287730555599",
];
#[test]
fn test_chacha_value_stability() {
use rand_chacha::ChaChaRng;
seeded_value_stability::<ChaChaRng>(EXPECTED_CHACHA);
}
#[cfg(not(feature = "u64_digit"))]
const EXPECTED_ISAAC: &[&str] = &[
"1",
"0",
"5",
"113",
"-132240",
"-36348760761",
"-365690596708430705434",
"-14090753008246284277803606722552430292432",
"-26313941628626248579319341019368550803676255307056857978955881718727601479436059",
"-14563174552421101848999036239003801073335703811160945137332228646111920972691151\
88341090358094331641182310792892459091016794928947242043358702692294695845817",
];
#[cfg(feature = "u64_digit")]
const EXPECTED_ISAAC: &[&str] = &[
"-1",
"-4",
"-29",
"1621",
"23872",
"-40371956434",
"-350815272425024298187",
"-38554888817044546636456097200348998322457",
"7474426176220721712055446211154990065592106428397966654956172383998793852911545",
"6168955541726830487961394166772329653532583907235825721475483003506842180688827\
391385624898257369023912466314791483731902392667906094226608113824795883754631",
];
#[test]
fn test_isaac_value_stability() {
use rand_isaac::IsaacRng;
seeded_value_stability::<IsaacRng>(EXPECTED_ISAAC);
}
#[cfg(not(feature = "u64_digit"))]
const EXPECTED_XOR: &[&str] = &[
"-1",
"-4",
"11",
"-1802",
"966495",
"-62592045703",
"-602281783447192077116",
"-34335811410223060575607987996861632509125",
"29156580925282215857325937227200350542000244609280383263289720243118706105351199",
"49920038676141573457451407325930326489996232208489690499754573826911037849083623\
24546142615325187412887314466195222441945661833644117700809693098722026764846",
];
#[cfg(feature = "u64_digit")]
const EXPECTED_XOR: &[&str] = &[
"-1",
"-3",
"4",
"-228",
"377276",
"32032893086",
"885120221048601050706",
"33404877924318663206979407569537287223622",
"-15253093455306269007559295940333933266263385975865952571271093251749752787075084",
"4502641950394305250103130679458759592222756470562408577296380915684757985604969904\
381774527626485128207406911227296090734227576935034372181808818486328078978",
];
#[test]
fn test_xorshift_value_stability() {
use rand_xorshift::XorShiftRng;
seeded_value_stability::<XorShiftRng>(EXPECTED_XOR);
}
}
#[cfg(feature = "prime")]
mod prime {
use num_bigint::prime::probably_prime;
use num_bigint::RandPrime;
use rand::prelude::*;
#[test]
fn test_prime_small() {
let mut rng = StdRng::from_seed([0u8; 32]);
for n in 2..10 {
let p = rng.gen_prime(n);
assert_eq!(p.bits(), n);
assert!(probably_prime(&p, 32));
}
}
#[test]
fn test_gen_prime_1024() {
let mut rng = StdRng::from_seed([0u8; 32]);
let p = rng.gen_prime(1024);
assert_eq!(p.bits(), 1024);
}
}

197
vendor/num-bigint-dig/tests/roots.rs vendored Normal file
View File

@@ -0,0 +1,197 @@
extern crate num_bigint_dig as num_bigint;
extern crate num_integer;
extern crate num_traits;
#[cfg(feature = "rand")]
extern crate rand;
mod biguint {
use crate::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() {
#[cfg(feature = "std")]
fn thread_rng() -> impl rand::Rng {
rand::thread_rng()
}
#[cfg(not(feature = "std"))]
fn thread_rng() -> impl rand::Rng {
use rand::SeedableRng;
// Chosen by fair dice roll
rand::rngs::StdRng::seed_from_u64(4)
}
use crate::num_bigint::RandBigInt;
use rand::distributions::Uniform;
use rand::Rng;
let rng = &mut 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 crate::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);
}
}

103
vendor/num-bigint-dig/tests/serde.rs vendored Normal file
View File

@@ -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_dig as num_bigint;
extern crate num_traits;
extern crate serde_test;
use crate::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);
}

49
vendor/num-bigint-dig/tests/torture.rs vendored Normal file
View File

@@ -0,0 +1,49 @@
#![cfg(feature = "rand")]
extern crate num_bigint_dig as num_bigint;
extern crate num_traits;
extern crate rand;
use crate::num_bigint::RandBigInt;
use num_traits::Zero;
use rand::prelude::*;
fn test_mul_divide_torture_count(count: usize) {
let bits_max = 1 << 12;
#[cfg(target_pointer_width = "32")]
let seed = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
#[cfg(target_pointer_width = "64")]
let seed = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32,
];
let mut rng = rand::rngs::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);
}