num-bigint-0.4.3/.cargo_vcs_info.json 0000644 00000000112 00000000001 0013103 0 ustar {
"git": {
"sha1": "e77ffacafef7e8fa2c2b990489b7aa30dceaed64"
}
}
num-bigint-0.4.3/.gitignore 0000644 0000000 0000000 00000000036 00726746425 0013720 0 ustar 0000000 0000000 Cargo.lock
target
*.bk
*.orig
num-bigint-0.4.3/Cargo.toml 0000644 00000003520 00000000001 0011107 0 ustar # 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 = "2018"
name = "num-bigint"
version = "0.4.3"
authors = ["The Rust Project Developers"]
build = "build.rs"
exclude = ["/bors.toml", "/ci/*", "/.github/*"]
description = "Big integer implementation for Rust"
homepage = "https://github.com/rust-num/num-bigint"
documentation = "https://docs.rs/num-bigint"
readme = "README.md"
keywords = ["mathematics", "numerics", "bignum"]
categories = ["algorithms", "data-structures", "science"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/rust-num/num-bigint"
[package.metadata.docs.rs]
features = ["std", "serde", "rand", "quickcheck", "arbitrary"]
[[bench]]
name = "bigint"
[[bench]]
name = "factorial"
[[bench]]
name = "gcd"
[[bench]]
name = "roots"
[[bench]]
name = "shootout-pidigits"
harness = false
[dependencies.arbitrary]
version = "1"
optional = true
default-features = false
[dependencies.num-integer]
version = "0.1.42"
features = ["i128"]
default-features = false
[dependencies.num-traits]
version = "0.2.11"
features = ["i128"]
default-features = false
[dependencies.quickcheck]
version = "1"
optional = true
default-features = false
[dependencies.rand]
version = "0.8"
optional = true
default-features = false
[dependencies.serde]
version = "1.0"
optional = true
default-features = false
[build-dependencies.autocfg]
version = "1"
[features]
default = ["std"]
std = ["num-integer/std", "num-traits/std"]
num-bigint-0.4.3/Cargo.toml.orig 0000644 0000000 0000000 00000002612 00726746425 0014621 0 ustar 0000000 0000000 [package]
authors = ["The Rust Project Developers"]
description = "Big integer implementation for Rust"
documentation = "https://docs.rs/num-bigint"
homepage = "https://github.com/rust-num/num-bigint"
keywords = ["mathematics", "numerics", "bignum"]
categories = [ "algorithms", "data-structures", "science" ]
license = "MIT OR Apache-2.0"
name = "num-bigint"
repository = "https://github.com/rust-num/num-bigint"
version = "0.4.3"
readme = "README.md"
build = "build.rs"
exclude = ["/bors.toml", "/ci/*", "/.github/*"]
edition = "2018"
[features]
default = ["std"]
std = ["num-integer/std", "num-traits/std"]
[package.metadata.docs.rs]
features = ["std", "serde", "rand", "quickcheck", "arbitrary"]
[[bench]]
name = "bigint"
[[bench]]
name = "factorial"
[[bench]]
name = "gcd"
[[bench]]
name = "roots"
[[bench]]
harness = false
name = "shootout-pidigits"
[dependencies]
[dependencies.num-integer]
version = "0.1.42"
default-features = false
features = ["i128"]
[dependencies.num-traits]
version = "0.2.11"
default-features = false
features = ["i128"]
[dependencies.rand]
optional = true
version = "0.8"
default-features = false
[dependencies.serde]
optional = true
version = "1.0"
default-features = false
[dependencies.quickcheck]
optional = true
version = "1"
default-features = false
[dependencies.arbitrary]
optional = true
version = "1"
default-features = false
[build-dependencies]
autocfg = "1"
num-bigint-0.4.3/LICENSE-APACHE 0000644 0000000 0000000 00000025137 00726746425 0013665 0 ustar 0000000 0000000 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.
num-bigint-0.4.3/LICENSE-MIT 0000644 0000000 0000000 00000002057 00726746425 0013371 0 ustar 0000000 0000000 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.
num-bigint-0.4.3/README.md 0000644 0000000 0000000 00000005324 00726746425 0013214 0 ustar 0000000 0000000 # num-bigint
[](https://crates.io/crates/num-bigint)
[](https://docs.rs/num-bigint)
[](https://rust-lang.github.io/rfcs/2495-min-rust-version.html)
[](https://github.com/rust-num/num-bigint/actions)
Big integer types for Rust, `BigInt` and `BigUint`.
## Usage
Add this to your `Cargo.toml`:
```toml
[dependencies]
num-bigint = "0.4"
```
## Features
The `std` crate feature is enabled by default, and is mandatory before Rust
1.36 and the stabilized `alloc` crate. If you depend on `num-bigint` with
`default-features = false`, you must manually enable the `std` feature yourself
if your compiler is not new enough.
### Random Generation
`num-bigint` supports the generation of random big integers when the `rand`
feature is enabled. To enable it include rand as
```toml
rand = "0.8"
num-bigint = { version = "0.4", features = ["rand"] }
```
Note that you must use the version of `rand` that `num-bigint` is compatible
with: `0.8`.
## Releases
Release notes are available in [RELEASES.md](RELEASES.md).
## Compatibility
The `num-bigint` crate is tested for rustc 1.31 and greater.
## Alternatives
While `num-bigint` strives for good performance in pure Rust code, other
crates may offer better performance with different trade-offs. The following
table offers a brief comparison to a few alternatives.
| Crate | License | Min rustc | Implementation |
| :--------------- | :------------- | :-------- | :------------- |
| **`num-bigint`** | MIT/Apache-2.0 | 1.31 | pure rust |
| [`ramp`] | Apache-2.0 | nightly | rust and inline assembly |
| [`rug`] | LGPL-3.0+ | 1.37 | bundles [GMP] via [`gmp-mpfr-sys`] |
| [`rust-gmp`] | MIT | stable? | links to [GMP] |
| [`apint`] | MIT/Apache-2.0 | 1.26 | pure rust (unfinished) |
[GMP]: https://gmplib.org/
[`gmp-mpfr-sys`]: https://crates.io/crates/gmp-mpfr-sys
[`rug`]: https://crates.io/crates/rug
[`rust-gmp`]: https://crates.io/crates/rust-gmp
[`ramp`]: https://crates.io/crates/ramp
[`apint`]: https://crates.io/crates/apint
## License
Licensed under either of
* [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0)
* [MIT license](http://opensource.org/licenses/MIT)
at your option.
### Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions.
num-bigint-0.4.3/RELEASES.md 0000644 0000000 0000000 00000030662 00726746425 0013465 0 ustar 0000000 0000000 # Release 0.4.3 (2021-11-02)
- [GHSA-v935-pqmr-g8v9]: [Fix unexpected panics in multiplication.][228]
**Contributors**: @arvidn, @cuviper, @guidovranken
[228]: https://github.com/rust-num/num-bigint/pull/228
[GHSA-v935-pqmr-g8v9]: https://github.com/rust-num/num-bigint/security/advisories/GHSA-v935-pqmr-g8v9
# Release 0.4.2 (2021-09-03)
- [Use explicit `Integer::div_ceil` to avoid the new unstable method.][219]
**Contributors**: @catenacyber, @cuviper
[219]: https://github.com/rust-num/num-bigint/pull/219
# Release 0.4.1 (2021-08-27)
- [Fixed scalar divide-by-zero panics.][200]
- [Implemented `DoubleEndedIterator` for `U32Digits` and `U64Digits`.][208]
- [Optimized multiplication to avoid unnecessary allocations.][199]
- [Optimized string formatting for very large values.][216]
**Contributors**: @cuviper, @PatrickNorton
[199]: https://github.com/rust-num/num-bigint/pull/199
[200]: https://github.com/rust-num/num-bigint/pull/200
[208]: https://github.com/rust-num/num-bigint/pull/208
[216]: https://github.com/rust-num/num-bigint/pull/216
# Release 0.4.0 (2021-03-05)
### Breaking Changes
- Updated public dependences on [arbitrary, quickcheck][194], and [rand][185]:
- `arbitrary` support has been updated to 1.0, requiring Rust 1.40.
- `quickcheck` support has been updated to 1.0, requiring Rust 1.46.
- `rand` support has been updated to 0.8, requiring Rust 1.36.
- [`Debug` now shows plain numeric values for `BigInt` and `BigUint`][195],
rather than the raw list of internal digits.
**Contributors**: @cuviper, @Gelbpunkt
[185]: https://github.com/rust-num/num-bigint/pull/185
[194]: https://github.com/rust-num/num-bigint/pull/194
[195]: https://github.com/rust-num/num-bigint/pull/195
# Release 0.3.3 (2021-09-03)
- [Use explicit `Integer::div_ceil` to avoid the new unstable method.][219]
**Contributors**: @catenacyber, @cuviper
# Release 0.3.2 (2021-03-04)
- [The new `BigUint` methods `count_ones` and `trailing_ones`][175] return the
number of `1` bits in the entire value or just its least-significant tail,
respectively.
- [The new `BigInt` and `BigUint` methods `bit` and `set_bit`][183] will read
and write individual bits of the value. For negative `BigInt`, bits are
determined as if they were in the two's complement representation.
- [The `from_radix_le` and `from_radix_be` methods][187] now accept empty
buffers to represent zero.
- [`BigInt` and `BigUint` can now iterate digits as `u32` or `u64`][192],
regardless of the actual internal digit size.
**Contributors**: @BartMassey, @cuviper, @janmarthedal, @sebastianv89, @Speedy37
[175]: https://github.com/rust-num/num-bigint/pull/175
[183]: https://github.com/rust-num/num-bigint/pull/183
[187]: https://github.com/rust-num/num-bigint/pull/187
[192]: https://github.com/rust-num/num-bigint/pull/192
# Release 0.3.1 (2020-11-03)
- [Addition and subtraction now uses intrinsics][141] for performance on `x86`
and `x86_64` when built with Rust 1.33 or later.
- [Conversions `to_f32` and `to_f64` now return infinity][163] for very large
numbers, rather than `None`. This does preserve the sign too, so a large
negative `BigInt` will convert to negative infinity.
- [The optional `arbitrary` feature implements `arbitrary::Arbitrary`][166],
distinct from `quickcheck::Arbitrary`.
- [The division algorithm has been optimized][170] to reduce the number of
temporary allocations and improve the internal guesses at each step.
- [`BigInt` and `BigUint` will opportunistically shrink capacity][171] if the
internal vector is much larger than needed.
**Contributors**: @cuviper, @e00E, @ejmahler, @notoria, @tczajka
[141]: https://github.com/rust-num/num-bigint/pull/141
[163]: https://github.com/rust-num/num-bigint/pull/163
[166]: https://github.com/rust-num/num-bigint/pull/166
[170]: https://github.com/rust-num/num-bigint/pull/170
[171]: https://github.com/rust-num/num-bigint/pull/171
# Release 0.3.0 (2020-06-12)
### Enhancements
- [The internal `BigDigit` may now be either `u32` or `u64`][62], although that
implementation detail is not exposed in the API. For now, this is chosen to
match the target pointer size, but may change in the future.
- [No-`std` is now supported with the `alloc` crate on Rust 1.36][101].
- [`Pow` is now implemented for bigint values][137], not just references.
- [`TryFrom` is now implemented on Rust 1.34 and later][123], converting signed
integers to unsigned, and narrowing big integers to primitives.
- [`Shl` and `Shr` are now implemented for a variety of shift types][142].
- A new `trailing_zeros()` returns the number of consecutive zeros from the
least significant bit.
- The new `BigInt::magnitude` and `into_parts` methods give access to its
`BigUint` part as the magnitude.
### Breaking Changes
- `num-bigint` now requires Rust 1.31 or greater.
- The "i128" opt-in feature was removed, now always available.
- [Updated public dependences][110]:
- `rand` support has been updated to 0.7, requiring Rust 1.32.
- `quickcheck` support has been updated to 0.9, requiring Rust 1.34.
- [Removed `impl Neg for BigUint`][145], which only ever panicked.
- [Bit counts are now `u64` instead of `usize`][143].
**Contributors**: @cuviper, @dignifiedquire, @hansihe,
@kpcyrd, @milesand, @tech6hutch
[62]: https://github.com/rust-num/num-bigint/pull/62
[101]: https://github.com/rust-num/num-bigint/pull/101
[110]: https://github.com/rust-num/num-bigint/pull/110
[123]: https://github.com/rust-num/num-bigint/pull/123
[137]: https://github.com/rust-num/num-bigint/pull/137
[142]: https://github.com/rust-num/num-bigint/pull/142
[143]: https://github.com/rust-num/num-bigint/pull/143
[145]: https://github.com/rust-num/num-bigint/pull/145
# Release 0.2.6 (2020-01-27)
- [Fix the promotion of negative `isize` in `BigInt` assign-ops][133].
**Contributors**: @cuviper, @HactarCE
[133]: https://github.com/rust-num/num-bigint/pull/133
# Release 0.2.5 (2020-01-09)
- [Updated the `autocfg` build dependency to 1.0][126].
**Contributors**: @cuviper, @tspiteri
[126]: https://github.com/rust-num/num-bigint/pull/126
# Release 0.2.4 (2020-01-01)
- [The new `BigUint::to_u32_digits` method][104] returns the number as a
little-endian vector of base-232 digits. The same method on
`BigInt` also returns the sign.
- [`BigUint::modpow` now applies a modulus even for exponent 1][113], which
also affects `BigInt::modpow`.
- [`BigInt::modpow` now returns the correct sign for negative bases with even
exponents][114].
[104]: https://github.com/rust-num/num-bigint/pull/104
[113]: https://github.com/rust-num/num-bigint/pull/113
[114]: https://github.com/rust-num/num-bigint/pull/114
**Contributors**: @alex-ozdemir, @cuviper, @dingelish, @Speedy37, @youknowone
# Release 0.2.3 (2019-09-03)
- [`Pow` is now implemented for `BigUint` exponents][77].
- [The optional `quickcheck` feature enables implementations of `Arbitrary`][99].
- See the [full comparison][compare-0.2.3] for performance enhancements and more!
[77]: https://github.com/rust-num/num-bigint/pull/77
[99]: https://github.com/rust-num/num-bigint/pull/99
[compare-0.2.3]: https://github.com/rust-num/num-bigint/compare/num-bigint-0.2.2...num-bigint-0.2.3
**Contributors**: @cuviper, @lcnr, @maxbla, @mikelodder7, @mikong,
@TheLetterTheta, @tspiteri, @XAMPPRocky, @youknowone
# Release 0.2.2 (2018-12-14)
- [The `Roots` implementations now use better initial guesses][71].
- [Fixed `to_signed_bytes_*` for some positive numbers][72], where the
most-significant byte is `0x80` and the rest are `0`.
[71]: https://github.com/rust-num/num-bigint/pull/71
[72]: https://github.com/rust-num/num-bigint/pull/72
**Contributors**: @cuviper, @leodasvacas
# Release 0.2.1 (2018-11-02)
- [`RandBigInt` now uses `Rng::fill_bytes`][53] to improve performance, instead
of repeated `gen::` 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!
num-bigint-0.4.3/benches/bigint.rs 0000644 0000000 0000000 00000022347 00726746425 0015172 0 ustar 0000000 0000000 #![feature(test)]
#![cfg(feature = "rand")]
extern crate test;
use num_bigint::{BigInt, BigUint, RandBigInt};
use num_traits::{FromPrimitive, Num, One, Zero};
use std::mem::replace;
use test::Bencher;
mod rng;
use rng::get_rng;
fn multiply_bench(b: &mut Bencher, xbits: u64, ybits: u64) {
let mut rng = get_rng();
let x = rng.gen_bigint(xbits);
let y = rng.gen_bigint(ybits);
b.iter(|| &x * &y);
}
fn divide_bench(b: &mut Bencher, xbits: u64, ybits: u64) {
let mut rng = get_rng();
let x = rng.gen_bigint(xbits);
let y = rng.gen_bigint(ybits);
b.iter(|| &x / &y);
}
fn remainder_bench(b: &mut Bencher, xbits: u64, ybits: u64) {
let mut rng = get_rng();
let x = rng.gen_bigint(xbits);
let y = rng.gen_bigint(ybits);
b.iter(|| &x % &y);
}
fn factorial(n: usize) -> BigUint {
let mut f: BigUint = One::one();
for i in 1..=n {
let bu: BigUint = FromPrimitive::from_usize(i).unwrap();
f *= bu;
}
f
}
/// Compute Fibonacci numbers
fn fib(n: usize) -> BigUint {
let mut f0: BigUint = Zero::zero();
let mut f1: BigUint = One::one();
for _ in 0..n {
let f2 = f0 + &f1;
f0 = replace(&mut f1, f2);
}
f0
}
/// Compute Fibonacci numbers with two ops per iteration
/// (add and subtract, like issue #200)
fn fib2(n: usize) -> BigUint {
let mut f0: BigUint = Zero::zero();
let mut f1: BigUint = One::one();
for _ in 0..n {
f1 += &f0;
f0 = &f1 - f0;
}
f0
}
#[bench]
fn multiply_0(b: &mut Bencher) {
multiply_bench(b, 1 << 8, 1 << 8);
}
#[bench]
fn multiply_1(b: &mut Bencher) {
multiply_bench(b, 1 << 8, 1 << 16);
}
#[bench]
fn multiply_2(b: &mut Bencher) {
multiply_bench(b, 1 << 16, 1 << 16);
}
#[bench]
fn multiply_3(b: &mut Bencher) {
multiply_bench(b, 1 << 16, 1 << 17);
}
#[bench]
fn divide_0(b: &mut Bencher) {
divide_bench(b, 1 << 8, 1 << 6);
}
#[bench]
fn divide_1(b: &mut Bencher) {
divide_bench(b, 1 << 12, 1 << 8);
}
#[bench]
fn divide_2(b: &mut Bencher) {
divide_bench(b, 1 << 16, 1 << 12);
}
#[bench]
fn divide_big_little(b: &mut Bencher) {
divide_bench(b, 1 << 16, 1 << 4);
}
#[bench]
fn remainder_0(b: &mut Bencher) {
remainder_bench(b, 1 << 8, 1 << 6);
}
#[bench]
fn remainder_1(b: &mut Bencher) {
remainder_bench(b, 1 << 12, 1 << 8);
}
#[bench]
fn remainder_2(b: &mut Bencher) {
remainder_bench(b, 1 << 16, 1 << 12);
}
#[bench]
fn remainder_big_little(b: &mut Bencher) {
remainder_bench(b, 1 << 16, 1 << 4);
}
#[bench]
fn factorial_100(b: &mut Bencher) {
b.iter(|| factorial(100));
}
#[bench]
fn fib_100(b: &mut Bencher) {
b.iter(|| fib(100));
}
#[bench]
fn fib_1000(b: &mut Bencher) {
b.iter(|| fib(1000));
}
#[bench]
fn fib_10000(b: &mut Bencher) {
b.iter(|| fib(10000));
}
#[bench]
fn fib2_100(b: &mut Bencher) {
b.iter(|| fib2(100));
}
#[bench]
fn fib2_1000(b: &mut Bencher) {
b.iter(|| fib2(1000));
}
#[bench]
fn fib2_10000(b: &mut Bencher) {
b.iter(|| fib2(10000));
}
#[bench]
fn fac_to_string(b: &mut Bencher) {
let fac = factorial(100);
b.iter(|| fac.to_string());
}
#[bench]
fn fib_to_string(b: &mut Bencher) {
let fib = fib(100);
b.iter(|| fib.to_string());
}
fn to_str_radix_bench(b: &mut Bencher, radix: u32, bits: u64) {
let mut rng = get_rng();
let x = rng.gen_bigint(bits);
b.iter(|| x.to_str_radix(radix));
}
#[bench]
fn to_str_radix_02(b: &mut Bencher) {
to_str_radix_bench(b, 2, 1009);
}
#[bench]
fn to_str_radix_08(b: &mut Bencher) {
to_str_radix_bench(b, 8, 1009);
}
#[bench]
fn to_str_radix_10(b: &mut Bencher) {
to_str_radix_bench(b, 10, 1009);
}
#[bench]
fn to_str_radix_10_2(b: &mut Bencher) {
to_str_radix_bench(b, 10, 10009);
}
#[bench]
fn to_str_radix_16(b: &mut Bencher) {
to_str_radix_bench(b, 16, 1009);
}
#[bench]
fn to_str_radix_36(b: &mut Bencher) {
to_str_radix_bench(b, 36, 1009);
}
fn from_str_radix_bench(b: &mut Bencher, radix: u32) {
let mut rng = get_rng();
let x = rng.gen_bigint(1009);
let s = x.to_str_radix(radix);
assert_eq!(x, BigInt::from_str_radix(&s, radix).unwrap());
b.iter(|| BigInt::from_str_radix(&s, radix));
}
#[bench]
fn from_str_radix_02(b: &mut Bencher) {
from_str_radix_bench(b, 2);
}
#[bench]
fn from_str_radix_08(b: &mut Bencher) {
from_str_radix_bench(b, 8);
}
#[bench]
fn from_str_radix_10(b: &mut Bencher) {
from_str_radix_bench(b, 10);
}
#[bench]
fn from_str_radix_16(b: &mut Bencher) {
from_str_radix_bench(b, 16);
}
#[bench]
fn from_str_radix_36(b: &mut Bencher) {
from_str_radix_bench(b, 36);
}
fn rand_bench(b: &mut Bencher, bits: u64) {
let mut rng = get_rng();
b.iter(|| rng.gen_bigint(bits));
}
#[bench]
fn rand_64(b: &mut Bencher) {
rand_bench(b, 1 << 6);
}
#[bench]
fn rand_256(b: &mut Bencher) {
rand_bench(b, 1 << 8);
}
#[bench]
fn rand_1009(b: &mut Bencher) {
rand_bench(b, 1009);
}
#[bench]
fn rand_2048(b: &mut Bencher) {
rand_bench(b, 1 << 11);
}
#[bench]
fn rand_4096(b: &mut Bencher) {
rand_bench(b, 1 << 12);
}
#[bench]
fn rand_8192(b: &mut Bencher) {
rand_bench(b, 1 << 13);
}
#[bench]
fn rand_65536(b: &mut Bencher) {
rand_bench(b, 1 << 16);
}
#[bench]
fn rand_131072(b: &mut Bencher) {
rand_bench(b, 1 << 17);
}
#[bench]
fn shl(b: &mut Bencher) {
let n = BigUint::one() << 1000u32;
let mut m = n.clone();
b.iter(|| {
m.clone_from(&n);
for i in 0..50 {
m <<= i;
}
})
}
#[bench]
fn shr(b: &mut Bencher) {
let n = BigUint::one() << 2000u32;
let mut m = n.clone();
b.iter(|| {
m.clone_from(&n);
for i in 0..50 {
m >>= i;
}
})
}
#[bench]
fn hash(b: &mut Bencher) {
use std::collections::HashSet;
let mut rng = get_rng();
let v: Vec = (1000..2000).map(|bits| rng.gen_bigint(bits)).collect();
b.iter(|| {
let h: HashSet<&BigInt> = v.iter().collect();
assert_eq!(h.len(), v.len());
});
}
#[bench]
fn pow_bench(b: &mut Bencher) {
b.iter(|| {
let upper = 100_u32;
let mut i_big = BigUint::from(1u32);
for _i in 2..=upper {
i_big += 1u32;
for j in 2..=upper {
i_big.pow(j);
}
}
});
}
#[bench]
fn pow_bench_bigexp(b: &mut Bencher) {
use num_traits::Pow;
b.iter(|| {
let upper = 100_u32;
let mut i_big = BigUint::from(1u32);
for _i in 2..=upper {
i_big += 1u32;
let mut j_big = BigUint::from(1u32);
for _j in 2..=upper {
j_big += 1u32;
Pow::pow(&i_big, &j_big);
}
}
});
}
#[bench]
fn pow_bench_1e1000(b: &mut Bencher) {
b.iter(|| BigUint::from(10u32).pow(1_000));
}
#[bench]
fn pow_bench_1e10000(b: &mut Bencher) {
b.iter(|| BigUint::from(10u32).pow(10_000));
}
#[bench]
fn pow_bench_1e100000(b: &mut Bencher) {
b.iter(|| BigUint::from(10u32).pow(100_000));
}
/// This modulus is the prime from the 2048-bit MODP DH group:
/// https://tools.ietf.org/html/rfc3526#section-3
const RFC3526_2048BIT_MODP_GROUP: &str = "\
FFFFFFFF_FFFFFFFF_C90FDAA2_2168C234_C4C6628B_80DC1CD1\
29024E08_8A67CC74_020BBEA6_3B139B22_514A0879_8E3404DD\
EF9519B3_CD3A431B_302B0A6D_F25F1437_4FE1356D_6D51C245\
E485B576_625E7EC6_F44C42E9_A637ED6B_0BFF5CB6_F406B7ED\
EE386BFB_5A899FA5_AE9F2411_7C4B1FE6_49286651_ECE45B3D\
C2007CB8_A163BF05_98DA4836_1C55D39A_69163FA8_FD24CF5F\
83655D23_DCA3AD96_1C62F356_208552BB_9ED52907_7096966D\
670C354E_4ABC9804_F1746C08_CA18217C_32905E46_2E36CE3B\
E39E772C_180E8603_9B2783A2_EC07A28F_B5C55DF0_6F4C52C9\
DE2BCBF6_95581718_3995497C_EA956AE5_15D22618_98FA0510\
15728E5A_8AACAA68_FFFFFFFF_FFFFFFFF";
#[bench]
fn modpow(b: &mut Bencher) {
let mut rng = get_rng();
let base = rng.gen_biguint(2048);
let e = rng.gen_biguint(2048);
let m = BigUint::from_str_radix(RFC3526_2048BIT_MODP_GROUP, 16).unwrap();
b.iter(|| base.modpow(&e, &m));
}
#[bench]
fn modpow_even(b: &mut Bencher) {
let mut rng = get_rng();
let base = rng.gen_biguint(2048);
let e = rng.gen_biguint(2048);
// Make the modulus even, so monty (base-2^32) doesn't apply.
let m = BigUint::from_str_radix(RFC3526_2048BIT_MODP_GROUP, 16).unwrap() - 1u32;
b.iter(|| base.modpow(&e, &m));
}
#[bench]
fn to_u32_digits(b: &mut Bencher) {
let mut rng = get_rng();
let n = rng.gen_biguint(2048);
b.iter(|| n.to_u32_digits());
}
#[bench]
fn iter_u32_digits(b: &mut Bencher) {
let mut rng = get_rng();
let n = rng.gen_biguint(2048);
b.iter(|| n.iter_u32_digits().max());
}
#[bench]
fn to_u64_digits(b: &mut Bencher) {
let mut rng = get_rng();
let n = rng.gen_biguint(2048);
b.iter(|| n.to_u64_digits());
}
#[bench]
fn iter_u64_digits(b: &mut Bencher) {
let mut rng = get_rng();
let n = rng.gen_biguint(2048);
b.iter(|| n.iter_u64_digits().max());
}
num-bigint-0.4.3/benches/factorial.rs 0000644 0000000 0000000 00000001737 00726746425 0015662 0 ustar 0000000 0000000 #![feature(test)]
extern crate test;
use num_bigint::BigUint;
use num_traits::One;
use std::ops::{Div, Mul};
use test::Bencher;
#[bench]
fn factorial_mul_biguint(b: &mut Bencher) {
b.iter(|| {
(1u32..1000)
.map(BigUint::from)
.fold(BigUint::one(), Mul::mul)
});
}
#[bench]
fn factorial_mul_u32(b: &mut Bencher) {
b.iter(|| (1u32..1000).fold(BigUint::one(), Mul::mul));
}
// The division test is inspired by this blog comparison:
//
#[bench]
fn factorial_div_biguint(b: &mut Bencher) {
let n: BigUint = (1u32..1000).fold(BigUint::one(), Mul::mul);
b.iter(|| {
(1u32..1000)
.rev()
.map(BigUint::from)
.fold(n.clone(), Div::div)
});
}
#[bench]
fn factorial_div_u32(b: &mut Bencher) {
let n: BigUint = (1u32..1000).fold(BigUint::one(), Mul::mul);
b.iter(|| (1u32..1000).rev().fold(n.clone(), Div::div));
}
num-bigint-0.4.3/benches/gcd.rs 0000644 0000000 0000000 00000002536 00726746425 0014451 0 ustar 0000000 0000000 #![feature(test)]
#![cfg(feature = "rand")]
extern crate test;
use num_bigint::{BigUint, RandBigInt};
use num_integer::Integer;
use num_traits::Zero;
use test::Bencher;
mod rng;
use rng::get_rng;
fn bench(b: &mut Bencher, bits: u64, gcd: fn(&BigUint, &BigUint) -> BigUint) {
let mut rng = get_rng();
let x = rng.gen_biguint(bits);
let y = rng.gen_biguint(bits);
assert_eq!(euclid(&x, &y), x.gcd(&y));
b.iter(|| gcd(&x, &y));
}
fn euclid(x: &BigUint, y: &BigUint) -> BigUint {
// Use Euclid's algorithm
let mut m = x.clone();
let mut n = y.clone();
while !m.is_zero() {
let temp = m;
m = n % &temp;
n = temp;
}
n
}
#[bench]
fn gcd_euclid_0064(b: &mut Bencher) {
bench(b, 64, euclid);
}
#[bench]
fn gcd_euclid_0256(b: &mut Bencher) {
bench(b, 256, euclid);
}
#[bench]
fn gcd_euclid_1024(b: &mut Bencher) {
bench(b, 1024, euclid);
}
#[bench]
fn gcd_euclid_4096(b: &mut Bencher) {
bench(b, 4096, euclid);
}
// Integer for BigUint now uses Stein for gcd
#[bench]
fn gcd_stein_0064(b: &mut Bencher) {
bench(b, 64, BigUint::gcd);
}
#[bench]
fn gcd_stein_0256(b: &mut Bencher) {
bench(b, 256, BigUint::gcd);
}
#[bench]
fn gcd_stein_1024(b: &mut Bencher) {
bench(b, 1024, BigUint::gcd);
}
#[bench]
fn gcd_stein_4096(b: &mut Bencher) {
bench(b, 4096, BigUint::gcd);
}
num-bigint-0.4.3/benches/rng/mod.rs 0000644 0000000 0000000 00000001672 00726746425 0015261 0 ustar 0000000 0000000 use rand::RngCore;
pub(crate) fn get_rng() -> impl RngCore {
XorShiftStar {
a: 0x0123_4567_89AB_CDEF,
}
}
/// Simple `Rng` for benchmarking without additional dependencies
struct XorShiftStar {
a: u64,
}
impl RngCore for XorShiftStar {
fn next_u32(&mut self) -> u32 {
self.next_u64() as u32
}
fn next_u64(&mut self) -> u64 {
// https://en.wikipedia.org/wiki/Xorshift#xorshift*
self.a ^= self.a >> 12;
self.a ^= self.a << 25;
self.a ^= self.a >> 27;
self.a.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
fn fill_bytes(&mut self, dest: &mut [u8]) {
for chunk in dest.chunks_mut(8) {
let bytes = self.next_u64().to_le_bytes();
let slice = &bytes[..chunk.len()];
chunk.copy_from_slice(slice)
}
}
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> {
Ok(self.fill_bytes(dest))
}
}
num-bigint-0.4.3/benches/roots.rs 0000644 0000000 0000000 00000006064 00726746425 0015062 0 ustar 0000000 0000000 #![feature(test)]
#![cfg(feature = "rand")]
extern crate test;
use num_bigint::{BigUint, RandBigInt};
use test::Bencher;
mod rng;
use rng::get_rng;
// The `big64` cases demonstrate the speed of cases where the value
// can be converted to a `u64` primitive for faster calculation.
//
// The `big1k` cases demonstrate those that can convert to `f64` for
// a better initial guess of the actual value.
//
// The `big2k` and `big4k` cases are too big for `f64`, and use a simpler guess.
fn check(x: &BigUint, n: u32) {
let root = x.nth_root(n);
if n == 2 {
assert_eq!(root, x.sqrt())
} else if n == 3 {
assert_eq!(root, x.cbrt())
}
let lo = root.pow(n);
assert!(lo <= *x);
assert_eq!(lo.nth_root(n), root);
assert_eq!((&lo - 1u32).nth_root(n), &root - 1u32);
let hi = (&root + 1u32).pow(n);
assert!(hi > *x);
assert_eq!(hi.nth_root(n), &root + 1u32);
assert_eq!((&hi - 1u32).nth_root(n), root);
}
fn bench_sqrt(b: &mut Bencher, bits: u64) {
let x = get_rng().gen_biguint(bits);
eprintln!("bench_sqrt({})", x);
check(&x, 2);
b.iter(|| x.sqrt());
}
#[bench]
fn big64_sqrt(b: &mut Bencher) {
bench_sqrt(b, 64);
}
#[bench]
fn big1k_sqrt(b: &mut Bencher) {
bench_sqrt(b, 1024);
}
#[bench]
fn big2k_sqrt(b: &mut Bencher) {
bench_sqrt(b, 2048);
}
#[bench]
fn big4k_sqrt(b: &mut Bencher) {
bench_sqrt(b, 4096);
}
fn bench_cbrt(b: &mut Bencher, bits: u64) {
let x = get_rng().gen_biguint(bits);
eprintln!("bench_cbrt({})", x);
check(&x, 3);
b.iter(|| x.cbrt());
}
#[bench]
fn big64_cbrt(b: &mut Bencher) {
bench_cbrt(b, 64);
}
#[bench]
fn big1k_cbrt(b: &mut Bencher) {
bench_cbrt(b, 1024);
}
#[bench]
fn big2k_cbrt(b: &mut Bencher) {
bench_cbrt(b, 2048);
}
#[bench]
fn big4k_cbrt(b: &mut Bencher) {
bench_cbrt(b, 4096);
}
fn bench_nth_root(b: &mut Bencher, bits: u64, n: u32) {
let x = get_rng().gen_biguint(bits);
eprintln!("bench_{}th_root({})", n, x);
check(&x, n);
b.iter(|| x.nth_root(n));
}
#[bench]
fn big64_nth_10(b: &mut Bencher) {
bench_nth_root(b, 64, 10);
}
#[bench]
fn big1k_nth_10(b: &mut Bencher) {
bench_nth_root(b, 1024, 10);
}
#[bench]
fn big1k_nth_100(b: &mut Bencher) {
bench_nth_root(b, 1024, 100);
}
#[bench]
fn big1k_nth_1000(b: &mut Bencher) {
bench_nth_root(b, 1024, 1000);
}
#[bench]
fn big1k_nth_10000(b: &mut Bencher) {
bench_nth_root(b, 1024, 10000);
}
#[bench]
fn big2k_nth_10(b: &mut Bencher) {
bench_nth_root(b, 2048, 10);
}
#[bench]
fn big2k_nth_100(b: &mut Bencher) {
bench_nth_root(b, 2048, 100);
}
#[bench]
fn big2k_nth_1000(b: &mut Bencher) {
bench_nth_root(b, 2048, 1000);
}
#[bench]
fn big2k_nth_10000(b: &mut Bencher) {
bench_nth_root(b, 2048, 10000);
}
#[bench]
fn big4k_nth_10(b: &mut Bencher) {
bench_nth_root(b, 4096, 10);
}
#[bench]
fn big4k_nth_100(b: &mut Bencher) {
bench_nth_root(b, 4096, 100);
}
#[bench]
fn big4k_nth_1000(b: &mut Bencher) {
bench_nth_root(b, 4096, 1000);
}
#[bench]
fn big4k_nth_10000(b: &mut Bencher) {
bench_nth_root(b, 4096, 10000);
}
num-bigint-0.4.3/benches/shootout-pidigits.rs 0000644 0000000 0000000 00000010054 00726746425 0017404 0 ustar 0000000 0000000 // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2013-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
use std::io;
use std::str::FromStr;
use num_bigint::BigInt;
use num_integer::Integer;
use num_traits::{FromPrimitive, One, ToPrimitive, Zero};
struct Context {
numer: BigInt,
accum: BigInt,
denom: BigInt,
}
impl Context {
fn new() -> Context {
Context {
numer: One::one(),
accum: Zero::zero(),
denom: One::one(),
}
}
fn from_i32(i: i32) -> BigInt {
FromPrimitive::from_i32(i).unwrap()
}
fn extract_digit(&self) -> i32 {
if self.numer > self.accum {
return -1;
}
let (q, r) = (&self.numer * Context::from_i32(3) + &self.accum).div_rem(&self.denom);
if r + &self.numer >= self.denom {
return -1;
}
q.to_i32().unwrap()
}
fn next_term(&mut self, k: i32) {
let y2 = Context::from_i32(k * 2 + 1);
self.accum = (&self.accum + (&self.numer << 1)) * &y2;
self.numer = &self.numer * Context::from_i32(k);
self.denom = &self.denom * y2;
}
fn eliminate_digit(&mut self, d: i32) {
let d = Context::from_i32(d);
let ten = Context::from_i32(10);
self.accum = (&self.accum - &self.denom * d) * &ten;
self.numer = &self.numer * ten;
}
}
fn pidigits(n: isize, out: &mut dyn io::Write) -> io::Result<()> {
let mut k = 0;
let mut context = Context::new();
for i in 1..=n {
let mut d;
loop {
k += 1;
context.next_term(k);
d = context.extract_digit();
if d != -1 {
break;
}
}
write!(out, "{}", d)?;
if i % 10 == 0 {
writeln!(out, "\t:{}", i)?;
}
context.eliminate_digit(d);
}
let m = n % 10;
if m != 0 {
for _ in m..10 {
write!(out, " ")?;
}
writeln!(out, "\t:{}", n)?;
}
Ok(())
}
const DEFAULT_DIGITS: isize = 512;
fn main() {
let args = std::env::args().collect::>();
let n = if args.len() < 2 {
DEFAULT_DIGITS
} else if args[1] == "--bench" {
return pidigits(DEFAULT_DIGITS, &mut std::io::sink()).unwrap();
} else {
FromStr::from_str(&args[1]).unwrap()
};
pidigits(n, &mut std::io::stdout()).unwrap();
}
num-bigint-0.4.3/build.rs 0000644 0000000 0000000 00000005262 00726746425 0013403 0 ustar 0000000 0000000 use std::env;
use std::error::Error;
use std::fs::File;
use std::io::Write;
use std::path::Path;
fn main() {
let pointer_width = env::var("CARGO_CFG_TARGET_POINTER_WIDTH");
let u64_digit = pointer_width.as_ref().map(String::as_str) == Ok("64");
if u64_digit {
autocfg::emit("u64_digit");
}
let ac = autocfg::new();
let std = if ac.probe_sysroot_crate("std") {
"std"
} else {
"core"
};
if ac.probe_path(&format!("{}::convert::TryFrom", std)) {
autocfg::emit("has_try_from");
}
if let Ok(target_arch) = env::var("CARGO_CFG_TARGET_ARCH") {
if target_arch == "x86_64" || target_arch == "x86" {
let digit = if u64_digit { "u64" } else { "u32" };
let addcarry = format!("{}::arch::{}::_addcarry_{}", std, target_arch, digit);
if ac.probe_path(&addcarry) {
autocfg::emit("use_addcarry");
}
}
}
autocfg::rerun_path("build.rs");
write_radix_bases().unwrap();
}
/// Write tables of the greatest power of each radix for the given bit size. These are returned
/// from `biguint::get_radix_base` to batch the multiplication/division of radix conversions on
/// full `BigUint` values, operating on primitive integers as much as possible.
///
/// e.g. BASES_16[3] = (59049, 10) // 3¹⁰ fits in u16, but 3¹¹ is too big
/// BASES_32[3] = (3486784401, 20)
/// BASES_64[3] = (12157665459056928801, 40)
///
/// Powers of two are not included, just zeroed, as they're implemented with shifts.
fn write_radix_bases() -> Result<(), Box> {
let out_dir = env::var("OUT_DIR")?;
let dest_path = Path::new(&out_dir).join("radix_bases.rs");
let mut f = File::create(&dest_path)?;
for &bits in &[16, 32, 64] {
let max = if bits < 64 {
(1 << bits) - 1
} else {
std::u64::MAX
};
writeln!(f, "#[deny(overflowing_literals)]")?;
writeln!(
f,
"pub(crate) static BASES_{bits}: [(u{bits}, usize); 257] = [",
bits = bits
)?;
for radix in 0u64..257 {
let (base, power) = if radix == 0 || radix.is_power_of_two() {
(0, 0)
} else {
let mut power = 1;
let mut base = radix;
while let Some(b) = base.checked_mul(radix) {
if b > max {
break;
}
base = b;
power += 1;
}
(base, power)
};
writeln!(f, " ({}, {}), // {}", base, power, radix)?;
}
writeln!(f, "];")?;
}
Ok(())
}
num-bigint-0.4.3/src/bigint/addition.rs 0000644 0000000 0000000 00000015017 00726746425 0016141 0 ustar 0000000 0000000 use super::CheckedUnsignedAbs::{Negative, Positive};
use super::Sign::{Minus, NoSign, Plus};
use super::{BigInt, UnsignedAbs};
use crate::{IsizePromotion, UsizePromotion};
use core::cmp::Ordering::{Equal, Greater, Less};
use core::iter::Sum;
use core::mem;
use core::ops::{Add, AddAssign};
use num_traits::{CheckedAdd, Zero};
// We want to forward to BigUint::add, but it's not clear how that will go until
// we compare both sign and magnitude. So we duplicate this body for every
// val/ref combination, deferring that decision to BigUint's own forwarding.
macro_rules! bigint_add {
($a:expr, $a_owned:expr, $a_data:expr, $b:expr, $b_owned:expr, $b_data:expr) => {
match ($a.sign, $b.sign) {
(_, NoSign) => $a_owned,
(NoSign, _) => $b_owned,
// same sign => keep the sign with the sum of magnitudes
(Plus, Plus) | (Minus, Minus) => BigInt::from_biguint($a.sign, $a_data + $b_data),
// opposite signs => keep the sign of the larger with the difference of magnitudes
(Plus, Minus) | (Minus, Plus) => match $a.data.cmp(&$b.data) {
Less => BigInt::from_biguint($b.sign, $b_data - $a_data),
Greater => BigInt::from_biguint($a.sign, $a_data - $b_data),
Equal => Zero::zero(),
},
}
};
}
impl<'a, 'b> Add<&'b BigInt> for &'a BigInt {
type Output = BigInt;
#[inline]
fn add(self, other: &BigInt) -> BigInt {
bigint_add!(
self,
self.clone(),
&self.data,
other,
other.clone(),
&other.data
)
}
}
impl<'a> Add for &'a BigInt {
type Output = BigInt;
#[inline]
fn add(self, other: BigInt) -> BigInt {
bigint_add!(self, self.clone(), &self.data, other, other, other.data)
}
}
impl<'a> Add<&'a BigInt> for BigInt {
type Output = BigInt;
#[inline]
fn add(self, other: &BigInt) -> BigInt {
bigint_add!(self, self, self.data, other, other.clone(), &other.data)
}
}
impl Add for BigInt {
type Output = BigInt;
#[inline]
fn add(self, other: BigInt) -> BigInt {
bigint_add!(self, self, self.data, other, other, other.data)
}
}
impl<'a> AddAssign<&'a BigInt> for BigInt {
#[inline]
fn add_assign(&mut self, other: &BigInt) {
let n = mem::replace(self, BigInt::zero());
*self = n + other;
}
}
forward_val_assign!(impl AddAssign for BigInt, add_assign);
promote_all_scalars!(impl Add for BigInt, add);
promote_all_scalars_assign!(impl AddAssign for BigInt, add_assign);
forward_all_scalar_binop_to_val_val_commutative!(impl Add for BigInt, add);
forward_all_scalar_binop_to_val_val_commutative!(impl Add for BigInt, add);
forward_all_scalar_binop_to_val_val_commutative!(impl Add for BigInt, add);
impl Add for BigInt {
type Output = BigInt;
#[inline]
fn add(self, other: u32) -> BigInt {
match self.sign {
NoSign => From::from(other),
Plus => BigInt::from(self.data + other),
Minus => match self.data.cmp(&From::from(other)) {
Equal => Zero::zero(),
Less => BigInt::from(other - self.data),
Greater => -BigInt::from(self.data - other),
},
}
}
}
impl AddAssign for BigInt {
#[inline]
fn add_assign(&mut self, other: u32) {
let n = mem::replace(self, BigInt::zero());
*self = n + other;
}
}
impl Add for BigInt {
type Output = BigInt;
#[inline]
fn add(self, other: u64) -> BigInt {
match self.sign {
NoSign => From::from(other),
Plus => BigInt::from(self.data + other),
Minus => match self.data.cmp(&From::from(other)) {
Equal => Zero::zero(),
Less => BigInt::from(other - self.data),
Greater => -BigInt::from(self.data - other),
},
}
}
}
impl AddAssign for BigInt {
#[inline]
fn add_assign(&mut self, other: u64) {
let n = mem::replace(self, BigInt::zero());
*self = n + other;
}
}
impl Add for BigInt {
type Output = BigInt;
#[inline]
fn add(self, other: u128) -> BigInt {
match self.sign {
NoSign => BigInt::from(other),
Plus => BigInt::from(self.data + other),
Minus => match self.data.cmp(&From::from(other)) {
Equal => BigInt::zero(),
Less => BigInt::from(other - self.data),
Greater => -BigInt::from(self.data - other),
},
}
}
}
impl AddAssign for BigInt {
#[inline]
fn add_assign(&mut self, other: u128) {
let n = mem::replace(self, BigInt::zero());
*self = n + other;
}
}
forward_all_scalar_binop_to_val_val_commutative!(impl Add for BigInt, add);
forward_all_scalar_binop_to_val_val_commutative!(impl Add for BigInt, add);
forward_all_scalar_binop_to_val_val_commutative!(impl Add for BigInt, add);
impl Add for BigInt {
type Output = BigInt;
#[inline]
fn add(self, other: i32) -> BigInt {
match other.checked_uabs() {
Positive(u) => self + u,
Negative(u) => self - u,
}
}
}
impl AddAssign for BigInt {
#[inline]
fn add_assign(&mut self, other: i32) {
match other.checked_uabs() {
Positive(u) => *self += u,
Negative(u) => *self -= u,
}
}
}
impl Add for BigInt {
type Output = BigInt;
#[inline]
fn add(self, other: i64) -> BigInt {
match other.checked_uabs() {
Positive(u) => self + u,
Negative(u) => self - u,
}
}
}
impl AddAssign for BigInt {
#[inline]
fn add_assign(&mut self, other: i64) {
match other.checked_uabs() {
Positive(u) => *self += u,
Negative(u) => *self -= u,
}
}
}
impl Add for BigInt {
type Output = BigInt;
#[inline]
fn add(self, other: i128) -> BigInt {
match other.checked_uabs() {
Positive(u) => self + u,
Negative(u) => self - u,
}
}
}
impl AddAssign for BigInt {
#[inline]
fn add_assign(&mut self, other: i128) {
match other.checked_uabs() {
Positive(u) => *self += u,
Negative(u) => *self -= u,
}
}
}
impl CheckedAdd for BigInt {
#[inline]
fn checked_add(&self, v: &BigInt) -> Option {
Some(self.add(v))
}
}
impl_sum_iter_type!(BigInt);
num-bigint-0.4.3/src/bigint/arbitrary.rs 0000644 0000000 0000000 00000002575 00726746425 0016352 0 ustar 0000000 0000000 use super::{BigInt, Sign};
#[cfg(feature = "quickcheck")]
use crate::std_alloc::Box;
use crate::BigUint;
#[cfg(feature = "quickcheck")]
impl quickcheck::Arbitrary for BigInt {
fn arbitrary(g: &mut quickcheck::Gen) -> Self {
let positive = bool::arbitrary(g);
let sign = if positive { Sign::Plus } else { Sign::Minus };
Self::from_biguint(sign, BigUint::arbitrary(g))
}
fn shrink(&self) -> Box> {
let sign = self.sign();
let unsigned_shrink = self.data.shrink();
Box::new(unsigned_shrink.map(move |x| BigInt::from_biguint(sign, x)))
}
}
#[cfg(feature = "arbitrary")]
impl arbitrary::Arbitrary<'_> for BigInt {
fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result {
let positive = bool::arbitrary(u)?;
let sign = if positive { Sign::Plus } else { Sign::Minus };
Ok(Self::from_biguint(sign, BigUint::arbitrary(u)?))
}
fn arbitrary_take_rest(mut u: arbitrary::Unstructured<'_>) -> arbitrary::Result {
let positive = bool::arbitrary(&mut u)?;
let sign = if positive { Sign::Plus } else { Sign::Minus };
Ok(Self::from_biguint(sign, BigUint::arbitrary_take_rest(u)?))
}
fn size_hint(depth: usize) -> (usize, Option) {
arbitrary::size_hint::and(bool::size_hint(depth), BigUint::size_hint(depth))
}
}
num-bigint-0.4.3/src/bigint/bits.rs 0000644 0000000 0000000 00000043525 00726746425 0015314 0 ustar 0000000 0000000 use super::BigInt;
use super::Sign::{Minus, NoSign, Plus};
use crate::big_digit::{self, BigDigit, DoubleBigDigit};
use crate::biguint::IntDigits;
use crate::std_alloc::Vec;
use core::cmp::Ordering::{Equal, Greater, Less};
use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign};
use num_traits::{ToPrimitive, Zero};
// Negation in two's complement.
// acc must be initialized as 1 for least-significant digit.
//
// When negating, a carry (acc == 1) means that all the digits
// considered to this point were zero. This means that if all the
// digits of a negative BigInt have been considered, carry must be
// zero as we cannot have negative zero.
//
// 01 -> ...f ff
// ff -> ...f 01
// 01 00 -> ...f ff 00
// 01 01 -> ...f fe ff
// 01 ff -> ...f fe 01
// ff 00 -> ...f 01 00
// ff 01 -> ...f 00 ff
// ff ff -> ...f 00 01
#[inline]
fn negate_carry(a: BigDigit, acc: &mut DoubleBigDigit) -> BigDigit {
*acc += DoubleBigDigit::from(!a);
let lo = *acc as BigDigit;
*acc >>= big_digit::BITS;
lo
}
// + 1 & -ff = ...0 01 & ...f 01 = ...0 01 = + 1
// +ff & - 1 = ...0 ff & ...f ff = ...0 ff = +ff
// answer is pos, has length of a
fn bitand_pos_neg(a: &mut Vec, b: &[BigDigit]) {
let mut carry_b = 1;
for (ai, &bi) in a.iter_mut().zip(b.iter()) {
let twos_b = negate_carry(bi, &mut carry_b);
*ai &= twos_b;
}
debug_assert!(b.len() > a.len() || carry_b == 0);
}
// - 1 & +ff = ...f ff & ...0 ff = ...0 ff = +ff
// -ff & + 1 = ...f 01 & ...0 01 = ...0 01 = + 1
// answer is pos, has length of b
fn bitand_neg_pos(a: &mut Vec, b: &[BigDigit]) {
let mut carry_a = 1;
for (ai, &bi) in a.iter_mut().zip(b.iter()) {
let twos_a = negate_carry(*ai, &mut carry_a);
*ai = twos_a & bi;
}
debug_assert!(a.len() > b.len() || carry_a == 0);
match Ord::cmp(&a.len(), &b.len()) {
Greater => a.truncate(b.len()),
Equal => {}
Less => {
let extra = &b[a.len()..];
a.extend(extra.iter().cloned());
}
}
}
// - 1 & -ff = ...f ff & ...f 01 = ...f 01 = - ff
// -ff & - 1 = ...f 01 & ...f ff = ...f 01 = - ff
// -ff & -fe = ...f 01 & ...f 02 = ...f 00 = -100
// answer is neg, has length of longest with a possible carry
fn bitand_neg_neg(a: &mut Vec, b: &[BigDigit]) {
let mut carry_a = 1;
let mut carry_b = 1;
let mut carry_and = 1;
for (ai, &bi) in a.iter_mut().zip(b.iter()) {
let twos_a = negate_carry(*ai, &mut carry_a);
let twos_b = negate_carry(bi, &mut carry_b);
*ai = negate_carry(twos_a & twos_b, &mut carry_and);
}
debug_assert!(a.len() > b.len() || carry_a == 0);
debug_assert!(b.len() > a.len() || carry_b == 0);
match Ord::cmp(&a.len(), &b.len()) {
Greater => {
for ai in a[b.len()..].iter_mut() {
let twos_a = negate_carry(*ai, &mut carry_a);
*ai = negate_carry(twos_a, &mut carry_and);
}
debug_assert!(carry_a == 0);
}
Equal => {}
Less => {
let extra = &b[a.len()..];
a.extend(extra.iter().map(|&bi| {
let twos_b = negate_carry(bi, &mut carry_b);
negate_carry(twos_b, &mut carry_and)
}));
debug_assert!(carry_b == 0);
}
}
if carry_and != 0 {
a.push(1);
}
}
forward_val_val_binop!(impl BitAnd for BigInt, bitand);
forward_ref_val_binop!(impl BitAnd for BigInt, bitand);
// do not use forward_ref_ref_binop_commutative! for bitand so that we can
// clone as needed, avoiding over-allocation
impl<'a, 'b> BitAnd<&'b BigInt> for &'a BigInt {
type Output = BigInt;
#[inline]
fn bitand(self, other: &BigInt) -> BigInt {
match (self.sign, other.sign) {
(NoSign, _) | (_, NoSign) => BigInt::zero(),
(Plus, Plus) => BigInt::from(&self.data & &other.data),
(Plus, Minus) => self.clone() & other,
(Minus, Plus) => other.clone() & self,
(Minus, Minus) => {
// forward to val-ref, choosing the larger to clone
if self.len() >= other.len() {
self.clone() & other
} else {
other.clone() & self
}
}
}
}
}
impl<'a> BitAnd<&'a BigInt> for BigInt {
type Output = BigInt;
#[inline]
fn bitand(mut self, other: &BigInt) -> BigInt {
self &= other;
self
}
}
forward_val_assign!(impl BitAndAssign for BigInt, bitand_assign);
impl<'a> BitAndAssign<&'a BigInt> for BigInt {
fn bitand_assign(&mut self, other: &BigInt) {
match (self.sign, other.sign) {
(NoSign, _) => {}
(_, NoSign) => self.set_zero(),
(Plus, Plus) => {
self.data &= &other.data;
if self.data.is_zero() {
self.sign = NoSign;
}
}
(Plus, Minus) => {
bitand_pos_neg(self.digits_mut(), other.digits());
self.normalize();
}
(Minus, Plus) => {
bitand_neg_pos(self.digits_mut(), other.digits());
self.sign = Plus;
self.normalize();
}
(Minus, Minus) => {
bitand_neg_neg(self.digits_mut(), other.digits());
self.normalize();
}
}
}
}
// + 1 | -ff = ...0 01 | ...f 01 = ...f 01 = -ff
// +ff | - 1 = ...0 ff | ...f ff = ...f ff = - 1
// answer is neg, has length of b
fn bitor_pos_neg(a: &mut Vec, b: &[BigDigit]) {
let mut carry_b = 1;
let mut carry_or = 1;
for (ai, &bi) in a.iter_mut().zip(b.iter()) {
let twos_b = negate_carry(bi, &mut carry_b);
*ai = negate_carry(*ai | twos_b, &mut carry_or);
}
debug_assert!(b.len() > a.len() || carry_b == 0);
match Ord::cmp(&a.len(), &b.len()) {
Greater => {
a.truncate(b.len());
}
Equal => {}
Less => {
let extra = &b[a.len()..];
a.extend(extra.iter().map(|&bi| {
let twos_b = negate_carry(bi, &mut carry_b);
negate_carry(twos_b, &mut carry_or)
}));
debug_assert!(carry_b == 0);
}
}
// for carry_or to be non-zero, we would need twos_b == 0
debug_assert!(carry_or == 0);
}
// - 1 | +ff = ...f ff | ...0 ff = ...f ff = - 1
// -ff | + 1 = ...f 01 | ...0 01 = ...f 01 = -ff
// answer is neg, has length of a
fn bitor_neg_pos(a: &mut Vec, b: &[BigDigit]) {
let mut carry_a = 1;
let mut carry_or = 1;
for (ai, &bi) in a.iter_mut().zip(b.iter()) {
let twos_a = negate_carry(*ai, &mut carry_a);
*ai = negate_carry(twos_a | bi, &mut carry_or);
}
debug_assert!(a.len() > b.len() || carry_a == 0);
if a.len() > b.len() {
for ai in a[b.len()..].iter_mut() {
let twos_a = negate_carry(*ai, &mut carry_a);
*ai = negate_carry(twos_a, &mut carry_or);
}
debug_assert!(carry_a == 0);
}
// for carry_or to be non-zero, we would need twos_a == 0
debug_assert!(carry_or == 0);
}
// - 1 | -ff = ...f ff | ...f 01 = ...f ff = -1
// -ff | - 1 = ...f 01 | ...f ff = ...f ff = -1
// answer is neg, has length of shortest
fn bitor_neg_neg(a: &mut Vec, b: &[BigDigit]) {
let mut carry_a = 1;
let mut carry_b = 1;
let mut carry_or = 1;
for (ai, &bi) in a.iter_mut().zip(b.iter()) {
let twos_a = negate_carry(*ai, &mut carry_a);
let twos_b = negate_carry(bi, &mut carry_b);
*ai = negate_carry(twos_a | twos_b, &mut carry_or);
}
debug_assert!(a.len() > b.len() || carry_a == 0);
debug_assert!(b.len() > a.len() || carry_b == 0);
if a.len() > b.len() {
a.truncate(b.len());
}
// for carry_or to be non-zero, we would need twos_a == 0 or twos_b == 0
debug_assert!(carry_or == 0);
}
forward_val_val_binop!(impl BitOr for BigInt, bitor);
forward_ref_val_binop!(impl BitOr for BigInt, bitor);
// do not use forward_ref_ref_binop_commutative! for bitor so that we can
// clone as needed, avoiding over-allocation
impl<'a, 'b> BitOr<&'b BigInt> for &'a BigInt {
type Output = BigInt;
#[inline]
fn bitor(self, other: &BigInt) -> BigInt {
match (self.sign, other.sign) {
(NoSign, _) => other.clone(),
(_, NoSign) => self.clone(),
(Plus, Plus) => BigInt::from(&self.data | &other.data),
(Plus, Minus) => other.clone() | self,
(Minus, Plus) => self.clone() | other,
(Minus, Minus) => {
// forward to val-ref, choosing the smaller to clone
if self.len() <= other.len() {
self.clone() | other
} else {
other.clone() | self
}
}
}
}
}
impl<'a> BitOr<&'a BigInt> for BigInt {
type Output = BigInt;
#[inline]
fn bitor(mut self, other: &BigInt) -> BigInt {
self |= other;
self
}
}
forward_val_assign!(impl BitOrAssign for BigInt, bitor_assign);
impl<'a> BitOrAssign<&'a BigInt> for BigInt {
fn bitor_assign(&mut self, other: &BigInt) {
match (self.sign, other.sign) {
(_, NoSign) => {}
(NoSign, _) => self.clone_from(other),
(Plus, Plus) => self.data |= &other.data,
(Plus, Minus) => {
bitor_pos_neg(self.digits_mut(), other.digits());
self.sign = Minus;
self.normalize();
}
(Minus, Plus) => {
bitor_neg_pos(self.digits_mut(), other.digits());
self.normalize();
}
(Minus, Minus) => {
bitor_neg_neg(self.digits_mut(), other.digits());
self.normalize();
}
}
}
}
// + 1 ^ -ff = ...0 01 ^ ...f 01 = ...f 00 = -100
// +ff ^ - 1 = ...0 ff ^ ...f ff = ...f 00 = -100
// answer is neg, has length of longest with a possible carry
fn bitxor_pos_neg(a: &mut Vec, b: &[BigDigit]) {
let mut carry_b = 1;
let mut carry_xor = 1;
for (ai, &bi) in a.iter_mut().zip(b.iter()) {
let twos_b = negate_carry(bi, &mut carry_b);
*ai = negate_carry(*ai ^ twos_b, &mut carry_xor);
}
debug_assert!(b.len() > a.len() || carry_b == 0);
match Ord::cmp(&a.len(), &b.len()) {
Greater => {
for ai in a[b.len()..].iter_mut() {
let twos_b = !0;
*ai = negate_carry(*ai ^ twos_b, &mut carry_xor);
}
}
Equal => {}
Less => {
let extra = &b[a.len()..];
a.extend(extra.iter().map(|&bi| {
let twos_b = negate_carry(bi, &mut carry_b);
negate_carry(twos_b, &mut carry_xor)
}));
debug_assert!(carry_b == 0);
}
}
if carry_xor != 0 {
a.push(1);
}
}
// - 1 ^ +ff = ...f ff ^ ...0 ff = ...f 00 = -100
// -ff ^ + 1 = ...f 01 ^ ...0 01 = ...f 00 = -100
// answer is neg, has length of longest with a possible carry
fn bitxor_neg_pos(a: &mut Vec, b: &[BigDigit]) {
let mut carry_a = 1;
let mut carry_xor = 1;
for (ai, &bi) in a.iter_mut().zip(b.iter()) {
let twos_a = negate_carry(*ai, &mut carry_a);
*ai = negate_carry(twos_a ^ bi, &mut carry_xor);
}
debug_assert!(a.len() > b.len() || carry_a == 0);
match Ord::cmp(&a.len(), &b.len()) {
Greater => {
for ai in a[b.len()..].iter_mut() {
let twos_a = negate_carry(*ai, &mut carry_a);
*ai = negate_carry(twos_a, &mut carry_xor);
}
debug_assert!(carry_a == 0);
}
Equal => {}
Less => {
let extra = &b[a.len()..];
a.extend(extra.iter().map(|&bi| {
let twos_a = !0;
negate_carry(twos_a ^ bi, &mut carry_xor)
}));
}
}
if carry_xor != 0 {
a.push(1);
}
}
// - 1 ^ -ff = ...f ff ^ ...f 01 = ...0 fe = +fe
// -ff & - 1 = ...f 01 ^ ...f ff = ...0 fe = +fe
// answer is pos, has length of longest
fn bitxor_neg_neg(a: &mut Vec, b: &[BigDigit]) {
let mut carry_a = 1;
let mut carry_b = 1;
for (ai, &bi) in a.iter_mut().zip(b.iter()) {
let twos_a = negate_carry(*ai, &mut carry_a);
let twos_b = negate_carry(bi, &mut carry_b);
*ai = twos_a ^ twos_b;
}
debug_assert!(a.len() > b.len() || carry_a == 0);
debug_assert!(b.len() > a.len() || carry_b == 0);
match Ord::cmp(&a.len(), &b.len()) {
Greater => {
for ai in a[b.len()..].iter_mut() {
let twos_a = negate_carry(*ai, &mut carry_a);
let twos_b = !0;
*ai = twos_a ^ twos_b;
}
debug_assert!(carry_a == 0);
}
Equal => {}
Less => {
let extra = &b[a.len()..];
a.extend(extra.iter().map(|&bi| {
let twos_a = !0;
let twos_b = negate_carry(bi, &mut carry_b);
twos_a ^ twos_b
}));
debug_assert!(carry_b == 0);
}
}
}
forward_all_binop_to_val_ref_commutative!(impl BitXor for BigInt, bitxor);
impl<'a> BitXor<&'a BigInt> for BigInt {
type Output = BigInt;
#[inline]
fn bitxor(mut self, other: &BigInt) -> BigInt {
self ^= other;
self
}
}
forward_val_assign!(impl BitXorAssign for BigInt, bitxor_assign);
impl<'a> BitXorAssign<&'a BigInt> for BigInt {
fn bitxor_assign(&mut self, other: &BigInt) {
match (self.sign, other.sign) {
(_, NoSign) => {}
(NoSign, _) => self.clone_from(other),
(Plus, Plus) => {
self.data ^= &other.data;
if self.data.is_zero() {
self.sign = NoSign;
}
}
(Plus, Minus) => {
bitxor_pos_neg(self.digits_mut(), other.digits());
self.sign = Minus;
self.normalize();
}
(Minus, Plus) => {
bitxor_neg_pos(self.digits_mut(), other.digits());
self.normalize();
}
(Minus, Minus) => {
bitxor_neg_neg(self.digits_mut(), other.digits());
self.sign = Plus;
self.normalize();
}
}
}
}
pub(super) fn set_negative_bit(x: &mut BigInt, bit: u64, value: bool) {
debug_assert_eq!(x.sign, Minus);
let data = &mut x.data;
let bits_per_digit = u64::from(big_digit::BITS);
if bit >= bits_per_digit * data.len() as u64 {
if !value {
data.set_bit(bit, true);
}
} else {
// If the Uint number is
// ... 0 x 1 0 ... 0
// then the two's complement is
// ... 1 !x 1 0 ... 0
// |-- bit at position 'trailing_zeros'
// where !x is obtained from x by flipping each bit
let trailing_zeros = data.trailing_zeros().unwrap();
if bit > trailing_zeros {
data.set_bit(bit, !value);
} else if bit == trailing_zeros && !value {
// Clearing the bit at position `trailing_zeros` is dealt with by doing
// similarly to what `bitand_neg_pos` does, except we start at digit
// `bit_index`. All digits below `bit_index` are guaranteed to be zero,
// so initially we have `carry_in` = `carry_out` = 1. Furthermore, we
// stop traversing the digits when there are no more carries.
let bit_index = (bit / bits_per_digit).to_usize().unwrap();
let bit_mask = (1 as BigDigit) << (bit % bits_per_digit);
let mut digit_iter = data.digits_mut().iter_mut().skip(bit_index);
let mut carry_in = 1;
let mut carry_out = 1;
let digit = digit_iter.next().unwrap();
let twos_in = negate_carry(*digit, &mut carry_in);
let twos_out = twos_in & !bit_mask;
*digit = negate_carry(twos_out, &mut carry_out);
for digit in digit_iter {
if carry_in == 0 && carry_out == 0 {
// Exit the loop since no more digits can change
break;
}
let twos = negate_carry(*digit, &mut carry_in);
*digit = negate_carry(twos, &mut carry_out);
}
if carry_out != 0 {
// All digits have been traversed and there is a carry
debug_assert_eq!(carry_in, 0);
data.digits_mut().push(1);
}
} else if bit < trailing_zeros && value {
// Flip each bit from position 'bit' to 'trailing_zeros', both inclusive
// ... 1 !x 1 0 ... 0 ... 0
// |-- bit at position 'bit'
// |-- bit at position 'trailing_zeros'
// bit_mask: 1 1 ... 1 0 .. 0
// This is done by xor'ing with the bit_mask
let index_lo = (bit / bits_per_digit).to_usize().unwrap();
let index_hi = (trailing_zeros / bits_per_digit).to_usize().unwrap();
let bit_mask_lo = big_digit::MAX << (bit % bits_per_digit);
let bit_mask_hi =
big_digit::MAX >> (bits_per_digit - 1 - (trailing_zeros % bits_per_digit));
let digits = data.digits_mut();
if index_lo == index_hi {
digits[index_lo] ^= bit_mask_lo & bit_mask_hi;
} else {
digits[index_lo] = bit_mask_lo;
for digit in &mut digits[index_lo + 1..index_hi] {
*digit = big_digit::MAX;
}
digits[index_hi] ^= bit_mask_hi;
}
} else {
// We end up here in two cases:
// bit == trailing_zeros && value: Bit is already set
// bit < trailing_zeros && !value: Bit is already cleared
}
}
}
num-bigint-0.4.3/src/bigint/convert.rs 0000644 0000000 0000000 00000027247 00726746425 0016036 0 ustar 0000000 0000000 use super::Sign::{self, Minus, NoSign, Plus};
use super::{BigInt, ToBigInt};
use crate::std_alloc::Vec;
#[cfg(has_try_from)]
use crate::TryFromBigIntError;
use crate::{BigUint, ParseBigIntError, ToBigUint};
use core::cmp::Ordering::{Equal, Greater, Less};
#[cfg(has_try_from)]
use core::convert::TryFrom;
use core::str::{self, FromStr};
use num_traits::{FromPrimitive, Num, ToPrimitive, Zero};
impl FromStr for BigInt {
type Err = ParseBigIntError;
#[inline]
fn from_str(s: &str) -> Result {
BigInt::from_str_radix(s, 10)
}
}
impl Num for BigInt {
type FromStrRadixErr = ParseBigIntError;
/// Creates and initializes a BigInt.
#[inline]
fn from_str_radix(mut s: &str, radix: u32) -> Result {
let sign = if s.starts_with('-') {
let tail = &s[1..];
if !tail.starts_with('+') {
s = tail
}
Minus
} else {
Plus
};
let bu = BigUint::from_str_radix(s, radix)?;
Ok(BigInt::from_biguint(sign, bu))
}
}
impl ToPrimitive for BigInt {
#[inline]
fn to_i64(&self) -> Option {
match self.sign {
Plus => self.data.to_i64(),
NoSign => Some(0),
Minus => {
let n = self.data.to_u64()?;
let m: u64 = 1 << 63;
match n.cmp(&m) {
Less => Some(-(n as i64)),
Equal => Some(core::i64::MIN),
Greater => None,
}
}
}
}
#[inline]
fn to_i128(&self) -> Option {
match self.sign {
Plus => self.data.to_i128(),
NoSign => Some(0),
Minus => {
let n = self.data.to_u128()?;
let m: u128 = 1 << 127;
match n.cmp(&m) {
Less => Some(-(n as i128)),
Equal => Some(core::i128::MIN),
Greater => None,
}
}
}
}
#[inline]
fn to_u64(&self) -> Option {
match self.sign {
Plus => self.data.to_u64(),
NoSign => Some(0),
Minus => None,
}
}
#[inline]
fn to_u128(&self) -> Option {
match self.sign {
Plus => self.data.to_u128(),
NoSign => Some(0),
Minus => None,
}
}
#[inline]
fn to_f32(&self) -> Option {
let n = self.data.to_f32()?;
Some(if self.sign == Minus { -n } else { n })
}
#[inline]
fn to_f64(&self) -> Option {
let n = self.data.to_f64()?;
Some(if self.sign == Minus { -n } else { n })
}
}
macro_rules! impl_try_from_bigint {
($T:ty, $to_ty:path) => {
#[cfg(has_try_from)]
impl TryFrom<&BigInt> for $T {
type Error = TryFromBigIntError<()>;
#[inline]
fn try_from(value: &BigInt) -> Result<$T, TryFromBigIntError<()>> {
$to_ty(value).ok_or(TryFromBigIntError::new(()))
}
}
#[cfg(has_try_from)]
impl TryFrom for $T {
type Error = TryFromBigIntError;
#[inline]
fn try_from(value: BigInt) -> Result<$T, TryFromBigIntError> {
<$T>::try_from(&value).map_err(|_| TryFromBigIntError::new(value))
}
}
};
}
impl_try_from_bigint!(u8, ToPrimitive::to_u8);
impl_try_from_bigint!(u16, ToPrimitive::to_u16);
impl_try_from_bigint!(u32, ToPrimitive::to_u32);
impl_try_from_bigint!(u64, ToPrimitive::to_u64);
impl_try_from_bigint!(usize, ToPrimitive::to_usize);
impl_try_from_bigint!(u128, ToPrimitive::to_u128);
impl_try_from_bigint!(i8, ToPrimitive::to_i8);
impl_try_from_bigint!(i16, ToPrimitive::to_i16);
impl_try_from_bigint!(i32, ToPrimitive::to_i32);
impl_try_from_bigint!(i64, ToPrimitive::to_i64);
impl_try_from_bigint!(isize, ToPrimitive::to_isize);
impl_try_from_bigint!(i128, ToPrimitive::to_i128);
impl FromPrimitive for BigInt {
#[inline]
fn from_i64(n: i64) -> Option {
Some(BigInt::from(n))
}
#[inline]
fn from_i128(n: i128) -> Option {
Some(BigInt::from(n))
}
#[inline]
fn from_u64(n: u64) -> Option {
Some(BigInt::from(n))
}
#[inline]
fn from_u128(n: u128) -> Option {
Some(BigInt::from(n))
}
#[inline]
fn from_f64(n: f64) -> Option {
if n >= 0.0 {
BigUint::from_f64(n).map(BigInt::from)
} else {
let x = BigUint::from_f64(-n)?;
Some(-BigInt::from(x))
}
}
}
impl From for BigInt {
#[inline]
fn from(n: i64) -> Self {
if n >= 0 {
BigInt::from(n as u64)
} else {
let u = core::u64::MAX - (n as u64) + 1;
BigInt {
sign: Minus,
data: BigUint::from(u),
}
}
}
}
impl From for BigInt {
#[inline]
fn from(n: i128) -> Self {
if n >= 0 {
BigInt::from(n as u128)
} else {
let u = core::u128::MAX - (n as u128) + 1;
BigInt {
sign: Minus,
data: BigUint::from(u),
}
}
}
}
macro_rules! impl_bigint_from_int {
($T:ty) => {
impl From<$T> for BigInt {
#[inline]
fn from(n: $T) -> Self {
BigInt::from(n as i64)
}
}
};
}
impl_bigint_from_int!(i8);
impl_bigint_from_int!(i16);
impl_bigint_from_int!(i32);
impl_bigint_from_int!(isize);
impl From for BigInt {
#[inline]
fn from(n: u64) -> Self {
if n > 0 {
BigInt {
sign: Plus,
data: BigUint::from(n),
}
} else {
BigInt::zero()
}
}
}
impl From for BigInt {
#[inline]
fn from(n: u128) -> Self {
if n > 0 {
BigInt {
sign: Plus,
data: BigUint::from(n),
}
} else {
BigInt::zero()
}
}
}
macro_rules! impl_bigint_from_uint {
($T:ty) => {
impl From<$T> for BigInt {
#[inline]
fn from(n: $T) -> Self {
BigInt::from(n as u64)
}
}
};
}
impl_bigint_from_uint!(u8);
impl_bigint_from_uint!(u16);
impl_bigint_from_uint!(u32);
impl_bigint_from_uint!(usize);
impl From for BigInt {
#[inline]
fn from(n: BigUint) -> Self {
if n.is_zero() {
BigInt::zero()
} else {
BigInt {
sign: Plus,
data: n,
}
}
}
}
impl ToBigInt for BigInt {
#[inline]
fn to_bigint(&self) -> Option {
Some(self.clone())
}
}
impl ToBigInt for BigUint {
#[inline]
fn to_bigint(&self) -> Option {
if self.is_zero() {
Some(Zero::zero())
} else {
Some(BigInt {
sign: Plus,
data: self.clone(),
})
}
}
}
impl ToBigUint for BigInt {
#[inline]
fn to_biguint(&self) -> Option {
match self.sign() {
Plus => Some(self.data.clone()),
NoSign => Some(Zero::zero()),
Minus => None,
}
}
}
#[cfg(has_try_from)]
impl TryFrom<&BigInt> for BigUint {
type Error = TryFromBigIntError<()>;
#[inline]
fn try_from(value: &BigInt) -> Result> {
value
.to_biguint()
.ok_or_else(|| TryFromBigIntError::new(()))
}
}
#[cfg(has_try_from)]
impl TryFrom for BigUint {
type Error = TryFromBigIntError;
#[inline]
fn try_from(value: BigInt) -> Result> {
if value.sign() == Sign::Minus {
Err(TryFromBigIntError::new(value))
} else {
Ok(value.data)
}
}
}
macro_rules! impl_to_bigint {
($T:ty, $from_ty:path) => {
impl ToBigInt for $T {
#[inline]
fn to_bigint(&self) -> Option {
$from_ty(*self)
}
}
};
}
impl_to_bigint!(isize, FromPrimitive::from_isize);
impl_to_bigint!(i8, FromPrimitive::from_i8);
impl_to_bigint!(i16, FromPrimitive::from_i16);
impl_to_bigint!(i32, FromPrimitive::from_i32);
impl_to_bigint!(i64, FromPrimitive::from_i64);
impl_to_bigint!(i128, FromPrimitive::from_i128);
impl_to_bigint!(usize, FromPrimitive::from_usize);
impl_to_bigint!(u8, FromPrimitive::from_u8);
impl_to_bigint!(u16, FromPrimitive::from_u16);
impl_to_bigint!(u32, FromPrimitive::from_u32);
impl_to_bigint!(u64, FromPrimitive::from_u64);
impl_to_bigint!(u128, FromPrimitive::from_u128);
impl_to_bigint!(f32, FromPrimitive::from_f32);
impl_to_bigint!(f64, FromPrimitive::from_f64);
#[inline]
pub(super) fn from_signed_bytes_be(digits: &[u8]) -> BigInt {
let sign = match digits.first() {
Some(v) if *v > 0x7f => Sign::Minus,
Some(_) => Sign::Plus,
None => return BigInt::zero(),
};
if sign == Sign::Minus {
// two's-complement the content to retrieve the magnitude
let mut digits = Vec::from(digits);
twos_complement_be(&mut digits);
BigInt::from_biguint(sign, BigUint::from_bytes_be(&*digits))
} else {
BigInt::from_biguint(sign, BigUint::from_bytes_be(digits))
}
}
#[inline]
pub(super) fn from_signed_bytes_le(digits: &[u8]) -> BigInt {
let sign = match digits.last() {
Some(v) if *v > 0x7f => Sign::Minus,
Some(_) => Sign::Plus,
None => return BigInt::zero(),
};
if sign == Sign::Minus {
// two's-complement the content to retrieve the magnitude
let mut digits = Vec::from(digits);
twos_complement_le(&mut digits);
BigInt::from_biguint(sign, BigUint::from_bytes_le(&*digits))
} else {
BigInt::from_biguint(sign, BigUint::from_bytes_le(digits))
}
}
#[inline]
pub(super) fn to_signed_bytes_be(x: &BigInt) -> Vec {
let mut bytes = x.data.to_bytes_be();
let first_byte = bytes.first().cloned().unwrap_or(0);
if first_byte > 0x7f
&& !(first_byte == 0x80 && bytes.iter().skip(1).all(Zero::is_zero) && x.sign == Sign::Minus)
{
// msb used by magnitude, extend by 1 byte
bytes.insert(0, 0);
}
if x.sign == Sign::Minus {
twos_complement_be(&mut bytes);
}
bytes
}
#[inline]
pub(super) fn to_signed_bytes_le(x: &BigInt) -> Vec {
let mut bytes = x.data.to_bytes_le();
let last_byte = bytes.last().cloned().unwrap_or(0);
if last_byte > 0x7f
&& !(last_byte == 0x80
&& bytes.iter().rev().skip(1).all(Zero::is_zero)
&& x.sign == Sign::Minus)
{
// msb used by magnitude, extend by 1 byte
bytes.push(0);
}
if x.sign == Sign::Minus {
twos_complement_le(&mut bytes);
}
bytes
}
/// Perform in-place two's complement of the given binary representation,
/// in little-endian byte order.
#[inline]
fn twos_complement_le(digits: &mut [u8]) {
twos_complement(digits)
}
/// Perform in-place two's complement of the given binary representation
/// in big-endian byte order.
#[inline]
fn twos_complement_be(digits: &mut [u8]) {
twos_complement(digits.iter_mut().rev())
}
/// Perform in-place two's complement of the given digit iterator
/// starting from the least significant byte.
#[inline]
fn twos_complement<'a, I>(digits: I)
where
I: IntoIterator- ,
{
let mut carry = true;
for d in digits {
*d = !*d;
if carry {
*d = d.wrapping_add(1);
carry = d.is_zero();
}
}
}
num-bigint-0.4.3/src/bigint/division.rs 0000644 0000000 0000000 00000023217 00726746425 0016173 0 ustar 0000000 0000000 use super::CheckedUnsignedAbs::{Negative, Positive};
use super::Sign::NoSign;
use super::{BigInt, UnsignedAbs};
use crate::{IsizePromotion, UsizePromotion};
use core::ops::{Div, DivAssign, Rem, RemAssign};
use num_integer::Integer;
use num_traits::{CheckedDiv, ToPrimitive, Zero};
forward_all_binop_to_ref_ref!(impl Div for BigInt, div);
impl<'a, 'b> Div<&'b BigInt> for &'a BigInt {
type Output = BigInt;
#[inline]
fn div(self, other: &BigInt) -> BigInt {
let (q, _) = self.div_rem(other);
q
}
}
impl<'a> DivAssign<&'a BigInt> for BigInt {
#[inline]
fn div_assign(&mut self, other: &BigInt) {
*self = &*self / other;
}
}
forward_val_assign!(impl DivAssign for BigInt, div_assign);
promote_all_scalars!(impl Div for BigInt, div);
promote_all_scalars_assign!(impl DivAssign for BigInt, div_assign);
forward_all_scalar_binop_to_val_val!(impl Div for BigInt, div);
forward_all_scalar_binop_to_val_val!(impl Div for BigInt, div);
forward_all_scalar_binop_to_val_val!(impl Div for BigInt, div);
impl Div for BigInt {
type Output = BigInt;
#[inline]
fn div(self, other: u32) -> BigInt {
BigInt::from_biguint(self.sign, self.data / other)
}
}
impl DivAssign for BigInt {
#[inline]
fn div_assign(&mut self, other: u32) {
self.data /= other;
if self.data.is_zero() {
self.sign = NoSign;
}
}
}
impl Div for u32 {
type Output = BigInt;
#[inline]
fn div(self, other: BigInt) -> BigInt {
BigInt::from_biguint(other.sign, self / other.data)
}
}
impl Div for BigInt {
type Output = BigInt;
#[inline]
fn div(self, other: u64) -> BigInt {
BigInt::from_biguint(self.sign, self.data / other)
}
}
impl DivAssign for BigInt {
#[inline]
fn div_assign(&mut self, other: u64) {
self.data /= other;
if self.data.is_zero() {
self.sign = NoSign;
}
}
}
impl Div for u64 {
type Output = BigInt;
#[inline]
fn div(self, other: BigInt) -> BigInt {
BigInt::from_biguint(other.sign, self / other.data)
}
}
impl Div for BigInt {
type Output = BigInt;
#[inline]
fn div(self, other: u128) -> BigInt {
BigInt::from_biguint(self.sign, self.data / other)
}
}
impl DivAssign for BigInt {
#[inline]
fn div_assign(&mut self, other: u128) {
self.data /= other;
if self.data.is_zero() {
self.sign = NoSign;
}
}
}
impl Div for u128 {
type Output = BigInt;
#[inline]
fn div(self, other: BigInt) -> BigInt {
BigInt::from_biguint(other.sign, self / other.data)
}
}
forward_all_scalar_binop_to_val_val!(impl Div for BigInt, div);
forward_all_scalar_binop_to_val_val!(impl Div for BigInt, div);
forward_all_scalar_binop_to_val_val!(impl Div for BigInt, div);
impl Div for BigInt {
type Output = BigInt;
#[inline]
fn div(self, other: i32) -> BigInt {
match other.checked_uabs() {
Positive(u) => self / u,
Negative(u) => -self / u,
}
}
}
impl DivAssign for BigInt {
#[inline]
fn div_assign(&mut self, other: i32) {
match other.checked_uabs() {
Positive(u) => *self /= u,
Negative(u) => {
self.sign = -self.sign;
*self /= u;
}
}
}
}
impl Div for i32 {
type Output = BigInt;
#[inline]
fn div(self, other: BigInt) -> BigInt {
match self.checked_uabs() {
Positive(u) => u / other,
Negative(u) => u / -other,
}
}
}
impl Div for BigInt {
type Output = BigInt;
#[inline]
fn div(self, other: i64) -> BigInt {
match other.checked_uabs() {
Positive(u) => self / u,
Negative(u) => -self / u,
}
}
}
impl DivAssign for BigInt {
#[inline]
fn div_assign(&mut self, other: i64) {
match other.checked_uabs() {
Positive(u) => *self /= u,
Negative(u) => {
self.sign = -self.sign;
*self /= u;
}
}
}
}
impl Div for i64 {
type Output = BigInt;
#[inline]
fn div(self, other: BigInt) -> BigInt {
match self.checked_uabs() {
Positive(u) => u / other,
Negative(u) => u / -other,
}
}
}
impl Div for BigInt {
type Output = BigInt;
#[inline]
fn div(self, other: i128) -> BigInt {
match other.checked_uabs() {
Positive(u) => self / u,
Negative(u) => -self / u,
}
}
}
impl DivAssign for BigInt {
#[inline]
fn div_assign(&mut self, other: i128) {
match other.checked_uabs() {
Positive(u) => *self /= u,
Negative(u) => {
self.sign = -self.sign;
*self /= u;
}
}
}
}
impl Div for i128 {
type Output = BigInt;
#[inline]
fn div(self, other: BigInt) -> BigInt {
match self.checked_uabs() {
Positive(u) => u / other,
Negative(u) => u / -other,
}
}
}
forward_all_binop_to_ref_ref!(impl Rem for BigInt, rem);
impl<'a, 'b> Rem<&'b BigInt> for &'a BigInt {
type Output = BigInt;
#[inline]
fn rem(self, other: &BigInt) -> BigInt {
if let Some(other) = other.to_u32() {
self % other
} else if let Some(other) = other.to_i32() {
self % other
} else {
let (_, r) = self.div_rem(other);
r
}
}
}
impl<'a> RemAssign<&'a BigInt> for BigInt {
#[inline]
fn rem_assign(&mut self, other: &BigInt) {
*self = &*self % other;
}
}
forward_val_assign!(impl RemAssign for BigInt, rem_assign);
promote_all_scalars!(impl Rem for BigInt, rem);
promote_all_scalars_assign!(impl RemAssign for BigInt, rem_assign);
forward_all_scalar_binop_to_val_val!(impl Rem for BigInt, rem);
forward_all_scalar_binop_to_val_val!(impl Rem for BigInt, rem);
forward_all_scalar_binop_to_val_val!(impl Rem for BigInt, rem);
impl Rem for BigInt {
type Output = BigInt;
#[inline]
fn rem(self, other: u32) -> BigInt {
BigInt::from_biguint(self.sign, self.data % other)
}
}
impl RemAssign for BigInt {
#[inline]
fn rem_assign(&mut self, other: u32) {
self.data %= other;
if self.data.is_zero() {
self.sign = NoSign;
}
}
}
impl Rem for u32 {
type Output = BigInt;
#[inline]
fn rem(self, other: BigInt) -> BigInt {
BigInt::from(self % other.data)
}
}
impl Rem for BigInt {
type Output = BigInt;
#[inline]
fn rem(self, other: u64) -> BigInt {
BigInt::from_biguint(self.sign, self.data % other)
}
}
impl RemAssign for BigInt {
#[inline]
fn rem_assign(&mut self, other: u64) {
self.data %= other;
if self.data.is_zero() {
self.sign = NoSign;
}
}
}
impl Rem for u64 {
type Output = BigInt;
#[inline]
fn rem(self, other: BigInt) -> BigInt {
BigInt::from(self % other.data)
}
}
impl Rem for BigInt {
type Output = BigInt;
#[inline]
fn rem(self, other: u128) -> BigInt {
BigInt::from_biguint(self.sign, self.data % other)
}
}
impl RemAssign for BigInt {
#[inline]
fn rem_assign(&mut self, other: u128) {
self.data %= other;
if self.data.is_zero() {
self.sign = NoSign;
}
}
}
impl Rem for u128 {
type Output = BigInt;
#[inline]
fn rem(self, other: BigInt) -> BigInt {
BigInt::from(self % other.data)
}
}
forward_all_scalar_binop_to_val_val!(impl Rem for BigInt, rem);
forward_all_scalar_binop_to_val_val!(impl Rem for BigInt, rem);
forward_all_scalar_binop_to_val_val!(impl Rem for BigInt, rem);
impl Rem for BigInt {
type Output = BigInt;
#[inline]
fn rem(self, other: i32) -> BigInt {
self % other.uabs()
}
}
impl RemAssign for BigInt {
#[inline]
fn rem_assign(&mut self, other: i32) {
*self %= other.uabs();
}
}
impl Rem for i32 {
type Output = BigInt;
#[inline]
fn rem(self, other: BigInt) -> BigInt {
match self.checked_uabs() {
Positive(u) => u % other,
Negative(u) => -(u % other),
}
}
}
impl Rem for BigInt {
type Output = BigInt;
#[inline]
fn rem(self, other: i64) -> BigInt {
self % other.uabs()
}
}
impl RemAssign for BigInt {
#[inline]
fn rem_assign(&mut self, other: i64) {
*self %= other.uabs();
}
}
impl Rem for i64 {
type Output = BigInt;
#[inline]
fn rem(self, other: BigInt) -> BigInt {
match self.checked_uabs() {
Positive(u) => u % other,
Negative(u) => -(u % other),
}
}
}
impl Rem for BigInt {
type Output = BigInt;
#[inline]
fn rem(self, other: i128) -> BigInt {
self % other.uabs()
}
}
impl RemAssign for BigInt {
#[inline]
fn rem_assign(&mut self, other: i128) {
*self %= other.uabs();
}
}
impl Rem for i128 {
type Output = BigInt;
#[inline]
fn rem(self, other: BigInt) -> BigInt {
match self.checked_uabs() {
Positive(u) => u % other,
Negative(u) => -(u % other),
}
}
}
impl CheckedDiv for BigInt {
#[inline]
fn checked_div(&self, v: &BigInt) -> Option {
if v.is_zero() {
return None;
}
Some(self.div(v))
}
}
num-bigint-0.4.3/src/bigint/multiplication.rs 0000644 0000000 0000000 00000012573 00726746425 0017407 0 ustar 0000000 0000000 use super::CheckedUnsignedAbs::{Negative, Positive};
use super::Sign::{self, Minus, NoSign, Plus};
use super::{BigInt, UnsignedAbs};
use crate::{IsizePromotion, UsizePromotion};
use core::iter::Product;
use core::ops::{Mul, MulAssign};
use num_traits::{CheckedMul, One, Zero};
impl Mul for Sign {
type Output = Sign;
#[inline]
fn mul(self, other: Sign) -> Sign {
match (self, other) {
(NoSign, _) | (_, NoSign) => NoSign,
(Plus, Plus) | (Minus, Minus) => Plus,
(Plus, Minus) | (Minus, Plus) => Minus,
}
}
}
macro_rules! impl_mul {
($(impl<$($a:lifetime),*> Mul<$Other:ty> for $Self:ty;)*) => {$(
impl<$($a),*> Mul<$Other> for $Self {
type Output = BigInt;
#[inline]
fn mul(self, other: $Other) -> BigInt {
// automatically match value/ref
let BigInt { data: x, .. } = self;
let BigInt { data: y, .. } = other;
BigInt::from_biguint(self.sign * other.sign, x * y)
}
}
)*}
}
impl_mul! {
impl<> Mul for BigInt;
impl<'b> Mul<&'b BigInt> for BigInt;
impl<'a> Mul for &'a BigInt;
impl<'a, 'b> Mul<&'b BigInt> for &'a BigInt;
}
macro_rules! impl_mul_assign {
($(impl<$($a:lifetime),*> MulAssign<$Other:ty> for BigInt;)*) => {$(
impl<$($a),*> MulAssign<$Other> for BigInt {
#[inline]
fn mul_assign(&mut self, other: $Other) {
// automatically match value/ref
let BigInt { data: y, .. } = other;
self.data *= y;
if self.data.is_zero() {
self.sign = NoSign;
} else {
self.sign = self.sign * other.sign;
}
}
}
)*}
}
impl_mul_assign! {
impl<> MulAssign for BigInt;
impl<'a> MulAssign<&'a BigInt> for BigInt;
}
promote_all_scalars!(impl Mul for BigInt, mul);
promote_all_scalars_assign!(impl MulAssign for BigInt, mul_assign);
forward_all_scalar_binop_to_val_val_commutative!(impl Mul for BigInt, mul);
forward_all_scalar_binop_to_val_val_commutative!(impl Mul for BigInt, mul);
forward_all_scalar_binop_to_val_val_commutative!(impl Mul for BigInt, mul);
impl Mul for BigInt {
type Output = BigInt;
#[inline]
fn mul(self, other: u32) -> BigInt {
BigInt::from_biguint(self.sign, self.data * other)
}
}
impl MulAssign for BigInt {
#[inline]
fn mul_assign(&mut self, other: u32) {
self.data *= other;
if self.data.is_zero() {
self.sign = NoSign;
}
}
}
impl Mul for BigInt {
type Output = BigInt;
#[inline]
fn mul(self, other: u64) -> BigInt {
BigInt::from_biguint(self.sign, self.data * other)
}
}
impl MulAssign for BigInt {
#[inline]
fn mul_assign(&mut self, other: u64) {
self.data *= other;
if self.data.is_zero() {
self.sign = NoSign;
}
}
}
impl Mul for BigInt {
type Output = BigInt;
#[inline]
fn mul(self, other: u128) -> BigInt {
BigInt::from_biguint(self.sign, self.data * other)
}
}
impl MulAssign for BigInt {
#[inline]
fn mul_assign(&mut self, other: u128) {
self.data *= other;
if self.data.is_zero() {
self.sign = NoSign;
}
}
}
forward_all_scalar_binop_to_val_val_commutative!(impl Mul for BigInt, mul);
forward_all_scalar_binop_to_val_val_commutative!(impl Mul for BigInt, mul);
forward_all_scalar_binop_to_val_val_commutative!(impl Mul for BigInt, mul);
impl Mul for BigInt {
type Output = BigInt;
#[inline]
fn mul(self, other: i32) -> BigInt {
match other.checked_uabs() {
Positive(u) => self * u,
Negative(u) => -self * u,
}
}
}
impl MulAssign for BigInt {
#[inline]
fn mul_assign(&mut self, other: i32) {
match other.checked_uabs() {
Positive(u) => *self *= u,
Negative(u) => {
self.sign = -self.sign;
self.data *= u;
}
}
}
}
impl Mul for BigInt {
type Output = BigInt;
#[inline]
fn mul(self, other: i64) -> BigInt {
match other.checked_uabs() {
Positive(u) => self * u,
Negative(u) => -self * u,
}
}
}
impl MulAssign for BigInt {
#[inline]
fn mul_assign(&mut self, other: i64) {
match other.checked_uabs() {
Positive(u) => *self *= u,
Negative(u) => {
self.sign = -self.sign;
self.data *= u;
}
}
}
}
impl Mul for BigInt {
type Output = BigInt;
#[inline]
fn mul(self, other: i128) -> BigInt {
match other.checked_uabs() {
Positive(u) => self * u,
Negative(u) => -self * u,
}
}
}
impl MulAssign for BigInt {
#[inline]
fn mul_assign(&mut self, other: i128) {
match other.checked_uabs() {
Positive(u) => *self *= u,
Negative(u) => {
self.sign = -self.sign;
self.data *= u;
}
}
}
}
impl CheckedMul for BigInt {
#[inline]
fn checked_mul(&self, v: &BigInt) -> Option {
Some(self.mul(v))
}
}
impl_product_iter_type!(BigInt);
num-bigint-0.4.3/src/bigint/power.rs 0000644 0000000 0000000 00000004607 00726746425 0015505 0 ustar 0000000 0000000 use super::BigInt;
use super::Sign::{self, Minus, Plus};
use crate::BigUint;
use num_integer::Integer;
use num_traits::{Pow, Signed, Zero};
/// Help function for pow
///
/// Computes the effect of the exponent on the sign.
#[inline]
fn powsign(sign: Sign, other: &T) -> Sign {
if other.is_zero() {
Plus
} else if sign != Minus || other.is_odd() {
sign
} else {
-sign
}
}
macro_rules! pow_impl {
($T:ty) => {
impl Pow<$T> for BigInt {
type Output = BigInt;
#[inline]
fn pow(self, rhs: $T) -> BigInt {
BigInt::from_biguint(powsign(self.sign, &rhs), self.data.pow(rhs))
}
}
impl<'b> Pow<&'b $T> for BigInt {
type Output = BigInt;
#[inline]
fn pow(self, rhs: &$T) -> BigInt {
BigInt::from_biguint(powsign(self.sign, rhs), self.data.pow(rhs))
}
}
impl<'a> Pow<$T> for &'a BigInt {
type Output = BigInt;
#[inline]
fn pow(self, rhs: $T) -> BigInt {
BigInt::from_biguint(powsign(self.sign, &rhs), Pow::pow(&self.data, rhs))
}
}
impl<'a, 'b> Pow<&'b $T> for &'a BigInt {
type Output = BigInt;
#[inline]
fn pow(self, rhs: &$T) -> BigInt {
BigInt::from_biguint(powsign(self.sign, rhs), Pow::pow(&self.data, rhs))
}
}
};
}
pow_impl!(u8);
pow_impl!(u16);
pow_impl!(u32);
pow_impl!(u64);
pow_impl!(usize);
pow_impl!(u128);
pow_impl!(BigUint);
pub(super) fn modpow(x: &BigInt, exponent: &BigInt, modulus: &BigInt) -> BigInt {
assert!(
!exponent.is_negative(),
"negative exponentiation is not supported!"
);
assert!(
!modulus.is_zero(),
"attempt to calculate with zero modulus!"
);
let result = x.data.modpow(&exponent.data, &modulus.data);
if result.is_zero() {
return BigInt::zero();
}
// The sign of the result follows the modulus, like `mod_floor`.
let (sign, mag) = match (x.is_negative() && exponent.is_odd(), modulus.is_negative()) {
(false, false) => (Plus, result),
(true, false) => (Plus, &modulus.data - result),
(false, true) => (Minus, &modulus.data - result),
(true, true) => (Minus, result),
};
BigInt::from_biguint(sign, mag)
}
num-bigint-0.4.3/src/bigint/serde.rs 0000644 0000000 0000000 00000003261 00726746425 0015446 0 ustar 0000000 0000000 use super::{BigInt, Sign};
use serde::de::{Error, Unexpected};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
impl Serialize for Sign {
fn serialize
(&self, serializer: S) -> Result
where
S: Serializer,
{
// Note: do not change the serialization format, or it may break
// forward and backward compatibility of serialized data!
match *self {
Sign::Minus => (-1i8).serialize(serializer),
Sign::NoSign => 0i8.serialize(serializer),
Sign::Plus => 1i8.serialize(serializer),
}
}
}
impl<'de> Deserialize<'de> for Sign {
fn deserialize(deserializer: D) -> Result
where
D: Deserializer<'de>,
{
let sign = i8::deserialize(deserializer)?;
match sign {
-1 => Ok(Sign::Minus),
0 => Ok(Sign::NoSign),
1 => Ok(Sign::Plus),
_ => Err(D::Error::invalid_value(
Unexpected::Signed(sign.into()),
&"a sign of -1, 0, or 1",
)),
}
}
}
impl Serialize for BigInt {
fn serialize(&self, serializer: S) -> Result
where
S: Serializer,
{
// Note: do not change the serialization format, or it may break
// forward and backward compatibility of serialized data!
(self.sign, &self.data).serialize(serializer)
}
}
impl<'de> Deserialize<'de> for BigInt {
fn deserialize(deserializer: D) -> Result
where
D: Deserializer<'de>,
{
let (sign, data) = Deserialize::deserialize(deserializer)?;
Ok(BigInt::from_biguint(sign, data))
}
}
num-bigint-0.4.3/src/bigint/shift.rs 0000644 0000000 0000000 00000006544 00726746425 0015470 0 ustar 0000000 0000000 use super::BigInt;
use super::Sign::NoSign;
use core::ops::{Shl, ShlAssign, Shr, ShrAssign};
use num_traits::{PrimInt, Signed, Zero};
macro_rules! impl_shift {
(@ref $Shx:ident :: $shx:ident, $ShxAssign:ident :: $shx_assign:ident, $rhs:ty) => {
impl<'b> $Shx<&'b $rhs> for BigInt {
type Output = BigInt;
#[inline]
fn $shx(self, rhs: &'b $rhs) -> BigInt {
$Shx::$shx(self, *rhs)
}
}
impl<'a, 'b> $Shx<&'b $rhs> for &'a BigInt {
type Output = BigInt;
#[inline]
fn $shx(self, rhs: &'b $rhs) -> BigInt {
$Shx::$shx(self, *rhs)
}
}
impl<'b> $ShxAssign<&'b $rhs> for BigInt {
#[inline]
fn $shx_assign(&mut self, rhs: &'b $rhs) {
$ShxAssign::$shx_assign(self, *rhs);
}
}
};
($($rhs:ty),+) => {$(
impl Shl<$rhs> for BigInt {
type Output = BigInt;
#[inline]
fn shl(self, rhs: $rhs) -> BigInt {
BigInt::from_biguint(self.sign, self.data << rhs)
}
}
impl<'a> Shl<$rhs> for &'a BigInt {
type Output = BigInt;
#[inline]
fn shl(self, rhs: $rhs) -> BigInt {
BigInt::from_biguint(self.sign, &self.data << rhs)
}
}
impl ShlAssign<$rhs> for BigInt {
#[inline]
fn shl_assign(&mut self, rhs: $rhs) {
self.data <<= rhs
}
}
impl_shift! { @ref Shl::shl, ShlAssign::shl_assign, $rhs }
impl Shr<$rhs> for BigInt {
type Output = BigInt;
#[inline]
fn shr(self, rhs: $rhs) -> BigInt {
let round_down = shr_round_down(&self, rhs);
let data = self.data >> rhs;
let data = if round_down { data + 1u8 } else { data };
BigInt::from_biguint(self.sign, data)
}
}
impl<'a> Shr<$rhs> for &'a BigInt {
type Output = BigInt;
#[inline]
fn shr(self, rhs: $rhs) -> BigInt {
let round_down = shr_round_down(self, rhs);
let data = &self.data >> rhs;
let data = if round_down { data + 1u8 } else { data };
BigInt::from_biguint(self.sign, data)
}
}
impl ShrAssign<$rhs> for BigInt {
#[inline]
fn shr_assign(&mut self, rhs: $rhs) {
let round_down = shr_round_down(self, rhs);
self.data >>= rhs;
if round_down {
self.data += 1u8;
} else if self.data.is_zero() {
self.sign = NoSign;
}
}
}
impl_shift! { @ref Shr::shr, ShrAssign::shr_assign, $rhs }
)*};
}
impl_shift! { u8, u16, u32, u64, u128, usize }
impl_shift! { i8, i16, i32, i64, i128, isize }
// Negative values need a rounding adjustment if there are any ones in the
// bits that are getting shifted out.
fn shr_round_down(i: &BigInt, shift: T) -> bool {
if i.is_negative() {
let zeros = i.trailing_zeros().expect("negative values are non-zero");
shift > T::zero() && shift.to_u64().map(|shift| zeros < shift).unwrap_or(true)
} else {
false
}
}
num-bigint-0.4.3/src/bigint/subtraction.rs 0000644 0000000 0000000 00000017104 00726746425 0016702 0 ustar 0000000 0000000 use super::CheckedUnsignedAbs::{Negative, Positive};
use super::Sign::{Minus, NoSign, Plus};
use super::{BigInt, UnsignedAbs};
use crate::{IsizePromotion, UsizePromotion};
use core::cmp::Ordering::{Equal, Greater, Less};
use core::mem;
use core::ops::{Sub, SubAssign};
use num_traits::{CheckedSub, Zero};
// We want to forward to BigUint::sub, but it's not clear how that will go until
// we compare both sign and magnitude. So we duplicate this body for every
// val/ref combination, deferring that decision to BigUint's own forwarding.
macro_rules! bigint_sub {
($a:expr, $a_owned:expr, $a_data:expr, $b:expr, $b_owned:expr, $b_data:expr) => {
match ($a.sign, $b.sign) {
(_, NoSign) => $a_owned,
(NoSign, _) => -$b_owned,
// opposite signs => keep the sign of the left with the sum of magnitudes
(Plus, Minus) | (Minus, Plus) => BigInt::from_biguint($a.sign, $a_data + $b_data),
// same sign => keep or toggle the sign of the left with the difference of magnitudes
(Plus, Plus) | (Minus, Minus) => match $a.data.cmp(&$b.data) {
Less => BigInt::from_biguint(-$a.sign, $b_data - $a_data),
Greater => BigInt::from_biguint($a.sign, $a_data - $b_data),
Equal => Zero::zero(),
},
}
};
}
impl<'a, 'b> Sub<&'b BigInt> for &'a BigInt {
type Output = BigInt;
#[inline]
fn sub(self, other: &BigInt) -> BigInt {
bigint_sub!(
self,
self.clone(),
&self.data,
other,
other.clone(),
&other.data
)
}
}
impl<'a> Sub for &'a BigInt {
type Output = BigInt;
#[inline]
fn sub(self, other: BigInt) -> BigInt {
bigint_sub!(self, self.clone(), &self.data, other, other, other.data)
}
}
impl<'a> Sub<&'a BigInt> for BigInt {
type Output = BigInt;
#[inline]
fn sub(self, other: &BigInt) -> BigInt {
bigint_sub!(self, self, self.data, other, other.clone(), &other.data)
}
}
impl Sub for BigInt {
type Output = BigInt;
#[inline]
fn sub(self, other: BigInt) -> BigInt {
bigint_sub!(self, self, self.data, other, other, other.data)
}
}
impl<'a> SubAssign<&'a BigInt> for BigInt {
#[inline]
fn sub_assign(&mut self, other: &BigInt) {
let n = mem::replace(self, BigInt::zero());
*self = n - other;
}
}
forward_val_assign!(impl SubAssign for BigInt, sub_assign);
promote_all_scalars!(impl Sub for BigInt, sub);
promote_all_scalars_assign!(impl SubAssign for BigInt, sub_assign);
forward_all_scalar_binop_to_val_val!(impl Sub for BigInt, sub);
forward_all_scalar_binop_to_val_val!(impl Sub for BigInt, sub);
forward_all_scalar_binop_to_val_val!(impl Sub for BigInt, sub);
impl Sub for BigInt {
type Output = BigInt;
#[inline]
fn sub(self, other: u32) -> BigInt {
match self.sign {
NoSign => -BigInt::from(other),
Minus => -BigInt::from(self.data + other),
Plus => match self.data.cmp(&From::from(other)) {
Equal => Zero::zero(),
Greater => BigInt::from(self.data - other),
Less => -BigInt::from(other - self.data),
},
}
}
}
impl SubAssign for BigInt {
#[inline]
fn sub_assign(&mut self, other: u32) {
let n = mem::replace(self, BigInt::zero());
*self = n - other;
}
}
impl Sub for u32 {
type Output = BigInt;
#[inline]
fn sub(self, other: BigInt) -> BigInt {
-(other - self)
}
}
impl Sub for u64 {
type Output = BigInt;
#[inline]
fn sub(self, other: BigInt) -> BigInt {
-(other - self)
}
}
impl Sub for u128 {
type Output = BigInt;
#[inline]
fn sub(self, other: BigInt) -> BigInt {
-(other - self)
}
}
impl Sub for BigInt {
type Output = BigInt;
#[inline]
fn sub(self, other: u64) -> BigInt {
match self.sign {
NoSign => -BigInt::from(other),
Minus => -BigInt::from(self.data + other),
Plus => match self.data.cmp(&From::from(other)) {
Equal => Zero::zero(),
Greater => BigInt::from(self.data - other),
Less => -BigInt::from(other - self.data),
},
}
}
}
impl SubAssign for BigInt {
#[inline]
fn sub_assign(&mut self, other: u64) {
let n = mem::replace(self, BigInt::zero());
*self = n - other;
}
}
impl Sub for BigInt {
type Output = BigInt;
#[inline]
fn sub(self, other: u128) -> BigInt {
match self.sign {
NoSign => -BigInt::from(other),
Minus => -BigInt::from(self.data + other),
Plus => match self.data.cmp(&From::from(other)) {
Equal => Zero::zero(),
Greater => BigInt::from(self.data - other),
Less => -BigInt::from(other - self.data),
},
}
}
}
impl SubAssign for BigInt {
#[inline]
fn sub_assign(&mut self, other: u128) {
let n = mem::replace(self, BigInt::zero());
*self = n - other;
}
}
forward_all_scalar_binop_to_val_val!(impl Sub for BigInt, sub);
forward_all_scalar_binop_to_val_val!(impl Sub for BigInt, sub);
forward_all_scalar_binop_to_val_val!(impl Sub for BigInt, sub);
impl Sub for BigInt {
type Output = BigInt;
#[inline]
fn sub(self, other: i32) -> BigInt {
match other.checked_uabs() {
Positive(u) => self - u,
Negative(u) => self + u,
}
}
}
impl SubAssign for BigInt {
#[inline]
fn sub_assign(&mut self, other: i32) {
match other.checked_uabs() {
Positive(u) => *self -= u,
Negative(u) => *self += u,
}
}
}
impl Sub for i32 {
type Output = BigInt;
#[inline]
fn sub(self, other: BigInt) -> BigInt {
match self.checked_uabs() {
Positive(u) => u - other,
Negative(u) => -other - u,
}
}
}
impl Sub for BigInt {
type Output = BigInt;
#[inline]
fn sub(self, other: i64) -> BigInt {
match other.checked_uabs() {
Positive(u) => self - u,
Negative(u) => self + u,
}
}
}
impl SubAssign for BigInt {
#[inline]
fn sub_assign(&mut self, other: i64) {
match other.checked_uabs() {
Positive(u) => *self -= u,
Negative(u) => *self += u,
}
}
}
impl Sub for i64 {
type Output = BigInt;
#[inline]
fn sub(self, other: BigInt) -> BigInt {
match self.checked_uabs() {
Positive(u) => u - other,
Negative(u) => -other - u,
}
}
}
impl Sub for BigInt {
type Output = BigInt;
#[inline]
fn sub(self, other: i128) -> BigInt {
match other.checked_uabs() {
Positive(u) => self - u,
Negative(u) => self + u,
}
}
}
impl SubAssign for BigInt {
#[inline]
fn sub_assign(&mut self, other: i128) {
match other.checked_uabs() {
Positive(u) => *self -= u,
Negative(u) => *self += u,
}
}
}
impl Sub for i128 {
type Output = BigInt;
#[inline]
fn sub(self, other: BigInt) -> BigInt {
match self.checked_uabs() {
Positive(u) => u - other,
Negative(u) => -other - u,
}
}
}
impl CheckedSub for BigInt {
#[inline]
fn checked_sub(&self, v: &BigInt) -> Option {
Some(self.sub(v))
}
}
num-bigint-0.4.3/src/bigint.rs 0000644 0000000 0000000 00000102203 00726746425 0014340 0 ustar 0000000 0000000 // `Add`/`Sub` ops may flip from `BigInt` to its `BigUint` magnitude
#![allow(clippy::suspicious_arithmetic_impl)]
use crate::std_alloc::{String, Vec};
use core::cmp::Ordering::{self, Equal};
use core::default::Default;
use core::fmt;
use core::hash;
use core::ops::{Neg, Not};
use core::str;
use core::{i128, u128};
use core::{i64, u64};
use num_integer::{Integer, Roots};
use num_traits::{Num, One, Pow, Signed, Zero};
use self::Sign::{Minus, NoSign, Plus};
use crate::big_digit::BigDigit;
use crate::biguint::to_str_radix_reversed;
use crate::biguint::{BigUint, IntDigits, U32Digits, U64Digits};
mod addition;
mod division;
mod multiplication;
mod subtraction;
mod bits;
mod convert;
mod power;
mod shift;
#[cfg(any(feature = "quickcheck", feature = "arbitrary"))]
mod arbitrary;
#[cfg(feature = "serde")]
mod serde;
/// A Sign is a `BigInt`'s composing element.
#[derive(PartialEq, PartialOrd, Eq, Ord, Copy, Clone, Debug, Hash)]
pub enum Sign {
Minus,
NoSign,
Plus,
}
impl Neg for Sign {
type Output = Sign;
/// Negate Sign value.
#[inline]
fn neg(self) -> Sign {
match self {
Minus => Plus,
NoSign => NoSign,
Plus => Minus,
}
}
}
/// A big signed integer type.
pub struct BigInt {
sign: Sign,
data: BigUint,
}
// Note: derived `Clone` doesn't specialize `clone_from`,
// but we want to keep the allocation in `data`.
impl Clone for BigInt {
#[inline]
fn clone(&self) -> Self {
BigInt {
sign: self.sign,
data: self.data.clone(),
}
}
#[inline]
fn clone_from(&mut self, other: &Self) {
self.sign = other.sign;
self.data.clone_from(&other.data);
}
}
impl hash::Hash for BigInt {
#[inline]
fn hash(&self, state: &mut H) {
debug_assert!((self.sign != NoSign) ^ self.data.is_zero());
self.sign.hash(state);
if self.sign != NoSign {
self.data.hash(state);
}
}
}
impl PartialEq for BigInt {
#[inline]
fn eq(&self, other: &BigInt) -> bool {
debug_assert!((self.sign != NoSign) ^ self.data.is_zero());
debug_assert!((other.sign != NoSign) ^ other.data.is_zero());
self.sign == other.sign && (self.sign == NoSign || self.data == other.data)
}
}
impl Eq for BigInt {}
impl PartialOrd for BigInt {
#[inline]
fn partial_cmp(&self, other: &BigInt) -> Option {
Some(self.cmp(other))
}
}
impl Ord for BigInt {
#[inline]
fn cmp(&self, other: &BigInt) -> Ordering {
debug_assert!((self.sign != NoSign) ^ self.data.is_zero());
debug_assert!((other.sign != NoSign) ^ other.data.is_zero());
let scmp = self.sign.cmp(&other.sign);
if scmp != Equal {
return scmp;
}
match self.sign {
NoSign => Equal,
Plus => self.data.cmp(&other.data),
Minus => other.data.cmp(&self.data),
}
}
}
impl Default for BigInt {
#[inline]
fn default() -> BigInt {
Zero::zero()
}
}
impl fmt::Debug for BigInt {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl fmt::Display for BigInt {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad_integral(!self.is_negative(), "", &self.data.to_str_radix(10))
}
}
impl fmt::Binary for BigInt {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad_integral(!self.is_negative(), "0b", &self.data.to_str_radix(2))
}
}
impl fmt::Octal for BigInt {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad_integral(!self.is_negative(), "0o", &self.data.to_str_radix(8))
}
}
impl fmt::LowerHex for BigInt {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad_integral(!self.is_negative(), "0x", &self.data.to_str_radix(16))
}
}
impl fmt::UpperHex for BigInt {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut s = self.data.to_str_radix(16);
s.make_ascii_uppercase();
f.pad_integral(!self.is_negative(), "0x", &s)
}
}
// !-2 = !...f fe = ...0 01 = +1
// !-1 = !...f ff = ...0 00 = 0
// ! 0 = !...0 00 = ...f ff = -1
// !+1 = !...0 01 = ...f fe = -2
impl Not for BigInt {
type Output = BigInt;
fn not(mut self) -> BigInt {
match self.sign {
NoSign | Plus => {
self.data += 1u32;
self.sign = Minus;
}
Minus => {
self.data -= 1u32;
self.sign = if self.data.is_zero() { NoSign } else { Plus };
}
}
self
}
}
impl<'a> Not for &'a BigInt {
type Output = BigInt;
fn not(self) -> BigInt {
match self.sign {
NoSign => -BigInt::one(),
Plus => -BigInt::from(&self.data + 1u32),
Minus => BigInt::from(&self.data - 1u32),
}
}
}
impl Zero for BigInt {
#[inline]
fn zero() -> BigInt {
BigInt {
sign: NoSign,
data: BigUint::zero(),
}
}
#[inline]
fn set_zero(&mut self) {
self.data.set_zero();
self.sign = NoSign;
}
#[inline]
fn is_zero(&self) -> bool {
self.sign == NoSign
}
}
impl One for BigInt {
#[inline]
fn one() -> BigInt {
BigInt {
sign: Plus,
data: BigUint::one(),
}
}
#[inline]
fn set_one(&mut self) {
self.data.set_one();
self.sign = Plus;
}
#[inline]
fn is_one(&self) -> bool {
self.sign == Plus && self.data.is_one()
}
}
impl Signed for BigInt {
#[inline]
fn abs(&self) -> BigInt {
match self.sign {
Plus | NoSign => self.clone(),
Minus => BigInt::from(self.data.clone()),
}
}
#[inline]
fn abs_sub(&self, other: &BigInt) -> BigInt {
if *self <= *other {
Zero::zero()
} else {
self - other
}
}
#[inline]
fn signum(&self) -> BigInt {
match self.sign {
Plus => BigInt::one(),
Minus => -BigInt::one(),
NoSign => BigInt::zero(),
}
}
#[inline]
fn is_positive(&self) -> bool {
self.sign == Plus
}
#[inline]
fn is_negative(&self) -> bool {
self.sign == Minus
}
}
trait UnsignedAbs {
type Unsigned;
/// A convenience method for getting the absolute value of a signed primitive as unsigned
/// See also `unsigned_abs`: https://github.com/rust-lang/rust/issues/74913
fn uabs(self) -> Self::Unsigned;
fn checked_uabs(self) -> CheckedUnsignedAbs;
}
enum CheckedUnsignedAbs {
Positive(T),
Negative(T),
}
use self::CheckedUnsignedAbs::{Negative, Positive};
macro_rules! impl_unsigned_abs {
($Signed:ty, $Unsigned:ty) => {
impl UnsignedAbs for $Signed {
type Unsigned = $Unsigned;
#[inline]
fn uabs(self) -> $Unsigned {
self.wrapping_abs() as $Unsigned
}
#[inline]
fn checked_uabs(self) -> CheckedUnsignedAbs {
if self >= 0 {
Positive(self as $Unsigned)
} else {
Negative(self.wrapping_neg() as $Unsigned)
}
}
}
};
}
impl_unsigned_abs!(i8, u8);
impl_unsigned_abs!(i16, u16);
impl_unsigned_abs!(i32, u32);
impl_unsigned_abs!(i64, u64);
impl_unsigned_abs!(i128, u128);
impl_unsigned_abs!(isize, usize);
impl Neg for BigInt {
type Output = BigInt;
#[inline]
fn neg(mut self) -> BigInt {
self.sign = -self.sign;
self
}
}
impl<'a> Neg for &'a BigInt {
type Output = BigInt;
#[inline]
fn neg(self) -> BigInt {
-self.clone()
}
}
impl Integer for BigInt {
#[inline]
fn div_rem(&self, other: &BigInt) -> (BigInt, BigInt) {
// r.sign == self.sign
let (d_ui, r_ui) = self.data.div_rem(&other.data);
let d = BigInt::from_biguint(self.sign, d_ui);
let r = BigInt::from_biguint(self.sign, r_ui);
if other.is_negative() {
(-d, r)
} else {
(d, r)
}
}
#[inline]
fn div_floor(&self, other: &BigInt) -> BigInt {
let (d_ui, m) = self.data.div_mod_floor(&other.data);
let d = BigInt::from(d_ui);
match (self.sign, other.sign) {
(Plus, Plus) | (NoSign, Plus) | (Minus, Minus) => d,
(Plus, Minus) | (NoSign, Minus) | (Minus, Plus) => {
if m.is_zero() {
-d
} else {
-d - 1u32
}
}
(_, NoSign) => unreachable!(),
}
}
#[inline]
fn mod_floor(&self, other: &BigInt) -> BigInt {
// m.sign == other.sign
let m_ui = self.data.mod_floor(&other.data);
let m = BigInt::from_biguint(other.sign, m_ui);
match (self.sign, other.sign) {
(Plus, Plus) | (NoSign, Plus) | (Minus, Minus) => m,
(Plus, Minus) | (NoSign, Minus) | (Minus, Plus) => {
if m.is_zero() {
m
} else {
other - m
}
}
(_, NoSign) => unreachable!(),
}
}
fn div_mod_floor(&self, other: &BigInt) -> (BigInt, BigInt) {
// m.sign == other.sign
let (d_ui, m_ui) = self.data.div_mod_floor(&other.data);
let d = BigInt::from(d_ui);
let m = BigInt::from_biguint(other.sign, m_ui);
match (self.sign, other.sign) {
(Plus, Plus) | (NoSign, Plus) | (Minus, Minus) => (d, m),
(Plus, Minus) | (NoSign, Minus) | (Minus, Plus) => {
if m.is_zero() {
(-d, m)
} else {
(-d - 1u32, other - m)
}
}
(_, NoSign) => unreachable!(),
}
}
#[inline]
fn div_ceil(&self, other: &Self) -> Self {
let (d_ui, m) = self.data.div_mod_floor(&other.data);
let d = BigInt::from(d_ui);
match (self.sign, other.sign) {
(Plus, Minus) | (NoSign, Minus) | (Minus, Plus) => -d,
(Plus, Plus) | (NoSign, Plus) | (Minus, Minus) => {
if m.is_zero() {
d
} else {
d + 1u32
}
}
(_, NoSign) => unreachable!(),
}
}
/// Calculates the Greatest Common Divisor (GCD) of the number and `other`.
///
/// The result is always positive.
#[inline]
fn gcd(&self, other: &BigInt) -> BigInt {
BigInt::from(self.data.gcd(&other.data))
}
/// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
#[inline]
fn lcm(&self, other: &BigInt) -> BigInt {
BigInt::from(self.data.lcm(&other.data))
}
/// Calculates the Greatest Common Divisor (GCD) and
/// Lowest Common Multiple (LCM) together.
#[inline]
fn gcd_lcm(&self, other: &BigInt) -> (BigInt, BigInt) {
let (gcd, lcm) = self.data.gcd_lcm(&other.data);
(BigInt::from(gcd), BigInt::from(lcm))
}
/// Greatest common divisor, least common multiple, and Bézout coefficients.
#[inline]
fn extended_gcd_lcm(&self, other: &BigInt) -> (num_integer::ExtendedGcd, BigInt) {
let egcd = self.extended_gcd(other);
let lcm = if egcd.gcd.is_zero() {
BigInt::zero()
} else {
BigInt::from(&self.data / &egcd.gcd.data * &other.data)
};
(egcd, lcm)
}
/// Deprecated, use `is_multiple_of` instead.
#[inline]
fn divides(&self, other: &BigInt) -> bool {
self.is_multiple_of(other)
}
/// Returns `true` if the number is a multiple of `other`.
#[inline]
fn is_multiple_of(&self, other: &BigInt) -> bool {
self.data.is_multiple_of(&other.data)
}
/// Returns `true` if the number is divisible by `2`.
#[inline]
fn is_even(&self) -> bool {
self.data.is_even()
}
/// Returns `true` if the number is not divisible by `2`.
#[inline]
fn is_odd(&self) -> bool {
self.data.is_odd()
}
/// Rounds up to nearest multiple of argument.
#[inline]
fn next_multiple_of(&self, other: &Self) -> Self {
let m = self.mod_floor(other);
if m.is_zero() {
self.clone()
} else {
self + (other - m)
}
}
/// Rounds down to nearest multiple of argument.
#[inline]
fn prev_multiple_of(&self, other: &Self) -> Self {
self - self.mod_floor(other)
}
}
impl Roots for BigInt {
fn nth_root(&self, n: u32) -> Self {
assert!(
!(self.is_negative() && n.is_even()),
"root of degree {} is imaginary",
n
);
BigInt::from_biguint(self.sign, self.data.nth_root(n))
}
fn sqrt(&self) -> Self {
assert!(!self.is_negative(), "square root is imaginary");
BigInt::from_biguint(self.sign, self.data.sqrt())
}
fn cbrt(&self) -> Self {
BigInt::from_biguint(self.sign, self.data.cbrt())
}
}
impl IntDigits for BigInt {
#[inline]
fn digits(&self) -> &[BigDigit] {
self.data.digits()
}
#[inline]
fn digits_mut(&mut self) -> &mut Vec {
self.data.digits_mut()
}
#[inline]
fn normalize(&mut self) {
self.data.normalize();
if self.data.is_zero() {
self.sign = NoSign;
}
}
#[inline]
fn capacity(&self) -> usize {
self.data.capacity()
}
#[inline]
fn len(&self) -> usize {
self.data.len()
}
}
/// A generic trait for converting a value to a `BigInt`. This may return
/// `None` when converting from `f32` or `f64`, and will always succeed
/// when converting from any integer or unsigned primitive, or `BigUint`.
pub trait ToBigInt {
/// Converts the value of `self` to a `BigInt`.
fn to_bigint(&self) -> Option;
}
impl BigInt {
/// Creates and initializes a BigInt.
///
/// The base 232 digits are ordered least significant digit first.
#[inline]
pub fn new(sign: Sign, digits: Vec) -> BigInt {
BigInt::from_biguint(sign, BigUint::new(digits))
}
/// Creates and initializes a `BigInt`.
///
/// The base 232 digits are ordered least significant digit first.
#[inline]
pub fn from_biguint(mut sign: Sign, mut data: BigUint) -> BigInt {
if sign == NoSign {
data.assign_from_slice(&[]);
} else if data.is_zero() {
sign = NoSign;
}
BigInt { sign, data }
}
/// Creates and initializes a `BigInt`.
///
/// The base 232 digits are ordered least significant digit first.
#[inline]
pub fn from_slice(sign: Sign, slice: &[u32]) -> BigInt {
BigInt::from_biguint(sign, BigUint::from_slice(slice))
}
/// Reinitializes a `BigInt`.
///
/// The base 232 digits are ordered least significant digit first.
#[inline]
pub fn assign_from_slice(&mut self, sign: Sign, slice: &[u32]) {
if sign == NoSign {
self.set_zero();
} else {
self.data.assign_from_slice(slice);
self.sign = if self.data.is_zero() { NoSign } else { sign };
}
}
/// Creates and initializes a `BigInt`.
///
/// The bytes are in big-endian byte order.
///
/// # Examples
///
/// ```
/// use num_bigint::{BigInt, Sign};
///
/// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"A"),
/// BigInt::parse_bytes(b"65", 10).unwrap());
/// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"AA"),
/// BigInt::parse_bytes(b"16705", 10).unwrap());
/// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"AB"),
/// BigInt::parse_bytes(b"16706", 10).unwrap());
/// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"Hello world!"),
/// BigInt::parse_bytes(b"22405534230753963835153736737", 10).unwrap());
/// ```
#[inline]
pub fn from_bytes_be(sign: Sign, bytes: &[u8]) -> BigInt {
BigInt::from_biguint(sign, BigUint::from_bytes_be(bytes))
}
/// Creates and initializes a `BigInt`.
///
/// The bytes are in little-endian byte order.
#[inline]
pub fn from_bytes_le(sign: Sign, bytes: &[u8]) -> BigInt {
BigInt::from_biguint(sign, BigUint::from_bytes_le(bytes))
}
/// Creates and initializes a `BigInt` from an array of bytes in
/// two's complement binary representation.
///
/// The digits are in big-endian base 28.
#[inline]
pub fn from_signed_bytes_be(digits: &[u8]) -> BigInt {
convert::from_signed_bytes_be(digits)
}
/// Creates and initializes a `BigInt` from an array of bytes in two's complement.
///
/// The digits are in little-endian base 28.
#[inline]
pub fn from_signed_bytes_le(digits: &[u8]) -> BigInt {
convert::from_signed_bytes_le(digits)
}
/// Creates and initializes a `BigInt`.
///
/// # Examples
///
/// ```
/// use num_bigint::{BigInt, ToBigInt};
///
/// assert_eq!(BigInt::parse_bytes(b"1234", 10), ToBigInt::to_bigint(&1234));
/// assert_eq!(BigInt::parse_bytes(b"ABCD", 16), ToBigInt::to_bigint(&0xABCD));
/// assert_eq!(BigInt::parse_bytes(b"G", 16), None);
/// ```
#[inline]
pub fn parse_bytes(buf: &[u8], radix: u32) -> Option {
let s = str::from_utf8(buf).ok()?;
BigInt::from_str_radix(s, radix).ok()
}
/// Creates and initializes a `BigInt`. Each u8 of the input slice is
/// interpreted as one digit of the number
/// and must therefore be less than `radix`.
///
/// The bytes are in big-endian byte order.
/// `radix` must be in the range `2...256`.
///
/// # Examples
///
/// ```
/// use num_bigint::{BigInt, Sign};
///
/// let inbase190 = vec![15, 33, 125, 12, 14];
/// let a = BigInt::from_radix_be(Sign::Minus, &inbase190, 190).unwrap();
/// assert_eq!(a.to_radix_be(190), (Sign:: Minus, inbase190));
/// ```
pub fn from_radix_be(sign: Sign, buf: &[u8], radix: u32) -> Option {
let u = BigUint::from_radix_be(buf, radix)?;
Some(BigInt::from_biguint(sign, u))
}
/// Creates and initializes a `BigInt`. Each u8 of the input slice is
/// interpreted as one digit of the number
/// and must therefore be less than `radix`.
///
/// The bytes are in little-endian byte order.
/// `radix` must be in the range `2...256`.
///
/// # Examples
///
/// ```
/// use num_bigint::{BigInt, Sign};
///
/// let inbase190 = vec![14, 12, 125, 33, 15];
/// let a = BigInt::from_radix_be(Sign::Minus, &inbase190, 190).unwrap();
/// assert_eq!(a.to_radix_be(190), (Sign::Minus, inbase190));
/// ```
pub fn from_radix_le(sign: Sign, buf: &[u8], radix: u32) -> Option {
let u = BigUint::from_radix_le(buf, radix)?;
Some(BigInt::from_biguint(sign, u))
}
/// Returns the sign and the byte representation of the `BigInt` in big-endian byte order.
///
/// # Examples
///
/// ```
/// use num_bigint::{ToBigInt, Sign};
///
/// let i = -1125.to_bigint().unwrap();
/// assert_eq!(i.to_bytes_be(), (Sign::Minus, vec![4, 101]));
/// ```
#[inline]
pub fn to_bytes_be(&self) -> (Sign, Vec) {
(self.sign, self.data.to_bytes_be())
}
/// Returns the sign and the byte representation of the `BigInt` in little-endian byte order.
///
/// # Examples
///
/// ```
/// use num_bigint::{ToBigInt, Sign};
///
/// let i = -1125.to_bigint().unwrap();
/// assert_eq!(i.to_bytes_le(), (Sign::Minus, vec![101, 4]));
/// ```
#[inline]
pub fn to_bytes_le(&self) -> (Sign, Vec) {
(self.sign, self.data.to_bytes_le())
}
/// Returns the sign and the `u32` digits representation of the `BigInt` ordered least
/// significant digit first.
///
/// # Examples
///
/// ```
/// use num_bigint::{BigInt, Sign};
///
/// assert_eq!(BigInt::from(-1125).to_u32_digits(), (Sign::Minus, vec![1125]));
/// assert_eq!(BigInt::from(4294967295u32).to_u32_digits(), (Sign::Plus, vec![4294967295]));
/// assert_eq!(BigInt::from(4294967296u64).to_u32_digits(), (Sign::Plus, vec![0, 1]));
/// assert_eq!(BigInt::from(-112500000000i64).to_u32_digits(), (Sign::Minus, vec![830850304, 26]));
/// assert_eq!(BigInt::from(112500000000i64).to_u32_digits(), (Sign::Plus, vec![830850304, 26]));
/// ```
#[inline]
pub fn to_u32_digits(&self) -> (Sign, Vec) {
(self.sign, self.data.to_u32_digits())
}
/// Returns the sign and the `u64` digits representation of the `BigInt` ordered least
/// significant digit first.
///
/// # Examples
///
/// ```
/// use num_bigint::{BigInt, Sign};
///
/// assert_eq!(BigInt::from(-1125).to_u64_digits(), (Sign::Minus, vec![1125]));
/// assert_eq!(BigInt::from(4294967295u32).to_u64_digits(), (Sign::Plus, vec![4294967295]));
/// assert_eq!(BigInt::from(4294967296u64).to_u64_digits(), (Sign::Plus, vec![4294967296]));
/// assert_eq!(BigInt::from(-112500000000i64).to_u64_digits(), (Sign::Minus, vec![112500000000]));
/// assert_eq!(BigInt::from(112500000000i64).to_u64_digits(), (Sign::Plus, vec![112500000000]));
/// assert_eq!(BigInt::from(1u128 << 64).to_u64_digits(), (Sign::Plus, vec![0, 1]));
/// ```
#[inline]
pub fn to_u64_digits(&self) -> (Sign, Vec) {
(self.sign, self.data.to_u64_digits())
}
/// Returns an iterator of `u32` digits representation of the `BigInt` ordered least
/// significant digit first.
///
/// # Examples
///
/// ```
/// use num_bigint::BigInt;
///
/// assert_eq!(BigInt::from(-1125).iter_u32_digits().collect::>(), vec![1125]);
/// assert_eq!(BigInt::from(4294967295u32).iter_u32_digits().collect::>(), vec![4294967295]);
/// assert_eq!(BigInt::from(4294967296u64).iter_u32_digits().collect::>(), vec![0, 1]);
/// assert_eq!(BigInt::from(-112500000000i64).iter_u32_digits().collect::>(), vec![830850304, 26]);
/// assert_eq!(BigInt::from(112500000000i64).iter_u32_digits().collect::>(), vec![830850304, 26]);
/// ```
#[inline]
pub fn iter_u32_digits(&self) -> U32Digits<'_> {
self.data.iter_u32_digits()
}
/// Returns an iterator of `u64` digits representation of the `BigInt` ordered least
/// significant digit first.
///
/// # Examples
///
/// ```
/// use num_bigint::BigInt;
///
/// assert_eq!(BigInt::from(-1125).iter_u64_digits().collect::>(), vec![1125u64]);
/// assert_eq!(BigInt::from(4294967295u32).iter_u64_digits().collect::>(), vec![4294967295u64]);
/// assert_eq!(BigInt::from(4294967296u64).iter_u64_digits().collect::>(), vec![4294967296u64]);
/// assert_eq!(BigInt::from(-112500000000i64).iter_u64_digits().collect::>(), vec![112500000000u64]);
/// assert_eq!(BigInt::from(112500000000i64).iter_u64_digits().collect::>(), vec![112500000000u64]);
/// assert_eq!(BigInt::from(1u128 << 64).iter_u64_digits().collect::>(), vec![0, 1]);
/// ```
#[inline]
pub fn iter_u64_digits(&self) -> U64Digits<'_> {
self.data.iter_u64_digits()
}
/// Returns the two's-complement byte representation of the `BigInt` in big-endian byte order.
///
/// # Examples
///
/// ```
/// use num_bigint::ToBigInt;
///
/// let i = -1125.to_bigint().unwrap();
/// assert_eq!(i.to_signed_bytes_be(), vec![251, 155]);
/// ```
#[inline]
pub fn to_signed_bytes_be(&self) -> Vec {
convert::to_signed_bytes_be(self)
}
/// Returns the two's-complement byte representation of the `BigInt` in little-endian byte order.
///
/// # Examples
///
/// ```
/// use num_bigint::ToBigInt;
///
/// let i = -1125.to_bigint().unwrap();
/// assert_eq!(i.to_signed_bytes_le(), vec![155, 251]);
/// ```
#[inline]
pub fn to_signed_bytes_le(&self) -> Vec {
convert::to_signed_bytes_le(self)
}
/// Returns the integer formatted as a string in the given radix.
/// `radix` must be in the range `2...36`.
///
/// # Examples
///
/// ```
/// use num_bigint::BigInt;
///
/// let i = BigInt::parse_bytes(b"ff", 16).unwrap();
/// assert_eq!(i.to_str_radix(16), "ff");
/// ```
#[inline]
pub fn to_str_radix(&self, radix: u32) -> String {
let mut v = to_str_radix_reversed(&self.data, radix);
if self.is_negative() {
v.push(b'-');
}
v.reverse();
unsafe { String::from_utf8_unchecked(v) }
}
/// Returns the integer in the requested base in big-endian digit order.
/// The output is not given in a human readable alphabet but as a zero
/// based u8 number.
/// `radix` must be in the range `2...256`.
///
/// # Examples
///
/// ```
/// use num_bigint::{BigInt, Sign};
///
/// assert_eq!(BigInt::from(-0xFFFFi64).to_radix_be(159),
/// (Sign::Minus, vec![2, 94, 27]));
/// // 0xFFFF = 65535 = 2*(159^2) + 94*159 + 27
/// ```
#[inline]
pub fn to_radix_be(&self, radix: u32) -> (Sign, Vec) {
(self.sign, self.data.to_radix_be(radix))
}
/// Returns the integer in the requested base in little-endian digit order.
/// The output is not given in a human readable alphabet but as a zero
/// based u8 number.
/// `radix` must be in the range `2...256`.
///
/// # Examples
///
/// ```
/// use num_bigint::{BigInt, Sign};
///
/// assert_eq!(BigInt::from(-0xFFFFi64).to_radix_le(159),
/// (Sign::Minus, vec![27, 94, 2]));
/// // 0xFFFF = 65535 = 27 + 94*159 + 2*(159^2)
/// ```
#[inline]
pub fn to_radix_le(&self, radix: u32) -> (Sign, Vec) {
(self.sign, self.data.to_radix_le(radix))
}
/// Returns the sign of the `BigInt` as a `Sign`.
///
/// # Examples
///
/// ```
/// use num_bigint::{BigInt, Sign};
/// use num_traits::Zero;
///
/// assert_eq!(BigInt::from(1234).sign(), Sign::Plus);
/// assert_eq!(BigInt::from(-4321).sign(), Sign::Minus);
/// assert_eq!(BigInt::zero().sign(), Sign::NoSign);
/// ```
#[inline]
pub fn sign(&self) -> Sign {
self.sign
}
/// Returns the magnitude of the `BigInt` as a `BigUint`.
///
/// # Examples
///
/// ```
/// use num_bigint::{BigInt, BigUint};
/// use num_traits::Zero;
///
/// assert_eq!(BigInt::from(1234).magnitude(), &BigUint::from(1234u32));
/// assert_eq!(BigInt::from(-4321).magnitude(), &BigUint::from(4321u32));
/// assert!(BigInt::zero().magnitude().is_zero());
/// ```
#[inline]
pub fn magnitude(&self) -> &BigUint {
&self.data
}
/// Convert this `BigInt` into its `Sign` and `BigUint` magnitude,
/// the reverse of `BigInt::from_biguint`.
///
/// # Examples
///
/// ```
/// use num_bigint::{BigInt, BigUint, Sign};
/// use num_traits::Zero;
///
/// assert_eq!(BigInt::from(1234).into_parts(), (Sign::Plus, BigUint::from(1234u32)));
/// assert_eq!(BigInt::from(-4321).into_parts(), (Sign::Minus, BigUint::from(4321u32)));
/// assert_eq!(BigInt::zero().into_parts(), (Sign::NoSign, BigUint::zero()));
/// ```
#[inline]
pub fn into_parts(self) -> (Sign, BigUint) {
(self.sign, self.data)
}
/// Determines the fewest bits necessary to express the `BigInt`,
/// not including the sign.
#[inline]
pub fn bits(&self) -> u64 {
self.data.bits()
}
/// Converts this `BigInt` into a `BigUint`, if it's not negative.
#[inline]
pub fn to_biguint(&self) -> Option {
match self.sign {
Plus => Some(self.data.clone()),
NoSign => Some(Zero::zero()),
Minus => None,
}
}
#[inline]
pub fn checked_add(&self, v: &BigInt) -> Option {
Some(self + v)
}
#[inline]
pub fn checked_sub(&self, v: &BigInt) -> Option {
Some(self - v)
}
#[inline]
pub fn checked_mul(&self, v: &BigInt) -> Option {
Some(self * v)
}
#[inline]
pub fn checked_div(&self, v: &BigInt) -> Option {
if v.is_zero() {
return None;
}
Some(self / v)
}
/// Returns `self ^ exponent`.
pub fn pow(&self, exponent: u32) -> Self {
Pow::pow(self, exponent)
}
/// Returns `(self ^ exponent) mod modulus`
///
/// Note that this rounds like `mod_floor`, not like the `%` operator,
/// which makes a difference when given a negative `self` or `modulus`.
/// The result will be in the interval `[0, modulus)` for `modulus > 0`,
/// or in the interval `(modulus, 0]` for `modulus < 0`
///
/// Panics if the exponent is negative or the modulus is zero.
pub fn modpow(&self, exponent: &Self, modulus: &Self) -> Self {
power::modpow(self, exponent, modulus)
}
/// Returns the truncated principal square root of `self` --
/// see [Roots::sqrt](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#method.sqrt).
pub fn sqrt(&self) -> Self {
Roots::sqrt(self)
}
/// Returns the truncated principal cube root of `self` --
/// see [Roots::cbrt](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#method.cbrt).
pub fn cbrt(&self) -> Self {
Roots::cbrt(self)
}
/// Returns the truncated principal `n`th root of `self` --
/// See [Roots::nth_root](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#tymethod.nth_root).
pub fn nth_root(&self, n: u32) -> Self {
Roots::nth_root(self, n)
}
/// Returns the number of least-significant bits that are zero,
/// or `None` if the entire number is zero.
pub fn trailing_zeros(&self) -> Option {
self.data.trailing_zeros()
}
/// Returns whether the bit in position `bit` is set,
/// using the two's complement for negative numbers
pub fn bit(&self, bit: u64) -> bool {
if self.is_negative() {
// Let the binary representation of a number be
// ... 0 x 1 0 ... 0
// Then the two's complement is
// ... 1 !x 1 0 ... 0
// where !x is obtained from x by flipping each bit
if bit >= u64::from(crate::big_digit::BITS) * self.len() as u64 {
true
} else {
let trailing_zeros = self.data.trailing_zeros().unwrap();
match Ord::cmp(&bit, &trailing_zeros) {
Ordering::Less => false,
Ordering::Equal => true,
Ordering::Greater => !self.data.bit(bit),
}
}
} else {
self.data.bit(bit)
}
}
/// Sets or clears the bit in the given position,
/// using the two's complement for negative numbers
///
/// Note that setting/clearing a bit (for positive/negative numbers,
/// respectively) greater than the current bit length, a reallocation
/// may be needed to store the new digits
pub fn set_bit(&mut self, bit: u64, value: bool) {
match self.sign {
Sign::Plus => self.data.set_bit(bit, value),
Sign::Minus => bits::set_negative_bit(self, bit, value),
Sign::NoSign => {
if value {
self.data.set_bit(bit, true);
self.sign = Sign::Plus;
} else {
// Clearing a bit for zero is a no-op
}
}
}
// The top bit may have been cleared, so normalize
self.normalize();
}
}
#[test]
fn test_from_biguint() {
fn check(inp_s: Sign, inp_n: usize, ans_s: Sign, ans_n: usize) {
let inp = BigInt::from_biguint(inp_s, BigUint::from(inp_n));
let ans = BigInt {
sign: ans_s,
data: BigUint::from(ans_n),
};
assert_eq!(inp, ans);
}
check(Plus, 1, Plus, 1);
check(Plus, 0, NoSign, 0);
check(Minus, 1, Minus, 1);
check(NoSign, 1, NoSign, 0);
}
#[test]
fn test_from_slice() {
fn check(inp_s: Sign, inp_n: u32, ans_s: Sign, ans_n: u32) {
let inp = BigInt::from_slice(inp_s, &[inp_n]);
let ans = BigInt {
sign: ans_s,
data: BigUint::from(ans_n),
};
assert_eq!(inp, ans);
}
check(Plus, 1, Plus, 1);
check(Plus, 0, NoSign, 0);
check(Minus, 1, Minus, 1);
check(NoSign, 1, NoSign, 0);
}
#[test]
fn test_assign_from_slice() {
fn check(inp_s: Sign, inp_n: u32, ans_s: Sign, ans_n: u32) {
let mut inp = BigInt::from_slice(Minus, &[2627_u32, 0_u32, 9182_u32, 42_u32]);
inp.assign_from_slice(inp_s, &[inp_n]);
let ans = BigInt {
sign: ans_s,
data: BigUint::from(ans_n),
};
assert_eq!(inp, ans);
}
check(Plus, 1, Plus, 1);
check(Plus, 0, NoSign, 0);
check(Minus, 1, Minus, 1);
check(NoSign, 1, NoSign, 0);
}
num-bigint-0.4.3/src/bigrand.rs 0000644 0000000 0000000 00000020445 00726746425 0014501 0 ustar 0000000 0000000 //! Randomization of big integers
use rand::distributions::uniform::{SampleBorrow, SampleUniform, UniformSampler};
use rand::prelude::*;
use crate::BigInt;
use crate::BigUint;
use crate::Sign::*;
use crate::biguint::biguint_from_vec;
use num_integer::Integer;
use num_traits::{ToPrimitive, Zero};
/// A trait for sampling random big integers.
///
/// The `rand` feature must be enabled to use this. See crate-level documentation for details.
pub trait RandBigInt {
/// Generate a random `BigUint` of the given bit size.
fn gen_biguint(&mut self, bit_size: u64) -> BigUint;
/// Generate a random BigInt of the given bit size.
fn gen_bigint(&mut self, bit_size: u64) -> 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;
}
fn gen_bits(rng: &mut R, data: &mut [u32], rem: u64) {
// `fill` is faster than many `gen::` calls
rng.fill(data);
if rem > 0 {
let last = data.len() - 1;
data[last] >>= 32 - rem;
}
}
impl RandBigInt for R {
#[cfg(not(u64_digit))]
fn gen_biguint(&mut self, bit_size: u64) -> BigUint {
let (digits, rem) = bit_size.div_rem(&32);
let len = (digits + (rem > 0) as u64)
.to_usize()
.expect("capacity overflow");
let mut data = vec![0u32; len];
gen_bits(self, &mut data, rem);
biguint_from_vec(data)
}
#[cfg(u64_digit)]
fn gen_biguint(&mut self, bit_size: u64) -> BigUint {
use core::slice;
let (digits, rem) = bit_size.div_rem(&32);
let len = (digits + (rem > 0) as u64)
.to_usize()
.expect("capacity overflow");
let native_digits = Integer::div_ceil(&bit_size, &64);
let native_len = native_digits.to_usize().expect("capacity overflow");
let mut data = vec![0u64; native_len];
unsafe {
// Generate bits in a `&mut [u32]` slice for value stability
let ptr = data.as_mut_ptr() as *mut u32;
debug_assert!(native_len * 2 >= len);
let data = slice::from_raw_parts_mut(ptr, len);
gen_bits(self, data, rem);
}
#[cfg(target_endian = "big")]
for digit in &mut data {
// swap u32 digits into u64 endianness
*digit = (*digit << 32) | (*digit >> 32);
}
biguint_from_vec(data)
}
fn gen_bigint(&mut self, bit_size: u64) -> BigInt {
loop {
// Generate a random BigUint...
let biguint = self.gen_biguint(bit_size);
// ...and then randomly assign it a Sign...
let sign = if biguint.is_zero() {
// ...except that if the BigUint is zero, we need to try
// again with probability 0.5. This is because otherwise,
// the probability of generating a zero BigInt would be
// double that of any other number.
if self.gen() {
continue;
} else {
NoSign
}
} else if self.gen() {
Plus
} else {
Minus
};
return BigInt::from_biguint(sign, biguint);
}
}
fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint {
assert!(!bound.is_zero());
let bits = bound.bits();
loop {
let n = self.gen_biguint(bits);
if n < *bound {
return n;
}
}
}
fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint {
assert!(*lbound < *ubound);
if lbound.is_zero() {
self.gen_biguint_below(ubound)
} else {
lbound + self.gen_biguint_below(&(ubound - lbound))
}
}
fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt {
assert!(*lbound < *ubound);
if lbound.is_zero() {
BigInt::from(self.gen_biguint_below(ubound.magnitude()))
} else if ubound.is_zero() {
lbound + BigInt::from(self.gen_biguint_below(lbound.magnitude()))
} else {
let delta = ubound - lbound;
lbound + BigInt::from(self.gen_biguint_below(delta.magnitude()))
}
}
}
/// The back-end implementing rand's `UniformSampler` for `BigUint`.
#[derive(Clone, Debug)]
pub struct UniformBigUint {
base: BigUint,
len: BigUint,
}
impl UniformSampler for UniformBigUint {
type X = BigUint;
#[inline]
fn new(low_b: B1, high_b: B2) -> Self
where
B1: SampleBorrow + Sized,
B2: SampleBorrow + 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(low_b: B1, high_b: B2) -> Self
where
B1: SampleBorrow + Sized,
B2: SampleBorrow + Sized,
{
let low = low_b.borrow();
let high = high_b.borrow();
assert!(low <= high);
Self::new(low, high + 1u32)
}
#[inline]
fn sample(&self, rng: &mut R) -> Self::X {
&self.base + rng.gen_biguint_below(&self.len)
}
#[inline]
fn sample_single(low: B1, high: B2, rng: &mut R) -> Self::X
where
B1: SampleBorrow + Sized,
B2: SampleBorrow + Sized,
{
rng.gen_biguint_range(low.borrow(), high.borrow())
}
}
impl SampleUniform for BigUint {
type Sampler = UniformBigUint;
}
/// The back-end implementing rand's `UniformSampler` for `BigInt`.
#[derive(Clone, Debug)]
pub struct UniformBigInt {
base: BigInt,
len: BigUint,
}
impl UniformSampler for UniformBigInt {
type X = BigInt;
#[inline]
fn new(low_b: B1, high_b: B2) -> Self
where
B1: SampleBorrow + Sized,
B2: SampleBorrow + Sized,
{
let low = low_b.borrow();
let high = high_b.borrow();
assert!(low < high);
UniformBigInt {
len: (high - low).into_parts().1,
base: low.clone(),
}
}
#[inline]
fn new_inclusive(low_b: B1, high_b: B2) -> Self
where
B1: SampleBorrow + Sized,
B2: SampleBorrow + Sized,
{
let low = low_b.borrow();
let high = high_b.borrow();
assert!(low <= high);
Self::new(low, high + 1u32)
}
#[inline]
fn sample(&self, rng: &mut R) -> Self::X {
&self.base + BigInt::from(rng.gen_biguint_below(&self.len))
}
#[inline]
fn sample_single(low: B1, high: B2, rng: &mut R) -> Self::X
where
B1: SampleBorrow + Sized,
B2: SampleBorrow + Sized,
{
rng.gen_bigint_range(low.borrow(), high.borrow())
}
}
impl SampleUniform for BigInt {
type Sampler = UniformBigInt;
}
/// A random distribution for `BigUint` and `BigInt` values of a particular bit size.
///
/// The `rand` feature must be enabled to use this. See crate-level documentation for details.
#[derive(Clone, Copy, Debug)]
pub struct RandomBits {
bits: u64,
}
impl RandomBits {
#[inline]
pub fn new(bits: u64) -> RandomBits {
RandomBits { bits }
}
}
impl Distribution for RandomBits {
#[inline]
fn sample(&self, rng: &mut R) -> BigUint {
rng.gen_biguint(self.bits)
}
}
impl Distribution for RandomBits {
#[inline]
fn sample(&self, rng: &mut R) -> BigInt {
rng.gen_bigint(self.bits)
}
}
num-bigint-0.4.3/src/biguint/addition.rs 0000644 0000000 0000000 00000015367 00726746425 0016336 0 ustar 0000000 0000000 #[cfg(not(u64_digit))]
use super::u32_from_u128;
use super::{BigUint, IntDigits};
use crate::big_digit::{self, BigDigit};
use crate::UsizePromotion;
use core::iter::Sum;
use core::ops::{Add, AddAssign};
use num_traits::{CheckedAdd, Zero};
#[cfg(all(use_addcarry, target_arch = "x86_64"))]
use core::arch::x86_64 as arch;
#[cfg(all(use_addcarry, target_arch = "x86"))]
use core::arch::x86 as arch;
// Add with carry:
#[cfg(all(use_addcarry, u64_digit))]
#[inline]
fn adc(carry: u8, a: u64, b: u64, out: &mut u64) -> u8 {
// Safety: There are absolutely no safety concerns with calling `_addcarry_u64`.
// It's just unsafe for API consistency with other intrinsics.
unsafe { arch::_addcarry_u64(carry, a, b, out) }
}
#[cfg(all(use_addcarry, not(u64_digit)))]
#[inline]
fn adc(carry: u8, a: u32, b: u32, out: &mut u32) -> u8 {
// Safety: There are absolutely no safety concerns with calling `_addcarry_u32`.
// It's just unsafe for API consistency with other intrinsics.
unsafe { arch::_addcarry_u32(carry, a, b, out) }
}
// fallback for environments where we don't have an addcarry intrinsic
#[cfg(not(use_addcarry))]
#[inline]
fn adc(carry: u8, a: BigDigit, b: BigDigit, out: &mut BigDigit) -> u8 {
use crate::big_digit::DoubleBigDigit;
let sum = DoubleBigDigit::from(a) + DoubleBigDigit::from(b) + DoubleBigDigit::from(carry);
*out = sum as BigDigit;
(sum >> big_digit::BITS) as u8
}
/// Two argument addition of raw slices, `a += b`, returning the carry.
///
/// This is used when the data `Vec` might need to resize to push a non-zero carry, so we perform
/// the addition first hoping that it will fit.
///
/// The caller _must_ ensure that `a` is at least as long as `b`.
#[inline]
pub(super) 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) {
carry = adc(carry, *a, *b, a);
}
if carry != 0 {
for a in a_hi {
carry = adc(carry, *a, 0, a);
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(super) fn add2(a: &mut [BigDigit], b: &[BigDigit]) {
let carry = __add2(a, b);
debug_assert!(carry == 0);
}
forward_all_binop_to_val_ref_commutative!(impl Add for BigUint, add);
forward_val_assign!(impl AddAssign for BigUint, add_assign);
impl<'a> Add<&'a BigUint> for BigUint {
type Output = BigUint;
fn add(mut self, other: &BigUint) -> BigUint {
self += other;
self
}
}
impl<'a> AddAssign<&'a BigUint> for BigUint {
#[inline]
fn add_assign(&mut self, other: &BigUint) {
let self_len = self.data.len();
let carry = if self_len < other.data.len() {
let lo_carry = __add2(&mut self.data[..], &other.data[..self_len]);
self.data.extend_from_slice(&other.data[self_len..]);
__add2(&mut self.data[self_len..], &[lo_carry])
} else {
__add2(&mut self.data[..], &other.data[..])
};
if carry != 0 {
self.data.push(carry);
}
}
}
promote_unsigned_scalars!(impl Add for BigUint, add);
promote_unsigned_scalars_assign!(impl AddAssign for BigUint, add_assign);
forward_all_scalar_binop_to_val_val_commutative!(impl Add for BigUint, add);
forward_all_scalar_binop_to_val_val_commutative!(impl Add for BigUint, add);
forward_all_scalar_binop_to_val_val_commutative!(impl Add for BigUint, add);
impl Add for BigUint {
type Output = BigUint;
#[inline]
fn add(mut self, other: u32) -> BigUint {
self += other;
self
}
}
impl AddAssign for BigUint {
#[inline]
fn add_assign(&mut self, other: u32) {
if other != 0 {
if self.data.is_empty() {
self.data.push(0);
}
let carry = __add2(&mut self.data, &[other as BigDigit]);
if carry != 0 {
self.data.push(carry);
}
}
}
}
impl Add for BigUint {
type Output = BigUint;
#[inline]
fn add(mut self, other: u64) -> BigUint {
self += other;
self
}
}
impl AddAssign for BigUint {
#[cfg(not(u64_digit))]
#[inline]
fn add_assign(&mut self, other: u64) {
let (hi, lo) = big_digit::from_doublebigdigit(other);
if hi == 0 {
*self += lo;
} else {
while self.data.len() < 2 {
self.data.push(0);
}
let carry = __add2(&mut self.data, &[lo, hi]);
if carry != 0 {
self.data.push(carry);
}
}
}
#[cfg(u64_digit)]
#[inline]
fn add_assign(&mut self, other: u64) {
if other != 0 {
if self.data.is_empty() {
self.data.push(0);
}
let carry = __add2(&mut self.data, &[other as BigDigit]);
if carry != 0 {
self.data.push(carry);
}
}
}
}
impl Add for BigUint {
type Output = BigUint;
#[inline]
fn add(mut self, other: u128) -> BigUint {
self += other;
self
}
}
impl AddAssign for BigUint {
#[cfg(not(u64_digit))]
#[inline]
fn add_assign(&mut self, other: u128) {
if other <= u128::from(u64::max_value()) {
*self += other as u64
} else {
let (a, b, c, d) = u32_from_u128(other);
let carry = if a > 0 {
while self.data.len() < 4 {
self.data.push(0);
}
__add2(&mut self.data, &[d, c, b, a])
} else {
debug_assert!(b > 0);
while self.data.len() < 3 {
self.data.push(0);
}
__add2(&mut self.data, &[d, c, b])
};
if carry != 0 {
self.data.push(carry);
}
}
}
#[cfg(u64_digit)]
#[inline]
fn add_assign(&mut self, other: u128) {
let (hi, lo) = big_digit::from_doublebigdigit(other);
if hi == 0 {
*self += lo;
} else {
while self.data.len() < 2 {
self.data.push(0);
}
let carry = __add2(&mut self.data, &[lo, hi]);
if carry != 0 {
self.data.push(carry);
}
}
}
}
impl CheckedAdd for BigUint {
#[inline]
fn checked_add(&self, v: &BigUint) -> Option {
Some(self.add(v))
}
}
impl_sum_iter_type!(BigUint);
num-bigint-0.4.3/src/biguint/arbitrary.rs 0000644 0000000 0000000 00000002016 00726746425 0016525 0 ustar 0000000 0000000 use super::{biguint_from_vec, BigUint};
use crate::big_digit::BigDigit;
#[cfg(feature = "quickcheck")]
use crate::std_alloc::Box;
use crate::std_alloc::Vec;
#[cfg(feature = "quickcheck")]
impl quickcheck::Arbitrary for BigUint {
fn arbitrary(g: &mut quickcheck::Gen) -> Self {
// Use arbitrary from Vec
biguint_from_vec(Vec::