extprim-1.7.1/.cargo_vcs_info.json0000644000000001121366450514500126330ustar00{ "git": { "sha1": "049d9bca2c38f62256e5133d42a25bba9176194d" } } extprim-1.7.1/Cargo.toml0000644000000032301366450514500106350ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "extprim" version = "1.7.1" authors = ["kennytm "] build = "build.rs" include = ["build.rs", "src/*.rs", "Cargo.toml", "README.md", "LICENSE*.txt"] description = "Extra primitive types (u128, i128)" documentation = "https://docs.rs/extprim" keywords = ["primitives", "u128", "i128"] categories = ["algorithms"] license = "MIT/Apache-2.0" repository = "https://github.com/kennytm/extprim" [dependencies.num-traits] version = "0.2" [dependencies.rand] version = "0.6" optional = true [dependencies.serde] version = "1" features = ["derive"] optional = true [dev-dependencies.extprim_literals] version = "2.0" [dev-dependencies.serde_derive] version = ">=1.0.0,<=1.0.98" [build-dependencies.rustc_version] version = "0.2" [build-dependencies.semver] version = "0.9" [features] default = ["use-std", "rand", "serde"] use-std = [] [badges.appveyor] repository = "kennytm/extprim" [badges.coveralls] repository = "kennytm/extprim" [badges.is-it-maintained-issue-resolution] repository = "kennytm/extprim" [badges.is-it-maintained-open-issues] repository = "kennytm/extprim" [badges.travis-ci] repository = "kennytm/extprim" extprim-1.7.1/Cargo.toml.orig000064400000000000000000000025561366240533400143030ustar0000000000000000[package] name = "extprim" version = "1.7.1" authors = ["kennytm "] description = "Extra primitive types (u128, i128)" repository = "https://github.com/kennytm/extprim" license = "MIT/Apache-2.0" keywords = ["primitives","u128","i128"] categories = ["algorithms"] documentation = "https://docs.rs/extprim" build = "build.rs" include = [ "build.rs", "src/*.rs", "Cargo.toml", "README.md", "LICENSE*.txt", ] [badges] travis-ci = { repository = "kennytm/extprim" } appveyor = { repository = "kennytm/extprim" } is-it-maintained-issue-resolution = { repository = "kennytm/extprim" } is-it-maintained-open-issues = { repository = "kennytm/extprim" } coveralls = { repository = "kennytm/extprim" } [workspace] members = ["extprim_literals", "extprim_literals_macros", "extprim_tests"] [dependencies] # note: upgrading to rand 0.7 requires 'dyn' support i.e. rust 1.27+ rand = { version = "0.6", optional = true } num-traits = "0.2" serde = { version = "1", optional = true, features = ["derive"] } [dev-dependencies] extprim_literals = { version = "2.0", path = "./extprim_literals" } # note: pin the version of serde_derive to 1.0.98 or below, # so we don't need to depend on proc-macro2 v1.0 serde_derive = ">=1.0.0,<=1.0.98" [build-dependencies] rustc_version = "0.2" semver = "0.9" [features] default = ["use-std", "rand", "serde"] use-std = [] extprim-1.7.1/LICENSE-APACHE.txt000064400000000000000000000261361356427720300141610ustar0000000000000000 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. extprim-1.7.1/LICENSE-MIT.txt000064400000000000000000000020341356427720300136600ustar0000000000000000Copyright (c) 2016 kennytm 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. extprim-1.7.1/README.md000064400000000000000000000046111356427720300126700ustar0000000000000000extprim ======= [![Travis (Linux and OS X) Build status](https://travis-ci.org/kennytm/extprim.svg?branch=master)](https://travis-ci.org/kennytm/extprim) [![AppVeyor (Windows) Build status](https://ci.appveyor.com/api/projects/status/59h8ugya24odwtgd/branch/master?svg=true)](https://ci.appveyor.com/project/kennytm/extprim/branch/master) [![Coverage Status](https://coveralls.io/repos/github/kennytm/extprim/badge.svg?branch=master)](https://coveralls.io/github/kennytm/extprim?branch=master) [![crates.io](http://meritbadge.herokuapp.com/extprim)](https://crates.io/crates/extprim) [![MIT / Apache 2.0](https://img.shields.io/badge/license-MIT%20%2f%20Apache%202.0-blue.svg)](./LICENSE-APACHE.txt) > *Thanks to [RFC 1504 “int128”](https://github.com/rust-lang/rfcs/blob/master/text/1504-int128.md), you can use `i128` > and `u128` directly on nightly Rust starting from 1.16. Using the built-in types are preferred.* Extra primitive types for stable Rust. Currently includes: * `u128` (unsigned 128-bit integers) * `i128` (signed 128-bit integers) [Documentation](https://docs.rs/extprim) You may also find other primitive types in other crates: * `u12` → [twelve_bit](https://crates.io/crates/twelve_bit) * `f16` → [half](https://crates.io/crates/half) * `d128` → [decimal](https://crates.io/crates/decimal) * `Complex` → [num-complex](https://crates.io/crates/num-complex) Usage ----- ```toml # Cargo.toml [dependencies] extprim = "1" ``` If you want to use the `u128!()` and `i128!()` macros, please include the `extprim_literals` plugin. ```toml # Cargo.toml [dependencies] extprim = "1" extprim_literals = "2" ``` Example ------- ```rust #[macro_use] extern crate extprim_literals; extern crate extprim; use std::str::FromStr; use extprim::i128::i128; fn main() { let a = i128::from_str("100000000000000000000000000000000000000").unwrap(); // convert string to u128 or i128 let b = i128::new(10).pow(38); // 64-bit integers can be directly new'ed assert_eq!(a, b); let c = i128::from_parts(5421010862427522170, 687399551400673280); // represent using the higher- and lower-64-bit parts let d = c - a; // standard operators like +, -, *, /, %, etc. work as expected. assert_eq!(d, i128::zero()); const e: i128 = i128!(100000000000000000000000000000000000000); // use the literal macros assert_eq!(a, e); } ``` extprim-1.7.1/build.rs000064400000000000000000000010041356427720300130470ustar0000000000000000extern crate rustc_version; extern crate semver; use rustc_version::{version_meta, Channel}; use semver::Version; pub fn main() { let version = version_meta().unwrap(); let channel = match version.channel { Channel::Dev | Channel::Nightly => "unstable", Channel::Beta | Channel::Stable => "stable", }; println!("cargo:rustc-cfg=extprim_channel=\"{}\"", channel); if version.semver >= Version::new(1, 26, 0) { println!("cargo:rustc-cfg=extprim_has_stable_i128"); } } extprim-1.7.1/src/compiler_rt.rs000064400000000000000000000063051356427720300150670ustar0000000000000000pub use self::detail::{udiv128, umod128, udivmod128}; #[cfg(extprim_has_stable_i128)] pub mod builtins { pub type I128 = i128; pub type U128 = u128; } #[cfg(all(target_pointer_width="64", unix))] mod detail { use u128::u128; use std::mem::uninitialized; // Prefer to use the C version if possible. Those should be more up-to-date. extern "C" { fn __udivti3(a: u128, b: u128) -> u128; fn __umodti3(a: u128, b: u128) -> u128; fn __udivmodti4(a: u128, b: u128, rem: *mut u128) -> u128; } pub fn udiv128(a: u128, b: u128) -> u128 { unsafe { __udivti3(a, b) } } pub fn umod128(a: u128, b: u128) -> u128 { unsafe { __umodti3(a, b) } } pub fn udivmod128(a: u128, b: u128) -> (u128, u128) { unsafe { let mut rem = uninitialized(); let div = __udivmodti4(a, b, &mut rem); (div, rem) } } } #[cfg(not(all(target_pointer_width="64", unix)))] mod detail { use u128::{u128, ZERO}; use std::mem::uninitialized; pub fn udiv128(a: u128, b: u128) -> u128 { udivmodti4(a, b, None) } pub fn umod128(a: u128, b: u128) -> u128 { udivmod128(a, b).1 } pub fn udivmod128(a: u128, b: u128) -> (u128, u128) { let mut rem = unsafe { uninitialized() }; let div = udivmodti4(a, b, Some(&mut rem)); (div, rem) } fn udivmodti4(n: u128, d: u128, rem: Option<&mut u128>) -> u128 { // Source is based on // http://llvm.org/klaus/compiler-rt/blob/master/lib/builtins/udivmodti4.c. // compiler-rt is an LLVM project. It is licensed in MIT and UIOSL. if n < d { rem.map(|r| { *r = n; }); return ZERO; } let sr = match (n.hi, n.lo, d.hi, d.lo) { (0, x, 0, y) => { rem.map(|r| { r.hi = 0; r.lo = x % y; }); return u128::new(x / y); }, (x, 0, y, 0) => { rem.map(|r| { r.hi = x % y; r.lo = 0; }); return u128::new(x / y); }, (_, _, dh, 0) if dh.is_power_of_two() => { rem.map(|r| { r.lo = n.lo; r.hi = n.hi & (dh - 1); }); return u128::new(n.hi >> dh.trailing_zeros()); }, (_, _, 0, dl) if dl.is_power_of_two() => { rem.map(|r| { r.lo = n.lo & (dl - 1); r.hi = 0; }); return n >> dl.trailing_zeros(); } _ => { d.leading_zeros() - n.leading_zeros() + 1 }, }; let mut q = n << (128 - sr); let mut r = n >> sr; let mut carry = 0; for _ in 0 .. sr { r = r << 1; r.lo |= q.hi >> 63; q = q << 1; q.lo |= carry; carry = 0; if r >= d { r = r - d; carry = 1; } } q = q << 1; q.lo |= carry; rem.map(|rp| { *rp = r; }); q } } extprim-1.7.1/src/error.rs000064400000000000000000000015751356427720300137050ustar0000000000000000use core::num::ParseIntError; use core::mem::transmute; pub fn invalid_digit() -> ParseIntError { unsafe { transmute(1u8) } } pub fn underflow() -> ParseIntError { unsafe { transmute(3u8) } } pub fn overflow() -> ParseIntError { unsafe { transmute(2u8) } } pub fn empty() -> ParseIntError { unsafe { transmute(0u8) } } pub fn is_overflow(e: &ParseIntError) -> bool { *e == overflow() } #[cfg(test)] mod tests { use error; #[test] fn test_local_parse_int_error_to_std() { assert_fmt_eq!("invalid digit found in string", 29, "{}", error::invalid_digit()); assert_fmt_eq!("cannot parse integer from empty string", 38, "{}", error::empty()); assert_fmt_eq!("number too large to fit in target type", 38, "{}", error::overflow()); assert_fmt_eq!("number too small to fit in target type", 38, "{}", error::underflow()); } } extprim-1.7.1/src/format_buffer.rs000064400000000000000000000025471356427720300153750ustar0000000000000000use std::fmt; use std::str::from_utf8_unchecked; /// An internal structure used to format numbers. This is not intended for general use, since /// irrelevant error checking is intentionally omitted. pub struct FormatBuffer<'a> { buffer: &'a mut [u8], len: usize, } impl<'a> FormatBuffer<'a> { pub fn new(buffer: &mut [u8]) -> FormatBuffer { FormatBuffer { buffer: buffer, len: 0, } } pub unsafe fn into_str(self) -> &'a str { from_utf8_unchecked(&self.buffer[.. self.len]) } } impl<'a> fmt::Write for FormatBuffer<'a> { fn write_str(&mut self, s: &str) -> fmt::Result { let bytes = s.as_bytes(); let new_len = self.len + bytes.len(); self.buffer[self.len .. new_len].copy_from_slice(bytes); self.len = new_len; Ok(()) } } #[cfg(test)] macro_rules! assert_fmt_eq { ($expected:expr, $max_len:expr, $($args:expr),*) => { { use ::std::fmt::Write; let mut buffer = [0u8; $max_len]; let mut buf = ::format_buffer::FormatBuffer::new(&mut buffer); write!(&mut buf, $($args),*).unwrap(); assert_eq!($expected, unsafe { buf.into_str() }); } } } #[test] fn test_format_buffer() { assert_fmt_eq!("001234", 6, "{:06}", 1234); assert_fmt_eq!("5678", 16, "{}{}{}", 5, 6, 78); } extprim-1.7.1/src/forward.rs000064400000000000000000000061241356427720300142130ustar0000000000000000macro_rules! forward_symmetric { ( $(#[$cattr:meta])* impl $tn:ident($name:ident, $cname:ident, $wname:ident, $oname:ident) for $target:ty ) => { forward_symmetric!( $(#[$cattr])* impl $tn<$target>($name, $cname, $wname, $oname) for $target ); }; ( $(#[$cattr:meta])* impl $tn:ident<$arg:ty>($name:ident, $cname:ident, $wname:ident, $oname:ident) for $target:ty ) => { forward_impl! { $(#[$cattr])* impl $tn< $arg; $arg { y => y }; Wrapping<$arg> { x => x.0 } > ($name, $cname, $wname, $oname) for $target, "arithmetic operation overflowed" } } } macro_rules! forward_shift { ( $(#[$cattr:meta])* impl $tn:ident($name:ident, $cname:ident, $wname:ident, $oname:ident) for $target:ty ) => { forward_impl! { $(#[$cattr])* impl $tn< u32; u8|u16|u32|u64|usize|i8|i16|i32|i64|isize { y => y.to_u32().unwrap_or_else(|| panic!("shift operation overflowed")) }; u32 { x => x } > ($name, $cname, $wname, $oname) for $target, "shift operation overflowed" } } } macro_rules! forward_assign { ($tn:ident($name:ident, $fwd:ident) for $target:ty) => { forward_assign!($tn<$target>($name, $fwd) for $target); }; ($tn:ident<$($targ:ty)|+>($name:ident, $fwd:ident) for $target:ty) => { $(impl $tn<$targ> for $target { fn $name(&mut self, other: $targ) { *self = self.$fwd(other); } })+ } } macro_rules! forward_impl { ( $(#[$cattr:meta])* impl $tn:ident< $arg:ty; $($targ:ty)|+ { $t:pat => $uncheck_cast:expr }; $wrarg:ty { $u:pat => $unwrap:expr } > ($name:ident, $cname:ident, $wname:ident, $oname:ident) for $target:ty, $emsg:expr ) => { impl $target { $(#[$cattr])* pub fn $cname(self, other: $arg) -> Option<$target> { match self.$oname(other) { (v, false) => Some(v), (_, true) => None, } } } $(impl $tn<$targ> for $target { type Output = Self; #[cfg(debug_assertions)] #[allow(unused_comparisons, overflowing_literals)] fn $name(self, other: $targ) -> Self { let other = match other { $t => $uncheck_cast, }; self.$cname(other).unwrap_or_else(|| panic!($emsg)) } #[cfg(not(debug_assertions))] fn $name(self, other: $targ) -> Self { self.$wname(match other { $t => $uncheck_cast }) } })+ impl $tn<$wrarg> for Wrapping<$target> { type Output = Self; fn $name(self, other: $wrarg) -> Self { match other { $u => Wrapping((self.0).$wname($unwrap)) } } } } } extprim-1.7.1/src/i128.rs000064400000000000000000002070621356427720300132360ustar0000000000000000//! Signed 128-bit integer. use std::cmp::Ordering; use std::fmt::{self, Write}; use std::iter::{Product, Sum}; use std::num::ParseIntError; use std::ops::*; use std::str::FromStr; #[cfg(feature="rand")] use rand::Rng; #[cfg(feature="rand")] use rand::distributions::{Standard, Distribution}; use num_traits::*; use error; use format_buffer::FormatBuffer; use traits::{ToExtraPrimitive, Wrapping}; use u128::u128; #[cfg(extprim_has_stable_i128)] use compiler_rt::builtins::{U128, I128}; //{{{ Structure /// Number of bits a signed 128-bit number occupies. pub const BITS: usize = 128; /// Number of bytes a signed 128-bit number occupies. pub const BYTES: usize = 16; /// The smallest signed 128-bit integer (`-170_141_183_460_469_231_731_687_303_715_884_105_728`). pub const MIN: i128 = i128(u128 { lo: 0, hi: 0x8000000000000000 }); /// The largest signed 128-bit integer (`170_141_183_460_469_231_731_687_303_715_884_105_727`). pub const MAX: i128 = i128(u128 { lo: !0, hi: 0x7fffffffffffffff }); /// The constant 0. pub const ZERO: i128 = i128(::u128::ZERO); /// The constant 1. pub const ONE: i128 = i128(::u128::ONE); /// An signed 128-bit number. #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Default, Copy, Clone, Hash, PartialEq, Eq)] #[repr(C)] #[allow(non_camel_case_types)] pub struct i128( #[doc(hidden)] pub u128, ); impl i128 { /// Constructs a new 128-bit integer from a 64-bit integer. #[cfg(extprim_channel="stable")] pub fn new(lo: i64) -> i128 { i128(u128 { lo: lo as u64, hi: (lo >> 63) as u64 }) } /// Constructs a new 128-bit integer from a 64-bit integer. #[cfg(extprim_channel="unstable")] pub const fn new(lo: i64) -> i128 { i128(u128 { lo: lo as u64, hi: (lo >> 63) as u64 }) } /// Constructs a new 128-bit integer from the built-in 128-bit integer. #[cfg(extprim_has_stable_i128)] #[cfg(extprim_channel="stable")] pub fn from_built_in(value: I128) -> i128 { i128(u128::from_built_in(value as U128)) } /// Constructs a new 128-bit integer from the built-in 128-bit integer. #[cfg(extprim_has_stable_i128)] #[cfg(extprim_channel="unstable")] pub const fn from_built_in(value: I128) -> i128 { i128(u128::from_built_in(value as U128)) } /// Constructs a new 128-bit integer from the high-64-bit and low-64-bit parts. /// /// The new integer can be considered as `hi * 2**64 + lo`. /// /// ``` /// use extprim::i128::i128; /// let number = i128::from_parts(-6692605943, 4362896299872285998); /// assert_eq!(format!("{}", number), "-123456789012345678901234567890"); /// // Note: -123456789012345678901234567890 = -6692605943 << 64 | 4362896299872285998 /// ``` #[cfg(extprim_channel="stable")] pub fn from_parts(hi: i64, lo: u64) -> i128 { i128(u128 { lo: lo, hi: hi as u64 }) } /// Constructs a new 128-bit integer from the high-64-bit and low-64-bit parts. /// /// The new integer can be considered as `hi * 2**64 + lo`. /// /// ``` /// use extprim::i128::i128; /// let number = i128::from_parts(-6692605943, 4362896299872285998); /// assert_eq!(format!("{}", number), "-123456789012345678901234567890"); /// // Note: -123456789012345678901234567890 = -6692605943 << 64 | 4362896299872285998 /// ``` #[cfg(extprim_channel="unstable")] pub const fn from_parts(hi: i64, lo: u64) -> i128 { i128(u128 { lo: lo, hi: hi as u64 }) } /// Fetch the lower-64-bit of the number. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// let number = i128::from_str_radix("-2ec6f5f523d047254447e8b26a3665", 16).unwrap(); /// assert_eq!(number.low64(), 0xdabbb8174d95c99bu64); /// ``` pub fn low64(self) -> u64 { self.0.lo } /// Fetch the higher-64-bit of the number. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// let number = i128::from_str_radix("-2ec6f5f523d047254447e8b26a3665", 16).unwrap(); /// assert_eq!(number.high64(), -0x2ec6f5f523d048i64); /// ``` pub fn high64(self) -> i64 { self.0.hi as i64 } /// Convert this number to unsigned with wrapping. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// use extprim::i128::i128; /// /// let a = u128::from_str_radix( "ffd1390a0adc2fb8dabbb8174d95c99b", 16).unwrap(); /// let b = i128::from_str_radix("-002ec6f5f523d047254447e8b26a3665", 16).unwrap(); /// assert_eq!(a.as_i128(), b); /// assert_eq!(b.as_u128(), a); /// ``` pub fn as_u128(self) -> u128 { self.0 } /// Converts this number to the built-in 128-bit integer type. #[cfg(extprim_has_stable_i128)] pub fn as_built_in(self) -> I128 { (self.high64() as I128) << 64 | self.low64() as I128 } } #[cfg(test)] mod structure_tests { use i128::i128; use std::i64; #[test] fn test_new() { assert_eq!(i128::from_parts(0, 66), i128::new(66)); assert_eq!(i128::from_parts(-1, !65), i128::new(-66)); assert_eq!(i128::from_parts(-1, 0x8000000000000000), i128::new(i64::MIN)); } } //}}} //{{{ Rand #[cfg(feature="rand")] impl Distribution for Standard { fn sample(&self, rng: &mut R) -> i128 { i128(self.sample(rng)) } } //}}} //{{{ Add, Sub impl i128 { /// Wrapping (modular) addition. Computes `self + other`, wrapping around at the boundary of /// the type. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(5).wrapping_add(i128::new(-6)), i128::new(-1)); /// assert_eq!(i128::max_value().wrapping_add(i128::one()), i128::min_value()); /// ``` pub fn wrapping_add(self, other: i128) -> i128 { i128(self.0.wrapping_add(other.0)) } /// Wrapping (modular) subtraction. Computes `self - other`, wrapping around at the boundary of /// the type. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(6).wrapping_sub(i128::new(13)), i128::new(-7)); /// assert_eq!(i128::min_value().wrapping_sub(i128::one()), i128::max_value()); /// ``` pub fn wrapping_sub(self, other: i128) -> i128 { i128(self.0.wrapping_sub(other.0)) } /// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary of the type. /// /// The only case where such wrapping can occur is when one negates MIN on a signed type (where /// MIN is the negative minimal value for the type); this is a positive value that is too large /// to represent in the type. In such a case, this function returns MIN itself. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(7).wrapping_neg(), i128::new(-7)); /// assert_eq!(i128::min_value().wrapping_neg(), i128::min_value()); /// ``` pub fn wrapping_neg(self) -> i128 { i128(self.0.wrapping_neg()) } /// Calculates `self + other`. /// /// Returns a tuple of the addition along with a boolean indicating whether an arithmetic /// overflow would occur. If an overflow would have occurred then the wrapped value is /// returned. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(6).overflowing_add(i128::new(13)), (i128::new(19), false)); /// assert_eq!(i128::max_value().overflowing_add(i128::one()), (i128::min_value(), true)); /// ``` pub fn overflowing_add(self, other: i128) -> (i128, bool) { let left_sign = self.is_negative(); let right_sign = other.is_negative(); let res = self.wrapping_add(other); let res_sign = res.is_negative(); (res, left_sign == right_sign && res_sign != left_sign) } /// Calculates `self - other`. /// /// Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic /// overflow would occur. If an overflow would have occurred then the wrapped value is /// returned. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(3).overflowing_sub(i128::new(8)), (i128::new(-5), false)); /// assert_eq!(i128::min_value().overflowing_sub(i128::max_value()), (i128::one(), true)); /// ``` pub fn overflowing_sub(self, other: i128) -> (i128, bool) { let left_sign = self.is_negative(); let right_sign = other.is_negative(); let res = self.wrapping_sub(other); let res_sign = res.is_negative(); (res, left_sign != right_sign && res_sign != left_sign) } /// Negates `self`, overflowing if this is equal to the minimum value. /// /// Returns a tuple of the negated version of self along with a boolean indicating whether an /// overflow happened. If self is the minimum value (`i128::MIN`), then the minimum value will /// be returned again and true will be returned for an overflow happening. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(7).overflowing_neg(), (i128::new(-7), false)); /// assert_eq!(i128::min_value().overflowing_neg(), (i128::min_value(), true)); /// ``` pub fn overflowing_neg(self) -> (i128, bool) { (self.wrapping_neg(), self == MIN) } /// Checked negation. Computes `-self`, returning `None` if `self == MIN`. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(7).checked_neg(), Some(i128::new(-7))); /// assert_eq!(i128::min_value().checked_neg(), None); /// ``` pub fn checked_neg(self) -> Option { match self.overflowing_neg() { (v, false) => Some(v), (_, true) => None, } } /// Saturating integer addition. Computes `self + other`, saturating at the numeric bounds /// instead of overflowing. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(6).saturating_add(i128::new(13)), i128::new(19)); /// assert_eq!(i128::max_value().saturating_add(i128::new(2)), i128::max_value()); /// assert_eq!(i128::min_value().saturating_add(i128::new(-2)), i128::min_value()); /// ``` pub fn saturating_add(self, other: i128) -> i128 { self.checked_add(other) .unwrap_or_else(|| if other.is_negative() { MIN } else { MAX }) } /// Saturating integer subtraction. Computes `self - other`, saturating at the numeric bounds /// instead of overflowing. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(3).saturating_sub(i128::new(8)), i128::new(-5)); /// assert_eq!(i128::max_value().saturating_sub(i128::new(-2)), i128::max_value()); /// assert_eq!(i128::min_value().saturating_sub(i128::new(2)), i128::min_value()); /// ``` pub fn saturating_sub(self, other: i128) -> i128 { self.checked_sub(other) .unwrap_or_else(|| if other.is_negative() { MAX } else { MIN }) } /// Saturating integer negation. Computes `-self`, saturating at numeric bounds instead of /// overflowing. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(7).saturating_neg(), i128::new(-7)); /// assert_eq!(i128::min_value().saturating_neg(), i128::max_value()); /// assert_eq!(i128::max_value().saturating_neg(), i128::min_value() + i128::one()); /// ``` pub fn saturating_neg(self) -> i128 { self.checked_neg().unwrap_or(MAX) } } forward_symmetric! { /// Checked integer addition. Computes `self + other`, returning `None` if overflow occurred. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(5).checked_add(i128::new(-6)), Some(i128::new(-1))); /// assert_eq!(i128::max_value().checked_add(i128::one()), None); /// ``` impl Add(add, checked_add, wrapping_add, overflowing_add) for i128 } forward_symmetric! { /// Checked integer subtraction. Computes `self - other`, returning `None` if underflow /// occurred. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(6).checked_sub(i128::new(13)), Some(i128::new(-7))); /// assert_eq!(i128::min_value().checked_sub(i128::one()), None); /// ``` impl Sub(sub, checked_sub, wrapping_sub, overflowing_sub) for i128 } forward_assign!(AddAssign(add_assign, add) for i128); forward_assign!(SubAssign(sub_assign, sub) for i128); impl Neg for i128 { type Output = Self; fn neg(self) -> Self { self.checked_neg().unwrap_or_else(|| panic!("arithmetic operation overflowed")) } } impl Neg for Wrapping { type Output = Self; fn neg(self) -> Self { Wrapping(self.0.wrapping_neg()) } } impl CheckedAdd for i128 { fn checked_add(&self, other: &Self) -> Option { Self::checked_add(*self, *other) } } impl CheckedSub for i128 { fn checked_sub(&self, other: &Self) -> Option { Self::checked_sub(*self, *other) } } impl Saturating for i128 { fn saturating_add(self, other: Self) -> Self { Self::saturating_add(self, other) } fn saturating_sub(self, other: Self) -> Self { Self::saturating_add(self, other) } } #[cfg(test)] mod add_sub_tests { use i128::{i128, ONE, MAX, MIN}; #[test] fn test_add() { assert_eq!(i128::from_parts(23, 12) + i128::from_parts(78, 45), i128::from_parts(101, 57)); assert_eq!(i128::from_parts(-0x0151b4d672066e52, 0x21b6c7c3766908a7) + i128::from_parts(0x08a45eef16781327, 0xff1049ddf49ff8a8), i128::from_parts(0x0752aa18a471a4d6, 0x20c711a16b09014f)); } #[test] #[should_panic(expected="arithmetic operation overflowed")] fn test_add_overflow_above() { let _ = MAX + ONE; } #[test] #[should_panic(expected="arithmetic operation overflowed")] fn test_add_overflow_below() { let _ = MIN + i128::from_parts(-1, !0); } #[test] fn test_sub() { assert_eq!(i128::from_parts(78, 45) - i128::from_parts(23, 12), i128::from_parts(55, 33)); assert_eq!(i128::from_parts(23, 12) - i128::from_parts(78, 45), i128::from_parts(-56, !32)); assert_eq!(i128::from_parts(-0x0151b4d672066e52, 0x21b6c7c3766908a7) - i128::from_parts(0x08a45eef16781327, 0xff1049ddf49ff8a8), i128::from_parts(-0x09f613c5887e817a, 0x22a67de581c90fff)); assert_eq!(i128::from_parts(3565142335064920496, 15687467940602204387) - i128::from_parts(4442421226426414073, 17275749316209243331), i128::from_parts(-877278891361493578, 16858462698102512672)); } #[test] #[should_panic(expected="arithmetic operation overflowed")] fn test_sub_overflow_above() { let _ = MAX - i128::from_parts(-1, !0); } #[test] #[should_panic(expected="arithmetic operation overflowed")] fn test_sub_overflow_below() { let _ = MIN - ONE; } #[test] #[should_panic(expected="arithmetic operation overflowed")] fn test_neg_min() { let _ = -MIN; } #[test] fn test_neg() { let neg1 = i128::from_parts(-1, !0); assert_eq!(neg1, -ONE); assert_eq!(ONE, -neg1); assert_eq!(MIN.wrapping_neg(), MIN); assert_eq!(MIN.overflowing_neg(), (MIN, true)); assert_eq!(MIN.saturating_neg(), MAX); assert_eq!(MIN.checked_neg(), None); } } //}}} //{{{ PartialOrd, Ord impl PartialOrd for i128 { fn partial_cmp(&self, other: &i128) -> Option { Some(self.cmp(other)) } } impl Ord for i128 { fn cmp(&self, other: &i128) -> Ordering { (self.high64(), self.low64()).cmp(&(other.high64(), other.low64())) } } #[cfg(test)] mod cmp_tests { use i128::{i128, MIN, MAX}; use u128::u128; const TEST_CASES: &'static [i128; 7] = &[ MIN, i128(u128 { lo: 0, hi: !0 }), i128(u128 { lo: !0, hi: !0 }), i128(u128 { lo: 0, hi: 0 }), i128(u128 { lo: 1, hi: 0 }), i128(u128 { lo: 0, hi: 1 }), MAX ]; #[test] fn test_ord() { for (i, a) in TEST_CASES.iter().enumerate() { for (j, b) in TEST_CASES.iter().enumerate() { assert_eq!(i.cmp(&j), a.cmp(b)); } } } } //}}} //{{{ Not, BitAnd, BitOr, BitXor impl Not for i128 { type Output = Self; fn not(self) -> Self { i128(!self.0) } } impl BitAnd for i128 { type Output = Self; fn bitand(self, other: Self) -> Self { i128(self.0 & other.0) } } impl BitOr for i128 { type Output = Self; fn bitor(self, other: Self) -> Self { i128(self.0 | other.0) } } impl BitXor for i128 { type Output = Self; fn bitxor(self, other: Self) -> Self { i128(self.0 ^ other.0) } } impl Not for Wrapping { type Output = Self; fn not(self) -> Self { Wrapping(!self.0) } } impl BitAnd for Wrapping { type Output = Self; fn bitand(self, other: Self) -> Self { Wrapping(self.0 & other.0) } } impl BitOr for Wrapping { type Output = Self; fn bitor(self, other: Self) -> Self { Wrapping(self.0 | other.0) } } impl BitXor for Wrapping { type Output = Self; fn bitxor(self, other: Self) -> Self { Wrapping(self.0 ^ other.0) } } forward_assign!(BitAndAssign(bitand_assign, bitand) for i128); forward_assign!(BitOrAssign(bitor_assign, bitor) for i128); forward_assign!(BitXorAssign(bitxor_assign, bitxor) for i128); #[cfg(test)] mod bitwise_tests { use i128::i128; #[test] fn test_not() { assert_eq!(i128::from_parts(0x491d3b2d80d706a6, 0x1eb41c5d2ad1a379), !i128::from_parts(-0x491d3b2d80d706a7, 0xe14be3a2d52e5c86)); } #[test] fn test_bit_and() { assert_eq!(i128::from_parts(-0x75007aa6237d556f, 0x8bbf525fb0c5cd79) & i128::from_parts(-0x7231336af452490f, 0xb26ab6ca714bce40), i128::from_parts(-0x77317beef77f5d6f, 0x822a124a3041cc40)); } #[test] fn test_bit_or() { assert_eq!(i128::from_parts(-0x1c481f51e1707415, 0x5c76dd080dd43e30) | i128::from_parts(0x35591b16599e2ece, 0x2e2957ca426d7b07), i128::from_parts(-0x8000441a0605011, 0x7e7fdfca4ffd7f37)); } #[test] fn test_bit_xor() { assert_eq!(i128::from_parts(0x50b17617e8f6ee49, 0x1b06f037a9187c71) ^ i128::from_parts(0x206f313ea29823bd, 0x66e0bc7aa198785a), i128::from_parts(0x70de47294a6ecdf4, 0x7de64c4d0880042b)); } } //}}} //{{{ Shl, Shr impl i128 { /// Panic-free bitwise shift-left; yields `self << (shift % 128)`. /// /// Note that this is not the same as a rotate-left; the RHS of a wrapping shift-left is /// restricted to the range of the type, rather than the bits shifted out of the LHS being /// returned to the other end. The primitive integer types all implement a `rotate_left` /// function, which may be what you want instead. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(1).wrapping_shl(127), i128::min_value()); /// assert_eq!(i128::new(19).wrapping_shl(256), i128::new(19)); /// ``` pub fn wrapping_shl(self, shift: u32) -> i128 { i128(self.0.wrapping_shl(shift)) } /// Panic-free bitwise shift-right; yields `self >> (shift % 128). /// /// Note that this is not the same as a rotate-right; the RHS of a wrapping shift-right is /// restricted to the range of the type, rather than the bits shifted out of the LHS being /// returned to the other end. The primitive integer types all implement a `rotate_right` /// function, which may be what you want instead. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(-50).wrapping_shr(2), i128::new(-13)); /// assert_eq!(i128::new(19).wrapping_shr(257), i128::new(9)); /// ``` pub fn wrapping_shr(self, shift: u32) -> i128 { let hi = self.high64(); let lo = self.low64(); let (hi, lo) = if (shift & 64) != 0 { (hi >> 63, (hi >> (shift & 63)) as u64) } else { let new_hi = hi.wrapping_shr(shift); let mut new_lo = lo.wrapping_shr(shift); if (shift & 127) != 0 { new_lo |= (hi as u64).wrapping_shl(64u32.wrapping_sub(shift)); } (new_hi, new_lo) }; i128::from_parts(hi, lo) } /// Shifts `self` left by `other` bits. /// /// Returns a tuple of the shifted version of self along with a boolean indicating whether the /// shift value was larger than or equal to the number of bits. If the shift value is too /// large, then value is masked by `0x7f`, and this value is then used to perform the shift. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(1).overflowing_shl(127), (i128::min_value(), false)); /// assert_eq!(i128::new(19).overflowing_shl(256), (i128::new(19), true)); /// ``` pub fn overflowing_shl(self, other: u32) -> (i128, bool) { (self.wrapping_shl(other), other >= 128) } /// Shifts `self` right by `other` bits. /// /// Returns a tuple of the shifted version of self along with a boolean indicating whether the /// shift value was larger than or equal to the number of bits. If the shift value is too /// large, then value is masked by `0x7f`, and this value is then used to perform the shift. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(-50).overflowing_shr(2), (i128::new(-13), false)); /// assert_eq!(i128::new(19).overflowing_shr(257), (i128::new(9), true)); /// ``` pub fn overflowing_shr(self, other: u32) -> (i128, bool) { (self.wrapping_shr(other), other >= 128) } } forward_shift!( /// Checked shift left. Computes `self << other`, returning `None` if rhs is larger than or /// equal to the number of bits in `self` (128). /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(1).checked_shl(127), Some(i128::min_value())); /// assert_eq!(i128::new(19).checked_shl(256), None); /// ``` impl Shl(shl, checked_shl, wrapping_shl, overflowing_shl) for i128 ); forward_shift!( /// Checked shift right. Computes `self >> other`, returning `None` if the shift is larger than /// or equal to the number of bits in `self` (128). /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(-50).checked_shr(2), Some(i128::new(-13))); /// assert_eq!(i128::new(19).checked_shr(257), None); /// ``` impl Shr(shr, checked_shr, wrapping_shr, overflowing_shr) for i128 ); forward_assign!(ShlAssign(shl_assign, shl) for i128); forward_assign!(ShrAssign(shr_assign, shr) for i128); #[cfg(test)] mod shift_tests { use i128::i128; #[test] fn test_shl() { assert_eq!(i128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152) << 0, i128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152)); assert_eq!(i128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152) << 1, i128::from_parts(0x3cb8f00361caebee, 0xa7e13b58b651e2a4)); assert_eq!(i128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152) << 64, i128::from_parts(0x53f09dac5b28f152, 0x0)); assert_eq!(i128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152) << 120, i128::from_parts(0x5200000000000000, 0x0)); assert_eq!(i128::from_parts(-0x7fdac9c2232ae28, 0x509d78e4a3008bcd) << 0, i128::from_parts(-0x7fdac9c2232ae28, 0x509d78e4a3008bcd)); assert_eq!(i128::from_parts(-0x7fdac9c2232ae28, 0x509d78e4a3008bcd) << 1, i128::from_parts(-0xffb593844655c50, 0xa13af1c94601179a)); assert_eq!(i128::from_parts(-0x7fdac9c2232ae28, 0x509d78e4a3008bcd) << 64, i128::from_parts(0x509d78e4a3008bcd, 0x0)); assert_eq!(i128::from_parts(-0x7fdac9c2232ae28, 0x509d78e4a3008bcd) << 120, i128::from_parts(-0x3300000000000000, 0x0)); } #[test] fn test_shr() { assert_eq!(i128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152) >> 0, i128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152)); assert_eq!(i128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152) >> 1, i128::from_parts(0x0f2e3c00d872bafb, 0xa9f84ed62d9478a9)); assert_eq!(i128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152) >> 64, i128::from_parts(0x0, 0x1e5c7801b0e575f7)); assert_eq!(i128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152) >> 120, i128::from_parts(0x0, 0x1e)); assert_eq!(i128::from_parts(-0x7fdac9c2232ae28, 0x509d78e4a3008bcd) >> 0, i128::from_parts(-0x7fdac9c2232ae28, 0x509d78e4a3008bcd)); assert_eq!(i128::from_parts(-0x7fdac9c2232ae28, 0x509d78e4a3008bcd) >> 1, i128::from_parts(-0x3fed64e11195714, 0x284ebc72518045e6)); assert_eq!(i128::from_parts(-0x7fdac9c2232ae28, 0x509d78e4a3008bcd) >> 64, i128::from_parts(-1, 0xf8025363ddcd51d8)); assert_eq!(i128::from_parts(-0x7fdac9c2232ae28, 0x509d78e4a3008bcd) >> 120, i128::from_parts(-1, 0xfffffffffffffff8)); } } #[cfg(all(test, extprim_channel="unstable"))] mod shift_bench { use i128::i128; use test::{Bencher, black_box}; // randomize shift range to avoid possible branch prediction effect. const BENCH_SHIFTS: &'static [u32] = &[ 77, 45, 57, 7, 34, 75, 38, 89, 89, 66, 16, 111, 66, 123, 14, 80, 94, 43, 46, 86, 121, 31, 123, 33, 23, 57, 50, 28, 26, 46, 8, 88, 74, 55, 108, 127, 1, 70, 73, 2, 1, 45, 36, 96, 124, 124, 91, 63, 25, 94, 8, 68, 41, 127, 107, 10, 111, 98, 97, 72, 78, 10, 125, 17, 62, 3, 65, 67, 13, 41, 68, 109, 23, 100, 98, 16, 78, 13, 0, 63, 107, 64, 13, 23, 69, 73, 2, 38, 16, 9, 124, 120, 39, 119, 3, 15, 25, 11, 84, 102, 69, 58, 39, 116, 66, 87, 111, 17, 11, 29, 35, 123, 23, 38, 43, 85, 32, 7, 34, 84, 27, 35, 122, 64, 33, 83, 78, 105, 31, 5, 58, 25, 21, 34, 15, 94, 10, 23, 48, 89, 23, 99, 110, 105, 32, 7, 116, 31, 10, 14, 22, 84, 40, 57, 7, 35, 8, 95, 121, 66, 95, 103, 26, 62, 24, 36, 48, 58, 122, 66, 37, 56, 35, 87, 36, 41, 75, 37, 25, 40, 60, 39, 94, 18, 33, 113, 34, 66, 34, 34, 88, 95, 81, 115, 10, 67, 33, 34, 23, 53, 10, 119, 54, 107, 37, 17, 85, 42, 83, 85, 102, 104, 94, 24, 97, 104, 93, 9, 95, 75, 41, 112, 64, 63, 72, 3, 26, 65, 103, 88, 121, 105, 98, 82, 89, 30, 37, 64, 68, 41, 93, 57, 105, 100, 108, 102, 44, 17, 61, 72, 33, 126, 73, 105, 0, 119, 97, 28, 9, 101, 44, ]; #[bench] fn bench_shr(bencher: &mut Bencher) { let number = i128::from_parts(-8704825901651121218, 3937562729638942691); bencher.iter(|| { for i in BENCH_SHIFTS { black_box(number.wrapping_shr(*i)); } }); } } //}}} //{{{ Mul /// Converts a signed integer `x` into the sign (whether it is negative) and the absolute value /// `|x|`. fn sign_abs(x: i128) -> (bool, u128) { if x.is_negative() { (true, x.0.wrapping_neg()) } else { (false, x.0) } } /// Reassembles a sign and absolute value back to a signed integer. fn from_sign_abs(sign: bool, abs: u128) -> i128 { i128(if sign { abs.wrapping_neg() } else { abs }) } impl i128 { /// Calculates the multiplication of `self` and `other`. /// /// Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic /// overflow would occur. If an overflow would have occurred then the wrapped value is returned. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(-6).overflowing_mul(i128::new(11)), (i128::new(-66), false)); /// /// let a = i128::from_parts(3, 1); /// let b = i128::from_parts(-1, 3); /// assert_eq!(a.overflowing_mul(b), (i128::from_parts(8, 3), true)); /// ``` pub fn overflowing_mul(self, other: i128) -> (i128, bool) { if self == ZERO || other == ZERO { return (ZERO, false); } let (sa, a) = sign_abs(self); let (sb, b) = sign_abs(other); let res_is_neg = sa != sb; let (res, res_overflow) = a.overflowing_mul(b); let res = from_sign_abs(res_is_neg, res); (res, res_overflow || res.is_negative() != res_is_neg) } /// Wrapping (modular) multiplication. Computes `self * other`, wrapping around at the boundary /// of the type. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(-6).wrapping_mul(i128::new(11)), i128::new(-66)); /// /// let a = i128::from_parts(3, 1); /// let b = i128::from_parts(-1, 3); /// assert_eq!(a.wrapping_mul(b), i128::from_parts(8, 3)); /// ``` pub fn wrapping_mul(self, other: i128) -> i128 { i128(self.0.wrapping_mul(other.0)) } /// Saturating integer multiplication. Computes `self * other`, saturating at the numeric /// bounds instead of overflowing. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(-6).saturating_mul(i128::new(11)), i128::new(-66)); /// /// let a = i128::from_parts(3, 1); /// let b = i128::from_parts(-1, 3); /// assert_eq!(a.saturating_mul(b), i128::min_value()); /// ``` pub fn saturating_mul(self, other: i128) -> i128 { self.checked_mul(other).unwrap_or_else(|| { if self.is_negative() == other.is_negative() { MAX } else { MIN } }) } } forward_symmetric! { /// Checked integer multiplication. Computes `self * other`, returning `None` if underflow or /// overflow occurred. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(-6).checked_mul(i128::new(11)), Some(i128::new(-66))); /// /// let a = i128::from_parts(3, 1); /// let b = i128::from_parts(-1, 3); /// assert_eq!(a.checked_mul(b), None); /// ``` impl Mul(mul, checked_mul, wrapping_mul, overflowing_mul) for i128 } forward_assign!(MulAssign(mul_assign, mul) for i128); impl CheckedMul for i128 { fn checked_mul(&self, other: &Self) -> Option { Self::checked_mul(*self, *other) } } #[cfg(test)] mod mul_tests { use i128::{i128, ONE, MAX, MIN}; #[test] fn test_mul() { assert_eq!(i128::new(6263979403966582069) * i128::new(2263184174907185431), i128::from_parts(0xaaa4d56f5b2f577, 0x916fb81166049cc3)); assert_eq!(ONE * ONE, ONE); assert_eq!(ONE * MAX, MAX); assert_eq!(MIN * ONE, MIN); assert_eq!(i128::new(-4) * i128::new(-9), i128::new(36)); assert_eq!(i128::new(-7) * i128::new(3), i128::new(-21)); assert_eq!(i128::from_parts(1, 1) * i128::new(-9), i128::from_parts(-10, !8)); assert_eq!(i128::from_parts(0x4000_0000_0000_0000, 0) * i128::new(-2), MIN); } #[test] fn test_wrapping_overflowing_mul() { let a = i128::from_parts(-6140994497999405230, 2270645839074617067); let b = i128::from_parts(8696394550295834000, 13800979035109902541); let c = i128::from_parts(-6771355848177145191, 5110157532910617135); assert_eq!(a.wrapping_mul(b), c); assert_eq!(a.overflowing_mul(b), (c, true)); assert_eq!(a.checked_mul(b), None); assert_eq!(a.saturating_mul(b), MIN); assert_eq!(i128::new(-1).wrapping_mul(i128::new(-1)), ONE); assert_eq!(i128::new(-1).overflowing_mul(i128::new(-1)), (ONE, false)); assert_eq!(i128::new(-1).checked_mul(i128::new(-1)), Some(ONE)); assert_eq!(i128::new(-1).saturating_mul(i128::new(-1)), ONE); assert_eq!(MAX.wrapping_mul(i128::new(2)), i128::from_parts(-1, !1)); assert_eq!(MAX.overflowing_mul(i128::new(2)), (i128::from_parts(-1, !1), true)); assert_eq!(MAX.checked_mul(i128::new(2)), None); assert_eq!(MAX.saturating_mul(i128::new(2)), MAX); } } //}}} //{{{ Div, Rem impl i128 { /// Wrapping (modular) division. Computes `self / other`, wrapping around at the boundary of /// the type. /// /// The only case where such wrapping can occur is when one divides `MIN / -1`; this is /// equivalent to `-MIN`, a positive value that is too large to represent in the type. In such /// a case, this function returns `MIN` itself. /// /// # Panics /// /// This function will panic if `other` is 0. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(100).wrapping_div(i128::new(-8)), i128::new(-12)); /// assert_eq!(i128::min_value().wrapping_div(i128::new(-1)), i128::min_value()); /// ``` pub fn wrapping_div(self, other: i128) -> i128 { let (sa, a) = sign_abs(self); let (sb, b) = sign_abs(other); let res = a.wrapping_div(b); from_sign_abs(sa != sb, res) } /// Wrapping (modular) remainder. Computes `self % other`, wrapping around at the boundary of /// the type. /// /// Such wrap-around never actually occurs mathematically; implementation artifacts make /// `x % y` invalid for `MIN / -1` on a signed type. In such a case, this function returns 0. /// /// # Panics /// /// This function will panic if `other` is 0. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(100).wrapping_rem(i128::new(-8)), i128::new(4)); /// assert_eq!(i128::min_value().wrapping_rem(i128::new(-1)), i128::zero()); /// ``` pub fn wrapping_rem(self, other: i128) -> i128 { let (sa, a) = sign_abs(self); let (_, b) = sign_abs(other); let res = a.wrapping_rem(b); from_sign_abs(sa, res) } /// Calculates the divisor when `self` is divided by `other`. /// /// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic /// overflow would occur. If an overflow would occur then self is returned. /// /// # Panics /// /// This function will panic if `other` is 0. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(100).overflowing_div(i128::new(-8)), (i128::new(-12), false)); /// assert_eq!(i128::min_value().overflowing_div(i128::new(-1)), (i128::min_value(), true)); /// ``` pub fn overflowing_div(self, other: i128) -> (i128, bool) { if self == MIN && other == -ONE { (MIN, true) } else { (self.wrapping_div(other), false) } } /// Calculates the remainder when `self` is divided by `other`. /// /// Returns a tuple of the remainder after dividing along with a boolean indicating whether an /// arithmetic overflow would occur. If an overflow would occur then 0 is returned. /// /// # Panics /// /// This function will panic if `other` is 0. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(100).overflowing_rem(i128::new(-8)), (i128::new(4), false)); /// assert_eq!(i128::min_value().overflowing_rem(i128::new(-1)), (i128::zero(), true)); /// ``` pub fn overflowing_rem(self, other: i128) -> (i128, bool) { if self == MIN && other == -ONE { (ZERO, true) } else { (self.wrapping_rem(other), false) } } /// Checked integer division. Computes `self / other`, returning `None` if `other == 0` or the /// operation results in underflow or overflow. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(100).checked_div(i128::new(-8)), Some(i128::new(-12))); /// assert_eq!(i128::min_value().checked_div(i128::new(-1)), None); /// assert_eq!(i128::new(3).checked_div(i128::zero()), None); /// ``` pub fn checked_div(self, other: i128) -> Option { if other == ZERO || self == MIN && other == -ONE { None } else { Some(self.wrapping_div(other)) } } /// Checked integer remainder. Computes `self % other`, returning `None` if `other == 0` or the /// operation results in underflow or overflow. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(100).checked_rem(i128::new(-8)), Some(i128::new(4))); /// assert_eq!(i128::min_value().checked_rem(i128::new(-1)), None); /// assert_eq!(i128::new(3).checked_rem(i128::zero()), None); /// ``` pub fn checked_rem(self, other: i128) -> Option { if other == ZERO || self == MIN && other == -ONE { None } else { Some(self.wrapping_rem(other)) } } } impl Div for i128 { type Output = Self; fn div(self, other: Self) -> Self { self.wrapping_div(other) } } impl Rem for i128 { type Output = Self; fn rem(self, other: Self) -> Self { self.wrapping_rem(other) } } impl Div for Wrapping { type Output = Self; fn div(self, other: Self) -> Self { Wrapping(self.0.wrapping_div(other.0)) } } impl Rem for Wrapping { type Output = Self; fn rem(self, other: Self) -> Self { Wrapping(self.0.wrapping_rem(other.0)) } } forward_assign!(DivAssign(div_assign, div) for i128); forward_assign!(RemAssign(rem_assign, rem) for i128); impl CheckedDiv for i128 { fn checked_div(&self, other: &Self) -> Option { Self::checked_div(*self, *other) } } /// Computes the divisor and remainder simultaneously. Returns `(a/b, a%b)`. /// /// Unlike the primitive types, calling this is likely faster than calling `a/b` and `a%b` /// separately. /// /// # Panics /// /// This function will panic if `denominator` is 0. If debug assertions is enabled, this function /// will also panic on overflow (when computing `div_rem(MIN, -1)`). /// /// # Examples /// /// ```rust /// use extprim::i128::{div_rem, i128}; /// /// assert_eq!(div_rem(i128::new(100), i128::new(-8)), (i128::new(-12), i128::new(4))); /// ``` pub fn div_rem(numerator: i128, denominator: i128) -> (i128, i128) { if cfg!(debug_assertions) && numerator == MIN && denominator == -ONE { panic!("arithmetic operation overflowed"); } let (sn, n) = sign_abs(numerator); let (sd, d) = sign_abs(denominator); let (div, rem) = ::u128::div_rem(n, d); (from_sign_abs(sn != sd, div), from_sign_abs(sn, rem)) } #[cfg(test)] mod div_rem_tests { use i128::{i128, ONE, div_rem}; #[test] fn test_div() { let nine = i128::new(9); let four = i128::new(4); let two = i128::new(2); assert_eq!(nine / four, two); assert_eq!(nine / -four, -two); assert_eq!((-nine) / four, -two); assert_eq!((-nine) / -four, two); assert_eq!(nine / two, four); assert_eq!(nine / -two, -four); assert_eq!((-nine) / two, -four); assert_eq!((-nine) / -two, four); // Test case copied from https://github.com/rust-lang/rust/issues/41228 assert_eq!(i128::from_parts(-4746635337927214985, 8887618921150887885) / i128::from_parts(4569140803224985180, 0), -ONE); } #[test] fn test_rem() { let nine = i128::new(9); let five = i128::new(5); let four = i128::new(4); assert_eq!(nine % five, four); assert_eq!(nine % -five, four); assert_eq!((-nine) % five, -four); assert_eq!((-nine) % -five, -four); } #[test] fn test_div_rem() { let nine = i128::new(9); let five = i128::new(5); let four = i128::new(4); assert_eq!(div_rem(nine, five), (ONE, four)); assert_eq!(div_rem(nine, -five), (-ONE, four)); assert_eq!(div_rem(-nine, five), (-ONE, -four)); assert_eq!(div_rem(-nine, -five), (ONE, -four)); } } //}}} //{{{ NumCast, ToPrimitive, FromPrimitive impl ToPrimitive for i128 { fn to_i64(&self) -> Option { let hi = self.high64(); let lo = self.low64(); if hi == 0 && (lo >> 63) == 0 || hi == -1 && (lo >> 63) != 0 { Some(lo as i64) } else { None } } fn to_u64(&self) -> Option { if self.high64() != 0 { None } else { Some(self.low64()) } } fn to_f64(&self) -> Option { let (sign, abs) = sign_abs(*self); let converted = abs.to_f64(); if sign { converted.map(|f| -f) } else { converted } } #[cfg(extprim_has_stable_i128)] fn to_i128(&self) -> Option { Some(self.as_built_in()) } #[cfg(extprim_has_stable_i128)] fn to_u128(&self) -> Option { if self.high64() >= 0 { Some(self.0.as_built_in()) } else { None } } } impl FromPrimitive for i128 { fn from_u64(n: u64) -> Option { ToExtraPrimitive::to_i128(&n) } fn from_i64(n: i64) -> Option { ToExtraPrimitive::to_i128(&n) } fn from_f64(n: f64) -> Option { ToExtraPrimitive::to_i128(&n) } } impl ToExtraPrimitive for i128 { fn to_u128(&self) -> Option { if self.is_negative() { None } else { Some(self.0) } } fn to_i128(&self) -> Option { Some(*self) } } impl From for i128 { fn from(arg: i8) -> Self { i128::new(arg as i64) } } impl From for i128 { fn from(arg: i16) -> Self { i128::new(arg as i64) } } impl From for i128 { fn from(arg: i32) -> Self { i128::new(arg as i64) } } impl From for i128 { fn from(arg: i64) -> Self { i128::new(arg) } } #[cfg(extprim_has_stable_i128)] impl From for i128 { fn from(arg: I128) -> Self { i128::from_built_in(arg) } } #[cfg(test)] mod conv_tests { use i128::{i128, MIN, MAX}; use num_traits::ToPrimitive; #[test] fn test_i128_to_f64() { assert_eq!(i128::new(0).to_f64(), Some(0.0f64)); assert_eq!(i128::new(1).to_f64(), Some(1.0f64)); assert_eq!(i128::new(2).to_f64(), Some(2.0f64)); assert_eq!(MAX.to_f64(), Some(170141183460469231731687303715884105727.0f64)); assert_eq!(i128::new(-1).to_f64(), Some(-1.0f64)); assert_eq!(i128::new(-2).to_f64(), Some(-2.0f64)); assert_eq!(MIN.to_f64(), Some(-170141183460469231731687303715884105728.0f64)); } #[test] #[cfg(extprim_has_stable_i128)] fn test_builtin_i128_to_i128() { assert_eq!(i128::from_built_in(0x76571c252122c42e_8cdf8e3b4b75c4d0i128), i128::from_parts(0x76571c252122c42e, 0x8cdf8e3b4b75c4d0)); assert_eq!(i128::from_built_in(-0x76571c252122c42e_8cdf8e3b4b75c4d0i128), i128::from_parts(-0x76571c252122c42f, 0x732071c4b48a3b30)); assert_eq!(0x76571c252122c42e_8cdf8e3b4b75c4d0i128, i128::from_parts(0x76571c252122c42e, 0x8cdf8e3b4b75c4d0).as_built_in()); assert_eq!(-0x76571c252122c42e_8cdf8e3b4b75c4d0i128, i128::from_parts(-0x76571c252122c42f, 0x732071c4b48a3b30).as_built_in()); } } //}}} //{{{ Constants impl i128 { /// Returns the smallest signed 128-bit integer /// (`-170_141_183_460_469_231_731_687_303_715_884_105_728`). pub fn min_value() -> i128 { MIN } /// Returns the largest signed 128-bit integer /// (`170_141_183_460_469_231_731_687_303_715_884_105_727`). pub fn max_value() -> i128 { MAX } /// Returns the constant 0. pub fn zero() -> i128 { ZERO } /// Returns the constant 1. pub fn one() -> i128 { ONE } } impl Bounded for i128 { fn min_value() -> Self { MIN } fn max_value() -> Self { MAX } } impl Zero for i128 { fn zero() -> Self { ZERO } fn is_zero(&self) -> bool { *self == ZERO } } impl One for i128 { fn one() -> Self { ONE } } //}}} //{{{ PrimInt impl i128 { /// Returns the number of ones in the binary representation of `self`. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(-1000).count_ones(), 120); /// ``` pub fn count_ones(self) -> u32 { self.0.count_ones() } /// Returns the number of zeros in the binary representation of `self`. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::new(-1000).count_zeros(), 8); /// ``` pub fn count_zeros(self) -> u32 { self.0.count_zeros() } /// Returns the number of leading zeros in the binary representation of `self`. /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::zero().leading_zeros(), 128); /// assert_eq!(i128::one().leading_zeros(), 127); /// assert_eq!(i128::new(-1).leading_zeros(), 0); /// assert_eq!(i128::max_value().leading_zeros(), 1); /// assert_eq!((i128::one() << 24u32).leading_zeros(), 103); /// assert_eq!((i128::one() << 124u32).leading_zeros(), 3); /// ``` pub fn leading_zeros(self) -> u32 { self.0.leading_zeros() } /// Returns the number of trailing zeros in the binary representation of `self`. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::zero().trailing_zeros(), 128); /// assert_eq!(i128::one().trailing_zeros(), 0); /// assert_eq!(i128::min_value().trailing_zeros(), 127); /// assert_eq!((i128::one() << 24u32).trailing_zeros(), 24); /// assert_eq!((i128::one() << 124u32).trailing_zeros(), 124); /// ``` pub fn trailing_zeros(self) -> u32 { self.0.trailing_zeros() } /// Shifts the bits to the left by a specified amount, `shift`, wrapping the truncated bits to /// the end of the resulting integer. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// let a = i128::from_str_radix("29c30f1029939b146664242d97d9f649", 16).unwrap(); /// let b = i128::from_str_radix("-1e7877eb363275cccdede9341304db6c", 16).unwrap(); /// assert_eq!(a.rotate_left(7), b); /// ``` pub fn rotate_left(self, shift: u32) -> i128 { i128(self.0.rotate_left(shift)) } /// Shifts the bits to the right by a specified amount, `shift`, wrapping the truncated bits to /// the end of the resulting integer. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// let a = i128::from_str_radix("29c30f1029939b146664242d97d9f649", 16).unwrap(); /// let b = i128::from_str_radix("-6dac79e1dfacd8c9d73337b7a4d04c14", 16).unwrap(); /// assert_eq!(a.rotate_right(7), b); /// ``` pub fn rotate_right(self, shift: u32) -> i128 { i128(self.0.rotate_right(shift)) } /// Reverses the byte order of the integer. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// let a = i128::from_str_radix("11122233344455560123456789abcdef", 16).unwrap(); /// let b = i128::from_str_radix("-1032547698badcfea9aabbcbccddedef", 16).unwrap(); /// assert_eq!(a.swap_bytes(), b); /// ``` pub fn swap_bytes(self) -> i128 { i128(self.0.swap_bytes()) } /// Converts an integer from big endian to the target's endianness. /// /// On big endian this is a no-op. On little endian the bytes are swapped. pub fn from_be(x: Self) -> Self { if cfg!(target_endian="big") { x } else { x.swap_bytes() } } /// Converts an integer from little endian to the target's endianness. /// /// On little endian this is a no-op. On big endian the bytes are swapped. pub fn from_le(x: Self) -> Self { if cfg!(target_endian="little") { x } else { x.swap_bytes() } } /// Converts `self` to big endian from the target's endianness. /// /// On big endian this is a no-op. On little endian the bytes are swapped. pub fn to_be(self) -> Self { Self::from_be(self) } /// Converts self to little endian from the target's endianness. /// /// On little endian this is a no-op. On big endian the bytes are swapped. pub fn to_le(self) -> Self { Self::from_le(self) } /// Raises `self` to the power of `exp`, using exponentiation by squaring. /// /// # Examples /// /// ``` /// use extprim::i128::i128; /// use std::str::FromStr; /// /// assert_eq!(i128::new(-5).pow(29), i128::from_str("-186264514923095703125").unwrap()); /// assert_eq!(i128::new(-5).pow(30), i128::from_str("931322574615478515625").unwrap()); /// ``` pub fn pow(self, exp: u32) -> Self { pow(self, exp as usize) } } impl PrimInt for i128 { fn count_ones(self) -> u32 { Self::count_ones(self) } fn count_zeros(self) -> u32 { Self::count_zeros(self) } fn leading_zeros(self) -> u32 { Self::leading_zeros(self) } fn trailing_zeros(self) -> u32 { Self::trailing_zeros(self) } fn rotate_left(self, shift: u32) -> Self { Self::rotate_left(self, shift) } fn rotate_right(self, shift: u32) -> Self { Self::rotate_right(self, shift) } fn swap_bytes(self) -> Self { Self::swap_bytes(self) } fn from_be(x: Self) -> Self { Self::from_be(x) } fn from_le(x: Self) -> Self { Self::from_le(x) } fn to_be(self) -> Self { Self::to_be(self) } fn to_le(self) -> Self { Self::to_le(self) } fn pow(self, exp: u32) -> Self { Self::pow(self, exp) } fn signed_shl(self, shift: u32) -> Self { self << (shift as usize) } fn signed_shr(self, shift: u32) -> Self { self >> (shift as usize) } fn unsigned_shl(self, shift: u32) -> Self { self << (shift as usize) } fn unsigned_shr(self, shift: u32) -> Self { i128(self.0 >> (shift as usize)) } } #[cfg(test)] mod checked_tests { use std::u64; use std::i64; use i128::{i128, ZERO, ONE, MAX, MIN}; #[test] fn test_checked_add() { assert_eq!(Some(ZERO), ONE.checked_add(-ONE)); assert_eq!(Some(ZERO), (-ONE).checked_add(ONE)); assert_eq!(Some(i128::new(-2)), (-ONE).checked_add(-ONE)); assert_eq!(Some(i128::new(2)), ONE.checked_add(ONE)); assert_eq!(Some(MAX), MAX.checked_add(ZERO)); assert_eq!(Some(-ONE), MAX.checked_add(MIN)); assert_eq!(None, MAX.checked_add(ONE)); assert_eq!(None, MIN.checked_add(-ONE)); assert_eq!(None, ONE.checked_add(MAX)); assert_eq!(None, (-ONE).checked_add(MIN)); assert_eq!(Some(ZERO), MAX.checked_add(-MAX)); assert_eq!(None, MIN.checked_add(MIN)); } #[test] fn test_checked_sub() { assert_eq!(Some(ZERO), ONE.checked_sub(ONE)); assert_eq!(Some(ZERO), MAX.checked_sub(MAX)); assert_eq!(Some(ZERO), MIN.checked_sub(MIN)); assert_eq!(Some(-ONE), ZERO.checked_sub(ONE)); assert_eq!(Some(MAX.wrapping_sub(ONE)), MAX.checked_sub(ONE)); assert_eq!(Some(-MAX), ZERO.checked_sub(MAX)); assert_eq!(None, ZERO.checked_sub(MIN)); assert_eq!(None, MIN.checked_sub(ONE)); assert_eq!(None, MAX.checked_sub(-ONE)); assert_eq!(Some(MAX), MAX.checked_sub(ZERO)); assert_eq!(Some(MIN), MIN.checked_sub(ZERO)); assert_eq!(Some(-ONE), MIN.checked_sub(-MAX)); assert_eq!(Some(i128::new(2)), ONE.checked_sub(-ONE)); } #[test] fn test_checked_mul() { assert_eq!(Some(ONE), ONE.checked_mul(ONE)); assert_eq!(Some(ZERO), MIN.checked_mul(ZERO)); assert_eq!(Some(MIN), MIN.checked_mul(ONE)); assert_eq!(None, MIN.checked_mul(i128::new(2))); assert_eq!(Some(MAX), MAX.checked_mul(ONE)); assert_eq!(None, i128::new(2).checked_mul(MAX)); assert_eq!(None, i128::from_parts(1, 0).checked_mul(i128::from_parts(1, 0))); assert_eq!(None, i128::from_parts(1, 0).checked_mul(i128::from_parts(0, u64::MAX))); assert_eq!(Some(-MAX), MAX.checked_mul(-ONE)); assert_eq!(None, MIN.checked_mul(-ONE)); assert_eq!(None, i128::from_parts(-1, 0).checked_mul(i128::from_parts(0, u64::MAX))); assert_eq!(Some(i128::from_parts(-i64::MAX, 0)), i128::from_parts(-1, 0).checked_mul(i128::new(i64::MAX))); assert_eq!(None, i128::from_parts(-1, 0).checked_mul(i128::new(i64::MIN))); } #[test] fn test_checked_div() { assert_eq!(Some(ONE), ONE.checked_div(ONE)); assert_eq!(Some(ONE), (-ONE).checked_div(-ONE)); assert_eq!(Some(MAX), MAX.checked_div(ONE)); assert_eq!(Some(MIN), MIN.checked_div(ONE)); assert_eq!(Some(ZERO), ONE.checked_div(MAX)); assert_eq!(Some(ZERO), ZERO.checked_div(MAX)); assert_eq!(Some(ZERO), ZERO.checked_div(MIN)); assert_eq!(None, ONE.checked_div(ZERO)); assert_eq!(None, MAX.checked_div(ZERO)); assert_eq!(None, MIN.checked_div(ZERO)); assert_eq!(Some(-MAX), MAX.checked_div(-ONE)); assert_eq!(None, MIN.checked_div(-ONE)); } } //}}} //{{{ Signed impl i128 { /// Computes the absolute value of `self`. /// /// # Overflow behavior /// /// The absolute value of `i128::MIN` cannot be represented as an `i128`, and attempting to /// calculate it will cause an overflow. This means that code in debug mode will trigger a /// panic on this case and optimized code will return `MIN` without a panic. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// use std::i64; /// /// assert_eq!(i128::new(10).abs(), i128::new(10)); /// assert_eq!(i128::new(-10).abs(), i128::new(10)); /// assert_eq!(i128::new(i64::MIN).abs(), i128::from_parts(0, 0x80000000_00000000)); /// ``` pub fn abs(self) -> Self { if self.is_negative() { -self } else { self } } /// Returns a number representing sign of `self`. /// /// * `0` if the number is zero /// * `1` if the number is positive /// * `-1` if the number is negative /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::max_value().signum(), i128::one()); /// assert_eq!(i128::zero().signum(), i128::zero()); /// assert_eq!(i128::min_value().signum(), -i128::one()); /// ``` pub fn signum(self) -> Self { let hi = self.high64(); let lo = self.low64(); if hi < 0 { -ONE } else if hi > 0 || lo > 0 { ONE } else { ZERO } } /// Returns `true` if `self` is positive and `false` if the number is zero or negative. /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert!( i128::max_value().is_positive()); /// assert!(! i128::zero().is_positive()); /// assert!(! i128::min_value().is_positive()); /// ``` pub fn is_positive(self) -> bool { let hi = self.high64(); let lo = self.low64(); hi > 0 || hi == 0 && lo > 0 } /// Returns `true` if `self` is negative and `false` if the number is zero or positive. /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert!(! i128::max_value().is_negative()); /// assert!(! i128::zero().is_negative()); /// assert!( i128::min_value().is_negative()); /// ``` pub fn is_negative(self) -> bool { self.high64() < 0 } } impl Signed for i128 { fn abs(&self) -> Self { Self::abs(*self) } fn signum(&self) -> Self { Self::signum(*self) } fn is_positive(&self) -> bool { Self::is_positive(*self) } fn is_negative(&self) -> bool { Self::is_negative(*self) } fn abs_sub(&self, other: &Self) -> Self { if *self <= *other { ZERO } else { *self - *other } } } //}}} //{{{ FromStr, FromStrRadix impl i128 { /// Converts a string slice in a given base to an integer. /// /// Leading and trailing whitespace represent an error. /// /// # Examples /// /// ```rust /// use extprim::i128::i128; /// /// assert_eq!(i128::from_str_radix("123456abcdef1234567890", 16), /// Ok(i128::from_parts(0x123456, 0xabcdef1234567890))); /// ``` pub fn from_str_radix(src: &str, radix: u32) -> Result { assert!(radix >= 2 && radix <= 36, "from_str_radix_int: must lie in the range `[2, 36]` - found {}", radix); let mut src_chars = src.chars(); let (is_negative, src) = match src_chars.next() { Some('-') => (true, src_chars.as_str()), Some(_) => (false, src), None => return Err(error::empty()), }; match u128::from_str_radix(src, radix) { Ok(res) => { let res = from_sign_abs(is_negative, res); if res != ZERO && res.is_negative() != is_negative { Err(if is_negative { error::underflow() } else { error::overflow() }) } else { Ok(res) } }, Err(e) => { if is_negative && error::is_overflow(&e) { Err(error::underflow()) } else { Err(e) } }, } } } impl Num for i128 { type FromStrRadixErr = ParseIntError; fn from_str_radix(src: &str, radix: u32) -> Result { Self::from_str_radix(src, radix) } } impl FromStr for i128 { type Err = ParseIntError; fn from_str(src: &str) -> Result { Self::from_str_radix(src, 10) } } #[cfg(test)] mod from_str_tests { use i128::{i128, ZERO, ONE, MIN, MAX}; use error; #[test] fn test_from_str_radix() { const NEG_TEST_RESULTS: &'static [&'static str] = &[ "-1101001110000001100001110100110110011101000101000000010101010011111111110000011111001111010001011110010010111111100000110111000", "-22120002200011001100011122212011101112220120010100201111102212122012112012001022", "-1221300030032212303220220002222133332003321322023302113330012320", "-2231231421040121443301142220330220044211010312230031421", "-10132201224250532404323114055045240003123220242012", "-1212403560410303232526313225350346610154225424", "-1516014164663505002523776037172136227740670", "-8502604040148764345816110644385565465038", "-140569828839923299370138738435219767736", "-460253358a63a84a62856346973015326a085", "-24684544189b3b874708a686624448540308", "-1b5619074137abcca07c1b789a5bb40143a", "-218c480b6358d305699729902706a4db84", "-33d141e10db8d70b6249ae5224b7c97ab", "-69c0c3a6ce8a02a9ff83e7a2f25fc1b8", "-102b311fc29a372ecb13e199baf8acfe", "-31aaf9047ff3ec83haa539ab9419b68", "-bb3a85b4194a20if536h6heha6i35b", "-2c76aee5d2b9da7ae7fb3a2a63aj6g", "-d7b08bdk5fk2de09j5ed0gcg27f5b", "-3djbdj2fa4khdffaldl1b208ej2kg", "-11172kdka2cf0gj0im640g8gi0mkd", "-7enbdaajdc653dabmllnjll400i8", "-2d7gm5k79nf6mc3fc0ob55gcf39b", "-mlhn5khiebmai868llpeih4mnla", "-8f2i4194hn4aeof39jdbnh5e518", "-392krpg3g0r0d1001nj4jm5fkb4", "-19kq0qaqlnf9c535470kddq5ida", "-ghleobpr1dricb67pkro9ii1rq", "-79hp9koffuiiscaoiouar0fgp0", "-39o31qdjka0akvv0v7kbp5vgdo", "-1hhh74vud8w72snbpj5teksfw5", "-on7ixvje61183p5w49qovbwxe", "-catrg80wne60wsi5f2y4nefab", "-69e1equxg4kja5utg038kcgc8", ]; let neg = i128::from_parts(-7620305690708017834, 34929685051752008); for (base2, res) in NEG_TEST_RESULTS.iter().enumerate() { let base = (base2 + 2) as u32; assert_eq!(Ok(neg), i128::from_str_radix(*res, base)); assert_eq!(Ok(-neg), i128::from_str_radix(&res[1..], base)); } assert_eq!(Ok(ZERO), i128::from_str_radix("0", 2)); assert_eq!(Ok(ZERO), i128::from_str_radix("-0", 2)); assert_eq!(Ok(ZERO), i128::from_str_radix("0000000000000000000000000000000000", 36)); assert_eq!(Err(error::invalid_digit()), i128::from_str_radix("123", 3)); assert_eq!(Ok(-ONE), i128::from_str_radix("-1", 10)); assert_eq!(Err(error::invalid_digit()), i128::from_str_radix("~1", 10)); assert_eq!(Err(error::empty()), i128::from_str_radix("", 10)); assert_eq!(Ok(MAX), i128::from_str_radix("7ksyyizzkutudzbv8aqztecjj", 36)); assert_eq!(Ok(MIN), i128::from_str_radix("-7ksyyizzkutudzbv8aqztecjk", 36)); assert_eq!(Err(error::overflow()), i128::from_str_radix("7ksyyizzkutudzbv8aqztecjk", 36)); assert_eq!(Err(error::underflow()), i128::from_str_radix("-7ksyyizzkutudzbv8aqztecjl", 36)); } } //}}} //{{{ String, Binary, LowerHex, UpperHex, Octal, Show // In Rust, all signed numbers will be printed as unsigned in binary, octal // and hex mode. impl fmt::Binary for i128 { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(formatter) } } impl fmt::LowerHex for i128 { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(formatter) } } impl fmt::UpperHex for i128 { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(formatter) } } impl fmt::Octal for i128 { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(formatter) } } impl fmt::Display for i128 { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { if !self.is_negative() { self.0.fmt(formatter) } else if *self == MIN { formatter.pad_integral(false, "", "170141183460469231731687303715884105728") } else { let mut buffer = [0u8; 39]; let mut buf = FormatBuffer::new(&mut buffer); write!(&mut buf, "{}", self.0.wrapping_neg())?; formatter.pad_integral(false, "", unsafe { buf.into_str() }) } } } impl fmt::Debug for i128 { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "i128!({})", self) } } #[cfg(test)] mod show_tests { use i128::{i128, ZERO, ONE, MIN, MAX}; #[test] fn test_show() { assert_fmt_eq!("0", 1, "{}", ZERO); assert_fmt_eq!("1", 1, "{}", ONE); assert_fmt_eq!("-1", 2, "{}", -ONE); assert_fmt_eq!("170141183460469231731687303715884105727", 40, "{}", MAX); assert_fmt_eq!("-170141183460469231731687303715884105727", 40, "{}", -MAX); assert_fmt_eq!("-170141183460469231731687303715884105728", 40, "{}", MIN); assert_fmt_eq!("-41001515780870386888810710836203638388", 40, "{}", i128::from_parts(-2222696624240918362, 11097545986877534604)); assert_fmt_eq!("+00170141183460469231731687303715884105727", 42, "{:+042}", MAX); assert_fmt_eq!("-00170141183460469231731687303715884105728", 42, "{:+042}", MIN); // Sanity test assert_fmt_eq!("ff", 2, "{:x}", -1i8); } } //}}} //{{{ Sum, Product impl Sum for i128 { fn sum(iter: I) -> Self where I: Iterator { iter.fold(ZERO, Add::add) } } impl Product for i128 { fn product(iter: I) -> Self where I: Iterator { iter.fold(ONE, Mul::mul) } } impl<'a> Sum<&'a i128> for i128 { fn sum(iter: I) -> Self where I: Iterator { iter.fold(ZERO, |acc, elem| acc + *elem) } } impl<'a> Product<&'a i128> for i128 { fn product(iter: I) -> Self where I: Iterator { iter.fold(ONE, |acc, elem| acc * *elem) } } #[cfg(test)] mod iter_tests { use i128::{i128, ZERO, ONE, MIN, MAX}; #[test] fn test_sum() { // Sum assert_eq!(ZERO, Vec::::new().into_iter().sum()); assert_eq!(ZERO, vec![ZERO, ZERO, ZERO].into_iter().sum()); assert_eq!(ZERO, vec![-ONE, ONE].into_iter().sum()); assert_eq!(ONE, vec![ONE].into_iter().sum()); assert_eq!(i128::from(3i64), vec![ONE, ONE, ONE].into_iter().sum()); assert_eq!(-ONE, vec![MAX, MIN].into_iter().sum()); assert_eq!(i128::from(2i64), vec![ i128::from(-3i64), i128::from(10i64), MIN, MAX - i128::from(4i64), ].into_iter().sum()); assert_eq!(MAX, vec![MAX].into_iter().sum()); assert_eq!(MIN, vec![MIN].into_iter().sum()); assert_eq!(i128::from_parts(7, 42), vec![i128::from_parts(7, 42)].into_iter().sum()); // Sum<&'a i128> assert_eq!(ZERO, [].iter().sum()); assert_eq!(ZERO, [ZERO, ZERO, ZERO].iter().sum()); assert_eq!(ZERO, [-ONE, ONE].iter().sum()); assert_eq!(ONE, [ONE].iter().sum()); assert_eq!(i128::from(3i64), [ONE, ONE, ONE].iter().sum()); assert_eq!(-ONE, [MAX, MIN].iter().sum()); assert_eq!(i128::from(2i64), [ i128::from(-3i64), i128::from(10i64), MIN, MAX - i128::from(4i64), ].iter().sum()); assert_eq!(MAX, [MAX].iter().sum()); assert_eq!(MIN, [MIN].iter().sum()); assert_eq!(i128::from_parts(7, 42), [i128::from_parts(7, 42)].iter().sum()); } #[test] fn test_product() { // Product assert_eq!(ONE, Vec::::new().into_iter().product()); assert_eq!(ONE, vec![ONE, ONE, ONE, ONE, ONE].into_iter().product()); assert_eq!(ZERO, vec![MAX, ZERO, MIN, ONE].into_iter().product()); assert_eq!(MAX, vec![MAX].into_iter().product()); assert_eq!(MAX, vec![ONE, MAX].into_iter().product()); assert_eq!(MIN, vec![MIN].into_iter().product()); assert_eq!(MIN, vec![ONE, MIN].into_iter().product()); assert_eq!(MIN, vec![ i128::from(-0x1i64), i128::from(0x2i64), i128::from(0x4i64), i128::from(0x10i64), i128::from(0x100i64), i128::from(0x10000i64), i128::from(0x100000000i64), i128::from_parts(0x1, 0x0), ].into_iter().product()); // Product<&'a i128> assert_eq!(ONE, [].iter().product()); assert_eq!(ONE, [ONE, ONE, ONE, ONE, ONE].iter().product()); assert_eq!(ZERO, [MAX, ZERO, MIN, ONE].iter().product()); assert_eq!(MAX, [MAX].iter().product()); assert_eq!(MAX, [ONE, MAX].iter().product()); assert_eq!(MIN, [MIN].iter().product()); assert_eq!(MIN, [ONE, MIN].iter().product()); assert_eq!(MIN, [ i128::from(-0x1i64), i128::from(0x2i64), i128::from(0x4i64), i128::from(0x10i64), i128::from(0x100i64), i128::from(0x10000i64), i128::from(0x100000000i64), i128::from_parts(0x1, 0x0), ].iter().product()); } } //}}} extprim-1.7.1/src/lib.rs000064400000000000000000000054141366240513200133070ustar0000000000000000//! This crate provides some extra simple types. //! //! u128 and i128 //! ============= //! //! Support signed and unsigned 128-bit integers. Also standard primitive operations are supported. //! //! These are mainly needed where explicit 128-bit integer types are required. If the purpose is to //! operate on "very large integers", the [bigint](https://crates.io/crates/num-bigint) library may //! be more suitable. //! //! ```rust //! #[macro_use] extern crate extprim_literals; //! extern crate extprim; //! //! use std::str::FromStr; //! use extprim::i128::i128; //! //! fn main() { //! let a = i128::from_str("100000000000000000000000000000000000000").unwrap(); //! // convert string to u128 or i128 //! let b = i128::new(10).pow(38); //! // 64-bit integers can be directly new'ed //! assert_eq!(a, b); //! //! let c = i128::from_parts(5421010862427522170, 687399551400673280); //! // represent using the higher- and lower-64-bit parts //! let d = c - a; //! // standard operators like +, -, *, /, %, etc. work as expected. //! assert_eq!(d, i128::zero()); //! //! const e: i128 = i128!(100000000000000000000000000000000000000); //! // use the literal macros //! assert_eq!(a, e); //! } //! ``` //! //! Literal macros //! ============== //! //! The extra primitive types can be created via the literal macros using the `extprim_literals` procedural macro. //! Please check the [documentation of `extprim_literals`](../../extprim_literals/index.html) for details. //! //! ```ignore //! #![macro_use] //! extern crate extprim_literals; //! extern crate extprim; //! //! fn main() { //! let a = u128!(0xffeeddcc_bbaa9988_77665544_33221100); //! let b = u128!(73); //! let result = a / b; //! let expected = u128!(4_660_183_619_323_730_626_856_278_982_251_165_334); //! assert_eq!(a / b, expected); //! } //! ``` #![cfg_attr(extprim_channel="unstable", feature(llvm_asm, test, specialization, const_fn))] // feature requirement: // - llvm_asm: to provide a fast implementation of u64_long_mul in x86_64 // - test: benchmarking // - specialization: to allow ToExtraPrimitive inherit from ToPrimitive, while ensuring conversion // between the 128-bit types remain correct // - const_fn: Create 128-bit constants #![cfg_attr(not(feature="use-std"), no_std)] #[cfg(extprim_channel="unstable")] extern crate test; #[cfg(feature = "serde")] #[macro_use] extern crate serde; #[cfg(feature="use-std")] extern crate core; #[cfg(not(feature="use-std"))] extern crate core as std; #[cfg(feature="rand")] extern crate rand; extern crate num_traits; #[macro_use] mod forward; #[cfg_attr(test, macro_use)] mod format_buffer; mod error; pub mod traits; pub mod u128; pub mod i128; mod compiler_rt; extprim-1.7.1/src/traits.rs000064400000000000000000000367761356430463100140710ustar0000000000000000//! Traits for conversion between the extra primitive types. use num_traits::{ToPrimitive, NumCast, One, Float}; #[cfg(feature="use-std")] use num_traits::Num; use u128::u128; use i128::i128; #[cfg(extprim_has_stable_i128)] use compiler_rt::builtins::{U128, I128}; use std::ops::MulAssign; /// Trait for converting itself into the extra primitive types. /// /// # Note /// /// Converting f32/f64 to u128/i128 will always succeed, even if they represent values outside of /// the u128/i128 ranges. They will just return `Some(0)` on overflow. This is similar to how /// `num_traits::ToPrimitive` treat the float conversions. /// /// ```rust /// use extprim::traits::ToExtraPrimitive; /// use extprim::u128::u128; /// use std::f64; /// /// assert_eq!(680.0f64.to_u128(), Some(u128::new(680))); /// assert_eq!(2.0f64.powi(64).to_u128(), Some(u128::from_parts(1, 0))); /// /// // The following examples overflow, but they all still convert to 0. /// assert_eq!(2.0f64.powi(128).to_u128(), Some(u128::zero())); /// assert_eq!(f64::MAX.to_u128(), Some(u128::zero())); /// assert_eq!(f64::INFINITY.to_u128(), Some(u128::zero())); /// assert_eq!(f64::NAN.to_u128(), Some(u128::zero())); /// ``` pub trait ToExtraPrimitive: ToPrimitive { /// Tries to convert itself into an unsigned 128-bit integer. fn to_u128(&self) -> Option; /// Tries to convert itself into a signed 128-bit integer. fn to_i128(&self) -> Option; } macro_rules! impl_to_extra_primitive_for_int { ($ty:ty) => { impl ToExtraPrimitive for $ty { fn to_u128(&self) -> Option { #[cfg(extprim_has_stable_i128)] { ToPrimitive::to_u128(self).map(u128::from_built_in) } #[cfg(not(extprim_has_stable_i128))] { self.to_u64().map(u128::new) } } fn to_i128(&self) -> Option { #[cfg(extprim_has_stable_i128)] { ToPrimitive::to_i128(self).map(i128::from_built_in) } #[cfg(not(extprim_has_stable_i128))] { match self.to_u64() { Some(v) => Some(i128(u128::new(v))), None => self.to_i64().map(i128::new), } } } } } } impl_to_extra_primitive_for_int!(u8); impl_to_extra_primitive_for_int!(i8); impl_to_extra_primitive_for_int!(u16); impl_to_extra_primitive_for_int!(i16); impl_to_extra_primitive_for_int!(u32); impl_to_extra_primitive_for_int!(i32); impl_to_extra_primitive_for_int!(u64); impl_to_extra_primitive_for_int!(i64); impl_to_extra_primitive_for_int!(usize); impl_to_extra_primitive_for_int!(isize); #[cfg(extprim_has_stable_i128)] impl_to_extra_primitive_for_int!(U128); #[cfg(extprim_has_stable_i128)] impl_to_extra_primitive_for_int!(I128); macro_rules! impl_to_extra_primitive_for_float { ($float:ty, $d:expr, $e:expr, $f:expr) => { // static_assert!($e == 127-$d); // static_assert!($f == 126-$d); // impl ToExtraPrimitive for $float { fn to_u128(&self) -> Option { let (mantissa, exp, sign) = Float::integer_decode(*self); Some(match exp { _ if sign < 0 => u128::zero(), -$d ... 0 => u128::new(mantissa >> -exp), 1 ... $e => u128::new(mantissa) << exp, _ => u128::zero(), }) } fn to_i128(&self) -> Option { let (mantissa, exp, sign) = Float::integer_decode(*self); let abs = match exp { -$d ... 0 => u128::new(mantissa >> -exp), 1 ... $f => u128::new(mantissa) << exp, $e if sign == -1 && mantissa == (1 << $d) => u128::from_parts(0x80000000_00000000, 0), _ => u128::zero(), }; Some(if sign >= 0 { abs.as_i128() } else { abs.wrapping_neg().as_i128() }) } } } } impl_to_extra_primitive_for_float!(f32, 23, 104, 103); impl_to_extra_primitive_for_float!(f64, 52, 75, 74); #[cfg(test)] mod float_to_128_tests { use u128::u128; use i128::i128; use traits::ToExtraPrimitive; use std::{u64, i64, f32, f64}; #[test] fn test_u64_to_u128() { assert_eq!(0u64.to_u128(), Some(u128::new(0))); assert_eq!(u64::MAX.to_u128(), Some(u128::new(u64::MAX))); } #[test] fn test_i64_to_u128() { assert_eq!(0i64.to_u128(), Some(u128::new(0))); assert_eq!(i64::MAX.to_u128(), Some(u128::new(0x7fffffff_ffffffff))); assert_eq!(i64::MIN.to_u128(), None); } #[test] fn test_u64_to_i128() { assert_eq!(0u64.to_i128(), Some(i128::new(0))); assert_eq!(u64::MAX.to_i128(), Some(i128::from_parts(0, u64::MAX))); } #[test] fn test_i64_to_i128() { assert_eq!(0i64.to_i128(), Some(i128::new(0))); assert_eq!(i64::MAX.to_i128(), Some(i128::new(i64::MAX))); assert_eq!(i64::MIN.to_i128(), Some(i128::new(i64::MIN))); } #[test] fn test_f64_to_u128() { assert_eq!(0.0f64.to_u128(), Some(u128::new(0))); assert_eq!(0.9f64.to_u128(), Some(u128::new(0))); assert_eq!(1.0f64.to_u128(), Some(u128::new(1))); assert_eq!(1.9f64.to_u128(), Some(u128::new(1))); assert_eq!(1.0e19f64.to_u128(), Some(u128::new(10000000000000000000))); assert_eq!(1.0e20f64.to_u128(), Some(u128::from_parts(5, 7766279631452241920))); assert_eq!(1.0e38f64.to_u128(), Some(u128::from_parts(5421010862427522048, 0))); assert_eq!(3.0e38f64.to_u128(), Some(u128::from_parts(16263032587282567168, 0))); assert_eq!(1.0e39f64.to_u128(), Some(u128::zero())); assert_eq!(340282366920938425684442744474606501888.0f64.to_u128(), Some(u128::from_parts(0xffffffff_fffff800, 0))); assert_eq!(340282366920938463463374607431768211456.0f64.to_u128(), Some(u128::zero())); assert_eq!((-0.0f64).to_u128(), Some(u128::zero())); assert_eq!((-1.0f64).to_u128(), Some(u128::zero())); assert_eq!((f64::NAN).to_u128(), Some(u128::zero())); assert_eq!((f64::MAX).to_u128(), Some(u128::zero())); assert_eq!((f64::MIN_POSITIVE).to_u128(), Some(u128::zero())); assert_eq!((f64::INFINITY).to_u128(), Some(u128::zero())); } #[test] fn test_f64_to_i128() { assert_eq!(0.0f64.to_i128(), Some(i128::new(0))); assert_eq!(0.9f64.to_i128(), Some(i128::new(0))); assert_eq!(1.0f64.to_i128(), Some(i128::new(1))); assert_eq!(1.9f64.to_i128(), Some(i128::new(1))); assert_eq!(1.0e19f64.to_i128(), Some(i128::from_parts(0, 10000000000000000000))); assert_eq!(1.0e20f64.to_i128(), Some(i128::from_parts(5, 7766279631452241920))); assert_eq!(1.0e38f64.to_i128(), Some(i128::from_parts(5421010862427522048, 0))); assert_eq!(3.0e38f64.to_i128(), Some(i128::zero())); assert_eq!(1.0e39f64.to_i128(), Some(i128::zero())); assert_eq!((-0.0f64).to_i128(), Some(i128::new(0))); assert_eq!((-0.9f64).to_i128(), Some(i128::new(0))); assert_eq!((-1.0f64).to_i128(), Some(i128::new(-1))); assert_eq!((-1.9f64).to_i128(), Some(i128::new(-1))); assert_eq!((-1.0e20f64).to_i128(), Some(i128::from_parts(-6, 10680464442257309696))); assert_eq!((-1.0e38f64).to_i128(), Some(i128::from_parts(-5421010862427522048, 0))); assert_eq!((-1.0e39f64).to_i128(), Some(i128::zero())); assert_eq!(170141183460469212842221372237303250944.0f64.to_i128(), Some(i128::from_parts(0x7fffffff_fffffc00, 0))); assert_eq!(170141183460469231731687303715884105728.0f64.to_i128(), Some(i128::zero())); assert_eq!((-170141183460469231731687303715884105728.0f64).to_i128(), Some(i128::min_value())); assert_eq!((-170141183460469269510619166673045815296.0f64).to_i128(), Some(i128::zero())); assert_eq!((f64::NAN).to_i128(), Some(i128::zero())); assert_eq!((f64::MAX).to_i128(), Some(i128::zero())); assert_eq!((f64::MIN_POSITIVE).to_i128(), Some(i128::zero())); assert_eq!((f64::INFINITY).to_i128(), Some(i128::zero())); } #[test] fn test_f32_to_u128() { assert_eq!(0.0f32.to_u128(), Some(u128::new(0))); assert_eq!(0.9f32.to_u128(), Some(u128::new(0))); assert_eq!(1.0f32.to_u128(), Some(u128::new(1))); assert_eq!(1.9f32.to_u128(), Some(u128::new(1))); assert_eq!(1.0e19f32.to_u128(), Some(u128::new(9999999980506447872))); assert_eq!(1.0e20f32.to_u128(), Some(u128::from_parts(5, 7766281635539976192))); assert_eq!(1.0e38f32.to_u128(), Some(u128::from_parts(5421010689110048768, 0))); assert_eq!(3.0e38f32.to_u128(), Some(u128::from_parts(16263032617085960192, 0))); assert_eq!((-0.0f32).to_u128(), Some(u128::zero())); assert_eq!((-1.0f32).to_u128(), Some(u128::zero())); assert_eq!((f32::NAN).to_u128(), Some(u128::zero())); assert_eq!((f32::MAX).to_u128(), Some(u128::from_parts(0xffffff0000000000, 0))); assert_eq!((f32::MIN_POSITIVE).to_u128(), Some(u128::zero())); assert_eq!((f32::INFINITY).to_u128(), Some(u128::zero())); } #[test] fn test_f32_to_i128() { assert_eq!(0.0f32.to_i128(), Some(i128::new(0))); assert_eq!(0.9f32.to_i128(), Some(i128::new(0))); assert_eq!(1.0f32.to_i128(), Some(i128::new(1))); assert_eq!(1.9f32.to_i128(), Some(i128::new(1))); assert_eq!(1.0e19f32.to_i128(), Some(i128::from_parts(0, 9999999980506447872))); assert_eq!(1.0e20f32.to_i128(), Some(i128::from_parts(5, 7766281635539976192))); assert_eq!(1.0e38f32.to_i128(), Some(i128::from_parts(5421010689110048768, 0))); assert_eq!(3.0e38f32.to_i128(), Some(i128::zero())); assert_eq!((-0.0f32).to_i128(), Some(i128::new(0))); assert_eq!((-0.9f32).to_i128(), Some(i128::new(0))); assert_eq!((-1.0f32).to_i128(), Some(i128::new(-1))); assert_eq!((-1.9f32).to_i128(), Some(i128::new(-1))); assert_eq!((-1.0e20f32).to_i128(), Some(i128::from_parts(-6, 10680462438169575424))); assert_eq!((-1.0e38f32).to_i128(), Some(i128::from_parts(-5421010689110048768, 0))); assert_eq!(170141173319264429905852091742258462720.0f32.to_i128(), Some(i128::from_parts(0x7fffff80_00000000, 0))); assert_eq!(170141183460469231731687303715884105728.0f32.to_i128(), Some(i128::zero())); assert_eq!((-170141183460469231731687303715884105728.0f32).to_i128(), Some(i128::min_value())); assert_eq!((-170141203742878835383357727663135391744.0f32).to_i128(), Some(i128::zero())); assert_eq!((f32::NAN).to_i128(), Some(i128::zero())); assert_eq!((f32::MAX).to_i128(), Some(i128::zero())); assert_eq!((f32::MIN_POSITIVE).to_i128(), Some(i128::zero())); assert_eq!((f32::INFINITY).to_i128(), Some(i128::zero())); } } #[cfg(extprim_channel = "unstable")] impl ToExtraPrimitive for T { default fn to_u128(&self) -> Option { ToPrimitive::to_u128(self).map(u128::from_built_in) } default fn to_i128(&self) -> Option { ToPrimitive::to_i128(self).map(i128::from_built_in) } } impl NumCast for u128 { fn from(n: T) -> Option { #[cfg(extprim_has_stable_i128)] { ToPrimitive::to_u128(&n).map(u128::from_built_in) } #[cfg(not(extprim_has_stable_i128))] { panic!("cannot use this before Rust 1.26.0"); } } } impl NumCast for i128 { fn from(n: T) -> Option { #[cfg(extprim_has_stable_i128)] { ToPrimitive::to_i128(&n).map(i128::from_built_in) } #[cfg(not(extprim_has_stable_i128))] { panic!("cannot use this before Rust 1.26.0"); } } } #[cfg(all(extprim_has_stable_i128, test))] mod num_cast_tests { use std::u64; use num_traits::NumCast; use u128::u128; use i128::i128; #[test] fn test_num_cast_for_u128() { assert_eq!(None::, NumCast::from(-1i8)); // sanity check. assert_eq!(None::, NumCast::from(-1i8)); assert_eq!(Some(u128::one()), NumCast::from(1i8)); assert_eq!(Some(u128::new(u64::MAX)), NumCast::from(u64::MAX)); assert_eq!(Some(u128::max_value()), NumCast::from(u128::max_value())); assert_eq!(Some(u128::one()), NumCast::from(i128::new(1))); assert_eq!(None::, NumCast::from(i128::new(-1))); } #[test] fn test_num_cast_for_i128() { assert_eq!(None::, NumCast::from(0x8000_0000_0000_0000u64)); // sanity check. assert_eq!(None::, NumCast::from(u128::max_value())); assert_eq!(Some(i128::one()), NumCast::from(1i8)); assert_eq!(Some(-i128::one()), NumCast::from(-1i8)); assert_eq!(Some(i128::from_parts(0, 0x8000_0000_0000_0000)), NumCast::from(0x8000_0000_0000_0000u64)); assert_eq!(Some(i128::max_value()), NumCast::from(i128::max_value())); assert_eq!(Some(i128::min_value()), NumCast::from(i128::min_value())); assert_eq!(Some(i128::one()), NumCast::from(i128::new(1))); assert_eq!(None::, NumCast::from(u128::from_parts(0x8000_0000_0000_0000, 0))); } } /// Wrapper for `u128` and `i128` to turn arithmetic operators to wrapping ones. /// /// Equivalent to `std::num::Wrapping`, but due to E0117 (orphan rule) we need to define it here to /// implement operators on it. #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug, Default)] pub struct Wrapping(pub T); /// Raise `base` to the power of `exp`, using exponentiation by squaring. /// /// # Examples /// /// ```rust /// use extprim::traits::pow; /// /// assert_eq!(pow(10u64, 7), 10000000u64); /// ``` #[deprecated(since="1.1.1", note="please use `num_traits::pow` instead")] pub fn pow(mut base: T, mut exp: u32) -> T { let mut acc = T::one(); while exp > 1 { if (exp & 1) == 1 { acc *= base; } exp /= 2; base *= base; } if exp == 1 { acc *= base; } acc } /// Parses a Rust integer literal into an actual integral type. /// /// If `is_negative` is true, a negative sign will be added to the string before the conversion. /// /// # Examples /// /// ```rust /// use extprim::traits::parse_rust_int_lit; /// use extprim::u128::u128; /// use extprim::i128::i128; /// /// assert_eq!(parse_rust_int_lit::("100_000", false).unwrap(), u128::new(100_000)); /// assert_eq!(parse_rust_int_lit::("0xffffffff_ffffffff_22222222_22222222", false).unwrap(), /// u128::from_parts(0xffffffff_ffffffff, 0x22222222_22222222)); /// assert_eq!(parse_rust_int_lit::("0b111", true).unwrap(), i128::new(-0b111)); /// assert_eq!(parse_rust_int_lit::("0x80000000_00000000_00000000_00000000", true).unwrap(), /// i128::min_value()); /// ``` #[cfg(feature="use-std")] // TODO should be usable even without std. pub fn parse_rust_int_lit(s: &str, is_negative: bool) -> Result { let mut c = s.chars(); let (base, digits) = if c.next() != Some('0') { (10, s) } else { match c.next() { Some('b') | Some('B') => (2, c.as_str()), Some('o') | Some('O') => (8, c.as_str()), Some('x') | Some('X') => (16, c.as_str()), _ => (10, s), } }; let sign = if is_negative { "-" } else { "" }; let digits = format!("{}{}", sign, digits.replace("_", "")); T::from_str_radix(&digits, base) } extprim-1.7.1/src/u128.rs000064400000000000000000002445301366240513200132440ustar0000000000000000//! Unsigned 128-bit integer. use std::cmp::Ordering; use std::fmt::{self, Write}; use std::iter::{Product, Sum}; use std::num::ParseIntError; use std::ops::*; use std::str::FromStr; use std::u64; #[cfg(feature="rand")] use rand::Rng; #[cfg(feature="rand")] use rand::distributions::{Standard, Distribution}; use num_traits::*; use compiler_rt::{udiv128, umod128, udivmod128}; use error; use format_buffer::FormatBuffer; use i128::i128; use traits::{ToExtraPrimitive, Wrapping}; #[cfg(extprim_has_stable_i128)] use compiler_rt::builtins::{I128, U128}; //{{{ Structure /// Number of bits an unsigned 128-bit number occupies. pub const BITS: usize = 128; /// Number of bytes an unsigned 128-bit number occupies. pub const BYTES: usize = 16; /// The smallest unsigned 128-bit integer (0). pub const MIN: u128 = u128 { lo: 0, hi: 0 }; /// The largest unsigned 128-bit integer (`340_282_366_920_938_463_463_374_607_431_768_211_455`). pub const MAX: u128 = u128 { lo: u64::MAX, hi: u64::MAX }; /// The constant 0. pub const ZERO: u128 = MIN; /// The constant 1. pub const ONE: u128 = u128 { lo: 1, hi: 0 }; /// An unsigned 128-bit number. #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Default, Copy, Clone, Hash, PartialEq, Eq)] #[repr(C)] #[allow(non_camel_case_types)] pub struct u128 { // TODO these two fields are public because `const fn` are not yet stable. /// The lower 64-bit of the number. #[doc(hidden)] #[cfg(target_endian="little")] pub lo: u64, /// The higher 64-bit of the number. #[doc(hidden)] pub hi: u64, /// The lower 64-bit of the number. #[doc(hidden)] #[cfg(target_endian="big")] pub lo: u64, } impl u128 { /// Constructs a new 128-bit integer from a 64-bit integer. #[cfg(extprim_channel="stable")] pub fn new(lo: u64) -> u128 { u128 { lo: lo, hi: 0 } } /// Constructs a new 128-bit integer from a 64-bit integer. #[cfg(extprim_channel="unstable")] pub const fn new(lo: u64) -> u128 { u128 { lo: lo, hi: 0 } } /// Constructs a new 128-bit integer from the built-in 128-bit integer. #[cfg(extprim_has_stable_i128)] #[cfg(extprim_channel="stable")] pub fn from_built_in(value: U128) -> u128 { u128 { lo: (value & 0xffff_ffff_ffff_ffff) as u64, hi: (value >> 64) as u64, } } /// Constructs a new 128-bit integer from the built-in 128-bit integer. #[cfg(extprim_has_stable_i128)] #[cfg(extprim_channel="unstable")] pub const fn from_built_in(value: U128) -> u128 { u128 { lo: (value & 0xffff_ffff_ffff_ffff) as u64, hi: (value >> 64) as u64, } } /// Constructs a new 128-bit integer from the high-64-bit and low-64-bit parts. /// /// The new integer can be considered as `hi * 2**64 + lo`. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// let number = u128::from_parts(6692605942, 14083847773837265618); /// assert_eq!(format!("{}", number), "123456789012345678901234567890"); /// ``` #[cfg(extprim_channel="stable")] pub fn from_parts(hi: u64, lo: u64) -> u128 { u128 { lo: lo, hi: hi } } /// Constructs a new 128-bit integer from the high-64-bit and low-64-bit parts. /// /// The new integer can be considered as `hi * 2**64 + lo`. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// let number = u128::from_parts(6692605942, 14083847773837265618); /// assert_eq!(format!("{}", number), "123456789012345678901234567890"); /// ``` #[cfg(extprim_channel="unstable")] pub const fn from_parts(hi: u64, lo: u64) -> u128 { u128 { lo: lo, hi: hi } } /// Fetches the lower-64-bit of the number. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// let number = u128::from_str_radix("ffd1390a0adc2fb8dabbb8174d95c99b", 16).unwrap(); /// assert_eq!(number.low64(), 0xdabbb8174d95c99b); /// ``` pub fn low64(self) -> u64 { self.lo } /// Fetch the higher-64-bit of the number. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// let number = u128::from_str_radix("ffd1390a0adc2fb8dabbb8174d95c99b", 16).unwrap(); /// assert_eq!(number.high64(), 0xffd1390a0adc2fb8); /// ``` pub fn high64(self) -> u64 { self.hi } /// Converts this number to signed with wrapping. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// use extprim::i128::i128; /// /// let a = u128::from_str_radix( "ffd1390a0adc2fb8dabbb8174d95c99b", 16).unwrap(); /// let b = i128::from_str_radix("-002ec6f5f523d047254447e8b26a3665", 16).unwrap(); /// assert_eq!(a.as_i128(), b); /// assert_eq!(b.as_u128(), a); /// ``` pub fn as_i128(self) -> i128 { i128::from_parts(self.hi as i64, self.lo) } /// Converts this number to the built-in 128-bit integer type. #[cfg(extprim_has_stable_i128)] pub fn as_built_in(self) -> U128 { (self.hi as U128) << 64 | self.lo as U128 } } //}}} //{{{ Rand #[cfg(feature="rand")] impl Distribution for Standard { fn sample(&self, rng: &mut R) -> u128 { let (lo, hi) = rng.gen(); u128::from_parts(lo, hi) } } //}}} //{{{ Add, Sub impl u128 { /// Wrapping (modular) addition. Computes `self + other`, wrapping around at the boundary of /// the type. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::new(5).wrapping_add(u128::new(6)), u128::new(11)); /// assert_eq!(u128::max_value().wrapping_add(u128::one()), u128::zero()); /// ``` pub fn wrapping_add(self, other: u128) -> u128 { let (lo, carry) = self.lo.overflowing_add(other.lo); let hi = self.hi.wrapping_add(other.hi); let hi = hi.wrapping_add(if carry { 1 } else { 0 }); u128::from_parts(hi, lo) } /// Wrapping (modular) subtraction. Computes `self - other`, wrapping around at the boundary of /// the type. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::new(6).wrapping_sub(u128::new(5)), u128::one()); /// assert_eq!(u128::new(5).wrapping_sub(u128::new(6)), u128::max_value()); /// ``` pub fn wrapping_sub(self, other: u128) -> u128 { let (lo, borrow) = self.lo.overflowing_sub(other.lo); let hi = self.hi.wrapping_sub(other.hi); let hi = hi.wrapping_sub(if borrow { 1 } else { 0 }); u128::from_parts(hi, lo) } /// Calculates `self + other`. /// /// Returns a tuple of the addition along with a boolean indicating whether an arithmetic /// overflow would occur. If an overflow would have occurred then the wrapped value is /// returned. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::new(6).overflowing_add(u128::new(13)), (u128::new(19), false)); /// assert_eq!(u128::max_value().overflowing_add(u128::one()), (u128::zero(), true)); /// ``` pub fn overflowing_add(self, other: u128) -> (u128, bool) { let (lo, lo_carry) = self.lo.overflowing_add(other.lo); let (hi, hi_carry_1) = self.hi.overflowing_add(if lo_carry { 1 } else { 0 }); let (hi, hi_carry_2) = hi.overflowing_add(other.hi); (u128::from_parts(hi, lo), hi_carry_1 || hi_carry_2) } /// Calculates `self - other`. /// /// Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic /// overflow would occur. If an overflow would have occurred then the wrapped value is /// returned. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::new(6).overflowing_sub(u128::new(5)), (u128::one(), false)); /// assert_eq!(u128::new(5).overflowing_sub(u128::new(6)), (u128::max_value(), true)); /// ``` pub fn overflowing_sub(self, other: u128) -> (u128, bool) { let (lo, lo_borrow) = self.lo.overflowing_sub(other.lo); let (hi, hi_borrow_1) = self.hi.overflowing_sub(if lo_borrow { 1 } else { 0 }); let (hi, hi_borrow_2) = hi.overflowing_sub(other.hi); (u128::from_parts(hi, lo), hi_borrow_1 || hi_borrow_2) } /// Saturating integer addition. Computes `self + other`, saturating at the numeric bounds /// instead of overflowing. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::new(13).saturating_add(u128::new(7)), u128::new(20)); /// /// let huge_num = u128::from_str_radix("ccccccccbbbbbbbbaaaaaaaa99999999", 16).unwrap(); /// let also_big = u128::from_str_radix("5566778899aabbccddeeff0011223344", 16).unwrap(); /// assert_eq!(huge_num.saturating_add(also_big), u128::max_value()); /// ``` pub fn saturating_add(self, other: u128) -> u128 { self.checked_add(other).unwrap_or(MAX) } /// Saturating integer subtraction. Computes `self - other`, saturating at the numeric bounds /// instead of overflowing. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::new(91).saturating_sub(u128::new(13)), u128::new(78)); /// assert_eq!(u128::new(13).saturating_sub(u128::new(91)), u128::zero()); /// ``` pub fn saturating_sub(self, other: u128) -> u128 { if self <= other { ZERO } else { self.wrapping_sub(other) } } /// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary of the type. /// /// Since unsigned types do not have negative equivalents all applications of this function /// will wrap (except for `-0`). For values smaller than the corresponding signed type's /// maximum the result is the same as casting the corresponding signed value. Any larger values /// are equivalent to `MAX + 1 - (val - MAX - 1)`. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::zero().wrapping_neg(), u128::zero()); /// assert_eq!(u128::one().wrapping_neg(), u128::max_value()); /// assert_eq!(u128::max_value().wrapping_neg(), u128::one()); /// ``` pub fn wrapping_neg(self) -> u128 { ONE.wrapping_add(!self) } } forward_symmetric! { /// Checked integer addition. Computes `self + other`, returning `None` if overflow occurred. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::new(5).checked_add(u128::new(8)), Some(u128::new(13))); /// assert_eq!(u128::max_value().checked_add(u128::max_value()), None); /// ``` impl Add(add, checked_add, wrapping_add, overflowing_add) for u128 } forward_symmetric! { /// Checked integer subtraction. Computes `self - other`, returning `None` if underflow /// occurred. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::new(8).checked_sub(u128::new(5)), Some(u128::new(3))); /// assert_eq!(u128::new(5).checked_sub(u128::new(8)), None); /// ``` impl Sub(sub, checked_sub, wrapping_sub, overflowing_sub) for u128 } forward_assign!(AddAssign(add_assign, add) for u128); forward_assign!(SubAssign(sub_assign, sub) for u128); impl Neg for Wrapping { type Output = Self; fn neg(self) -> Self { Wrapping(self.0.wrapping_neg()) } } impl CheckedAdd for u128 { fn checked_add(&self, other: &Self) -> Option { Self::checked_add(*self, *other) } } impl CheckedSub for u128 { fn checked_sub(&self, other: &Self) -> Option { Self::checked_sub(*self, *other) } } impl Saturating for u128 { fn saturating_add(self, other: Self) -> Self { Self::saturating_add(self, other) } fn saturating_sub(self, other: Self) -> Self { Self::saturating_add(self, other) } } #[cfg(test)] mod add_sub_tests { use u128::{u128, ZERO, ONE, MAX}; #[test] fn test_add() { assert_eq!(u128::from_parts(23, 12) + u128::from_parts(78, 45), u128::from_parts(101, 57)); assert_eq!(u128::from_parts(0x4968eca20d32da8d, 0xaf40c0e1a806fa23) + u128::from_parts(0x71b6119ef76e4fe3, 0x0f58496c74669747), u128::from_parts(0xbb1efe4104a12a70, 0xbe990a4e1c6d916a)); assert_eq!(u128::from_parts(1, 0xffffffff_ffffffff) + u128::from_parts(0, 1), u128::from_parts(2, 0)); } #[test] fn test_wrapping_overflowing_add() { let a = u128::from_parts(0xfeae4b298df991ae, 0x21b6c7c3766908a7); let b = u128::from_parts(0x08a45eef16781327, 0xff1049ddf49ff8a8); let c = u128::from_parts(0x0752aa18a471a4d6, 0x20c711a16b09014f); assert_eq!(a.wrapping_add(b), c); assert_eq!(a.overflowing_add(b), (c, true)); assert_eq!(a.checked_add(b), None); assert_eq!(a.saturating_add(b), MAX); assert_eq!(ONE.wrapping_add(ONE), u128::new(2)); assert_eq!(ONE.overflowing_add(ONE), (u128::new(2), false)); assert_eq!(ONE.checked_add(ONE), Some(u128::new(2))); assert_eq!(ONE.saturating_add(ONE), u128::new(2)); assert_eq!(MAX.wrapping_add(ONE), ZERO); assert_eq!(MAX.overflowing_add(ONE), (ZERO, true)); assert_eq!(MAX.checked_add(ONE), None); assert_eq!(MAX.saturating_add(ONE), MAX); } #[test] #[should_panic(expected="arithmetic operation overflowed")] fn test_add_overflow_without_carry() { let _ = u128::from_parts(0x80000000_00000000, 0) + u128::from_parts(0x80000000_00000000, 0); } #[test] #[should_panic(expected="arithmetic operation overflowed")] fn test_add_overflow_with_carry() { let _ = MAX + ONE; } #[test] fn test_sub() { assert_eq!(u128::from_parts(78, 45) - u128::from_parts(23, 12), u128::from_parts(55, 33)); assert_eq!(u128::from_parts(0xfeae4b298df991ae, 0x21b6c7c3766908a7) - u128::from_parts(0x08a45eef16781327, 0xff1049ddf49ff8a8), u128::from_parts(0xf609ec3a77817e86, 0x22a67de581c90fff)); } #[test] fn test_wrapping_overflowing_sub() { let a = u128::from_parts(3565142335064920496, 15687467940602204387); let b = u128::from_parts(4442421226426414073, 17275749316209243331); let c = u128::from_parts(17569465182348058038, 16858462698102512672); let neg_c = c.wrapping_neg(); assert_eq!(a.wrapping_sub(b), c); assert_eq!(a.overflowing_sub(b), (c, true)); assert_eq!(a.checked_sub(b), None); assert_eq!(a.saturating_sub(b), ZERO); assert_eq!(b.wrapping_sub(a), neg_c); assert_eq!(b.overflowing_sub(a), (neg_c, false)); assert_eq!(b.checked_sub(a), Some(neg_c)); assert_eq!(b.saturating_sub(a), neg_c); assert_eq!(ONE.wrapping_sub(ONE), ZERO); assert_eq!(ONE.overflowing_sub(ONE), (ZERO, false)); assert_eq!(ONE.checked_sub(ONE), Some(ZERO)); assert_eq!(ONE.saturating_sub(ONE), ZERO); assert_eq!(ZERO.wrapping_sub(ONE), MAX); assert_eq!(ZERO.overflowing_sub(ONE), (MAX, true)); assert_eq!(ZERO.checked_sub(ONE), None); assert_eq!(ZERO.saturating_sub(ONE), ZERO); } #[test] #[should_panic(expected="arithmetic operation overflowed")] fn test_sub_overflow() { let _ = ZERO - ONE; } } //}}} //{{{ PartialOrd, Ord impl PartialOrd for u128 { fn partial_cmp(&self, other: &u128) -> Option { Some(self.cmp(other)) } } impl Ord for u128 { fn cmp(&self, other: &u128) -> Ordering { (self.hi, self.lo).cmp(&(other.hi, other.lo)) } } #[cfg(test)] mod cmp_tests { use u128::{u128, MAX, ZERO, ONE}; #[test] fn test_ord() { let a = ZERO; let b = ONE; let c = u128::from_parts(1, 0); let d = MAX; assert!(a < b); assert!(a <= b); assert!(c > b); assert!(c == c); assert!(d != c); assert!(d >= c); } } //}}} //{{{ Not, BitAnd, BitOr, BitXor impl Not for u128 { type Output = Self; fn not(self) -> Self { u128 { lo: !self.lo, hi: !self.hi } } } impl BitAnd for u128 { type Output = Self; fn bitand(self, other: Self) -> Self { u128 { lo: self.lo & other.lo, hi: self.hi & other.hi } } } impl BitOr for u128 { type Output = Self; fn bitor(self, other: Self) -> Self { u128 { lo: self.lo | other.lo, hi: self.hi | other.hi } } } impl BitXor for u128 { type Output = Self; fn bitxor(self, other: Self) -> Self { u128 { lo: self.lo ^ other.lo, hi: self.hi ^ other.hi } } } impl Not for Wrapping { type Output = Self; fn not(self) -> Self { Wrapping(!self.0) } } impl BitAnd for Wrapping { type Output = Self; fn bitand(self, other: Self) -> Self { Wrapping(self.0 & other.0) } } impl BitOr for Wrapping { type Output = Self; fn bitor(self, other: Self) -> Self { Wrapping(self.0 | other.0) } } impl BitXor for Wrapping { type Output = Self; fn bitxor(self, other: Self) -> Self { Wrapping(self.0 ^ other.0) } } forward_assign!(BitAndAssign(bitand_assign, bitand) for u128); forward_assign!(BitOrAssign(bitor_assign, bitor) for u128); forward_assign!(BitXorAssign(bitxor_assign, bitxor) for u128); #[cfg(test)] mod bitwise_tests { use u128::u128; #[test] fn test_not() { assert_eq!(u128::from_parts(0x491d3b2d80d706a6, 0x1eb41c5d2ad1a379), !u128::from_parts(0xb6e2c4d27f28f959, 0xe14be3a2d52e5c86)); } #[test] fn test_bit_and() { assert_eq!(u128::from_parts(0x8aff8559dc82aa91, 0x8bbf525fb0c5cd79) & u128::from_parts(0x8dcecc950badb6f1, 0xb26ab6ca714bce40), u128::from_parts(0x88ce84110880a291, 0x822a124a3041cc40)); } #[test] fn test_bit_or() { assert_eq!(u128::from_parts(0xe3b7e0ae1e8f8beb, 0x5c76dd080dd43e30) | u128::from_parts(0x35591b16599e2ece, 0x2e2957ca426d7b07), u128::from_parts(0xf7fffbbe5f9fafef, 0x7e7fdfca4ffd7f37)); } #[test] fn test_bit_xor() { assert_eq!(u128::from_parts(0x50b17617e8f6ee49, 0x1b06f037a9187c71) ^ u128::from_parts(0x206f313ea29823bd, 0x66e0bc7aa198785a), u128::from_parts(0x70de47294a6ecdf4, 0x7de64c4d0880042b)); } } //}}} //{{{ Shl, Shr impl u128 { /// Panic-free bitwise shift-left; yields `self << (shift % 128)`. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::new(7).wrapping_shl(66), u128::from_parts(28, 0)); /// assert_eq!(u128::new(7).wrapping_shl(128), u128::new(7)); /// assert_eq!(u128::new(7).wrapping_shl(129), u128::new(14)); /// ``` pub fn wrapping_shl(self, shift: u32) -> u128 { let lo = self.lo; let hi = self.hi; let (lo, hi) = if (shift & 64) != 0 { (0, lo.wrapping_shl(shift & 63)) } else { let new_lo = lo.wrapping_shl(shift); let mut new_hi = hi.wrapping_shl(shift); if (shift & 127) != 0 { new_hi |= lo.wrapping_shr(64u32.wrapping_sub(shift)); } (new_lo, new_hi) }; u128::from_parts(hi, lo) } /// Panic-free bitwsie shift-right; yields `self >> (shift % 128)`. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::max_value().wrapping_shr(66), u128::new(0x3fffffffffffffff)); /// assert_eq!(u128::new(7).wrapping_shr(128), u128::new(7)); /// assert_eq!(u128::new(7).wrapping_shr(129), u128::new(3)); /// ``` pub fn wrapping_shr(self, shift: u32) -> u128 { let lo = self.lo; let hi = self.hi; let (hi, lo) = if (shift & 64) != 0 { (0, hi.wrapping_shr(shift & 63)) } else { let new_hi = hi.wrapping_shr(shift); let mut new_lo = lo.wrapping_shr(shift); if (shift & 127) != 0 { new_lo |= hi.wrapping_shl(64u32.wrapping_sub(shift)); } (new_hi, new_lo) }; u128::from_parts(hi, lo) } /// Shifts `self` left by `other` bits. /// /// Returns a tuple of the shifted version of `self` along with a boolean indicating whether /// the shift value was larger than or equal to the number of bits (128). If the shift value is /// too large, then value is masked by `0x7f`, and this value is then used to perform the shift. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::new(7).overflowing_shl(66), (u128::from_parts(28, 0), false)); /// assert_eq!(u128::new(7).overflowing_shl(128), (u128::new(7), true)); /// assert_eq!(u128::new(7).overflowing_shl(129), (u128::new(14), true)); /// ``` pub fn overflowing_shl(self, other: u32) -> (u128, bool) { (self.wrapping_shl(other), other >= 128) } /// Shifts `self` right by `other` bits. /// /// Returns a tuple of the shifted version of `self` along with a boolean indicating whether /// the shift value was larger than or equal to the number of bits (128). If the shift value is /// too large, then value is masked by `0x7f`, and this value is then used to perform the shift. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::max_value().overflowing_shr(66), (u128::new(0x3fffffffffffffff), false)); /// assert_eq!(u128::new(7).overflowing_shr(128), (u128::new(7), true)); /// assert_eq!(u128::new(7).overflowing_shr(129), (u128::new(3), true)); /// ``` pub fn overflowing_shr(self, other: u32) -> (u128, bool) { (self.wrapping_shr(other), other >= 128) } } forward_shift! { /// Checked shift left. Computes `self << other`, returning `None` if the shift is larger than /// or equal to the number of bits in `self` (128). /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::new(7).checked_shl(66), Some(u128::from_parts(28, 0))); /// assert_eq!(u128::new(7).checked_shl(128), None); /// assert_eq!(u128::new(7).checked_shl(129), None); /// ``` impl Shl(shl, checked_shl, wrapping_shl, overflowing_shl) for u128 } forward_shift! { /// Checked shift right. Computes `self >> other`, returning `None` if the shift is larger than /// or equal to the number of bits in `self` (128). /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::max_value().checked_shr(66), Some(u128::new(0x3fffffffffffffff))); /// assert_eq!(u128::new(7).checked_shr(128), None); /// assert_eq!(u128::new(7).checked_shr(129), None); /// ``` impl Shr(shr, checked_shr, wrapping_shr, overflowing_shr) for u128 } forward_assign!(ShlAssign(shl_assign, shl) for u128); forward_assign!(ShrAssign(shr_assign, shr) for u128); #[cfg(test)] mod shift_tests { use u128::u128; #[test] fn test_shl() { assert_eq!(u128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152) << 0, u128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152)); assert_eq!(u128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152) << 1, u128::from_parts(0x3cb8f00361caebee, 0xa7e13b58b651e2a4)); assert_eq!(u128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152) << 64, u128::from_parts(0x53f09dac5b28f152, 0x0)); assert_eq!(u128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152) << 120, u128::from_parts(0x5200000000000000, 0x0)); assert_eq!(u128::from_parts(0xf8025363ddcd51d8, 0x509d78e4a3008bcd) << 0, u128::from_parts(0xf8025363ddcd51d8, 0x509d78e4a3008bcd)); assert_eq!(u128::from_parts(0xf8025363ddcd51d8, 0x509d78e4a3008bcd) << 1, u128::from_parts(0xf004a6c7bb9aa3b0, 0xa13af1c94601179a)); assert_eq!(u128::from_parts(0xf8025363ddcd51d8, 0x509d78e4a3008bcd) << 64, u128::from_parts(0x509d78e4a3008bcd, 0x0)); assert_eq!(u128::from_parts(0xf8025363ddcd51d8, 0x509d78e4a3008bcd) << 120, u128::from_parts(0xcd00000000000000, 0x0)); } #[test] fn test_shr() { assert_eq!(u128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152) >> 0, u128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152)); assert_eq!(u128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152) >> 1, u128::from_parts(0xf2e3c00d872bafb, 0xa9f84ed62d9478a9)); assert_eq!(u128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152) >> 64, u128::from_parts(0x0, 0x1e5c7801b0e575f7)); assert_eq!(u128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152) >> 120, u128::from_parts(0x0, 0x1e)); assert_eq!(u128::from_parts(0xf8025363ddcd51d8, 0x509d78e4a3008bcd) >> 0, u128::from_parts(0xf8025363ddcd51d8, 0x509d78e4a3008bcd)); assert_eq!(u128::from_parts(0xf8025363ddcd51d8, 0x509d78e4a3008bcd) >> 1, u128::from_parts(0x7c0129b1eee6a8ec, 0x284ebc72518045e6)); assert_eq!(u128::from_parts(0xf8025363ddcd51d8, 0x509d78e4a3008bcd) >> 64, u128::from_parts(0x0, 0xf8025363ddcd51d8)); assert_eq!(u128::from_parts(0xf8025363ddcd51d8, 0x509d78e4a3008bcd) >> 120, u128::from_parts(0x0, 0xf8)); } #[test] #[should_panic(expected="shift operation overflowed")] fn test_shl_overflow() { let _ = u128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152) << 128; } #[test] #[should_panic(expected="shift operation overflowed")] fn test_shr_overflow() { let _ = u128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152) >> 256; } } #[cfg(all(test, extprim_channel="unstable"))] mod shift_bench { use u128::u128; use test::{Bencher, black_box}; // randomize shift range to avoid possible branch prediction effect. const BENCH_SHIFTS: &'static [u32] = &[ 77, 45, 57, 7, 34, 75, 38, 89, 89, 66, 16, 111, 66, 123, 14, 80, 94, 43, 46, 86, 121, 31, 123, 33, 23, 57, 50, 28, 26, 46, 8, 88, 74, 55, 108, 127, 1, 70, 73, 2, 1, 45, 36, 96, 124, 124, 91, 63, 25, 94, 8, 68, 41, 127, 107, 10, 111, 98, 97, 72, 78, 10, 125, 17, 62, 3, 65, 67, 13, 41, 68, 109, 23, 100, 98, 16, 78, 13, 0, 63, 107, 64, 13, 23, 69, 73, 2, 38, 16, 9, 124, 120, 39, 119, 3, 15, 25, 11, 84, 102, 69, 58, 39, 116, 66, 87, 111, 17, 11, 29, 35, 123, 23, 38, 43, 85, 32, 7, 34, 84, 27, 35, 122, 64, 33, 83, 78, 105, 31, 5, 58, 25, 21, 34, 15, 94, 10, 23, 48, 89, 23, 99, 110, 105, 32, 7, 116, 31, 10, 14, 22, 84, 40, 57, 7, 35, 8, 95, 121, 66, 95, 103, 26, 62, 24, 36, 48, 58, 122, 66, 37, 56, 35, 87, 36, 41, 75, 37, 25, 40, 60, 39, 94, 18, 33, 113, 34, 66, 34, 34, 88, 95, 81, 115, 10, 67, 33, 34, 23, 53, 10, 119, 54, 107, 37, 17, 85, 42, 83, 85, 102, 104, 94, 24, 97, 104, 93, 9, 95, 75, 41, 112, 64, 63, 72, 3, 26, 65, 103, 88, 121, 105, 98, 82, 89, 30, 37, 64, 68, 41, 93, 57, 105, 100, 108, 102, 44, 17, 61, 72, 33, 126, 73, 105, 0, 119, 97, 28, 9, 101, 44, ]; #[bench] fn bench_shl(bencher: &mut Bencher) { let number = u128::from_parts(9741918172058430398, 3937562729638942691); bencher.iter(|| { for i in BENCH_SHIFTS { black_box(number.wrapping_shl(*i)); } }); } #[bench] fn bench_shr(bencher: &mut Bencher) { let number = u128::from_parts(9741918172058430398, 3937562729638942691); bencher.iter(|| { for i in BENCH_SHIFTS { black_box(number.wrapping_shr(*i)); } }); } } //}}} //{{{ Mul /// Computes the product of two unsigned 64-bit integers. Returns a 128-bit /// integer. #[cfg(not(all(target_arch="x86_64", extprim_channel="unstable")))] fn u64_long_mul(left: u64, right: u64) -> u128 { let a = left >> 32; let b = left & 0xffffffff; let c = right >> 32; let d = right & 0xffffffff; let lo = b.wrapping_mul(d); let (mid, carry) = a.wrapping_mul(d).overflowing_add(b.wrapping_mul(c)); let hi = a.wrapping_mul(c).wrapping_add(if carry { 1 << 32 } else { 0 }); u128::from_parts(hi, lo).wrapping_add(u128::from_parts(mid >> 32, mid << 32)) } #[cfg(all(target_arch="x86_64", extprim_channel="unstable"))] fn u64_long_mul(left: u64, right: u64) -> u128 { unsafe { let mut result: u128 = ::std::mem::uninitialized(); llvm_asm!(" movq $2, %rax mulq $3 movq %rax, $0 movq %rdx, $1 " : "=r"(result.lo), "=r"(result.hi) : "r"(left), "r"(right) : "rax", "rdx"); result } } impl u128 { /// Wrapping (modular) multiplication. Computes `self * other`, wrapping around at the boundary /// of the type. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::new(6).wrapping_mul(u128::new(9)), u128::new(54)); /// /// let a = u128::max_value() - u128::new(2); /// let b = u128::max_value() - u128::new(4); /// assert_eq!(a.wrapping_mul(b), u128::new(15)); /// ``` pub fn wrapping_mul(self, other: u128) -> u128 { let a = self.hi; let b = self.lo; let c = other.hi; let d = other.lo; let mut low = u64_long_mul(b, d); let ad = a.wrapping_mul(d); let bc = b.wrapping_mul(c); low.hi = low.hi.wrapping_add(ad).wrapping_add(bc); low } /// Calculates the multiplication of `self` and `other`. /// /// Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic /// overflow would occur. If an overflow would have occurred then the wrapped value is returned. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::new(6).overflowing_mul(u128::new(9)), (u128::new(54), false)); /// /// let a = u128::max_value() - u128::new(2); /// let b = u128::max_value() - u128::new(4); /// assert_eq!(a.overflowing_mul(b), (u128::new(15), true)); /// ``` pub fn overflowing_mul(self, other: u128) -> (u128, bool) { let a = self.hi; let b = self.lo; let c = other.hi; let d = other.lo; let (hi, hi_overflow_mul) = match (a, c) { (a, 0) => a.overflowing_mul(d), (0, c) => c.overflowing_mul(b), (a, c) => (a.wrapping_mul(d).wrapping_add(c.wrapping_mul(b)), true), }; let mut low = u64_long_mul(b, d); let (hi, hi_overflow_add) = low.hi.overflowing_add(hi); low.hi = hi; (low, hi_overflow_mul || hi_overflow_add) } /// Saturating integer multiplication. Computes `self * other`, saturating at the numeric /// bounds instead of overflowing. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::new(6).saturating_mul(u128::new(9)), u128::new(54)); /// /// let a = u128::max_value() - u128::new(2); /// let b = u128::max_value() - u128::new(4); /// assert_eq!(a.saturating_mul(b), u128::max_value()); /// ``` pub fn saturating_mul(self, other: u128) -> u128 { self.checked_mul(other).unwrap_or(MAX) } /// Wrapping (modular) multiplication with a 64-bit number. Computes `self * other`, wrapping /// around at the boundary of the type. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::new(6).wrapping_mul_64(9), u128::new(54)); /// /// let a = u128::max_value() - u128::new(2); /// assert_eq!(a.wrapping_mul_64(7), u128::max_value() - u128::new(20)); /// ``` pub fn wrapping_mul_64(self, other: u64) -> u128 { let mut low = u64_long_mul(self.lo, other); low.hi = low.hi.wrapping_add(self.hi.wrapping_mul(other)); low } /// Calculates the multiplication of `self` and `other` with a 64-bit number. /// /// Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic /// overflow would occur. If an overflow would have occurred then the wrapped value is returned. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::new(6).overflowing_mul_64(9), (u128::new(54), false)); /// /// let a = u128::max_value() - u128::new(2); /// assert_eq!(a.overflowing_mul_64(7), (u128::max_value() - u128::new(20), true)); /// ``` pub fn overflowing_mul_64(self, other: u64) -> (u128, bool) { let mut low = u64_long_mul(self.lo, other); let (hi, hi_overflow_mul) = self.hi.overflowing_mul(other); let (hi, hi_overflow_add) = low.hi.overflowing_add(hi); low.hi = hi; (low, hi_overflow_mul || hi_overflow_add) } /// Saturating integer multiplication with a 64-bit number. Computes `self * other`, saturating /// at the numeric bounds instead of overflowing. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::new(6).saturating_mul_64(9), u128::new(54)); /// /// let a = u128::max_value() - u128::new(2); /// assert_eq!(a.saturating_mul_64(7), u128::max_value()); /// ``` pub fn saturating_mul_64(self, other: u64) -> u128 { self.checked_mul_64(other).unwrap_or(MAX) } } forward_symmetric!( /// Checked integer multiplication. Computes `self * other`, returning `None` if underflow or /// overflow occurred. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::new(6).checked_mul(u128::new(9)), Some(u128::new(54))); /// /// let a = u128::max_value() - u128::new(2); /// let b = u128::max_value() - u128::new(4); /// assert_eq!(a.checked_mul(b), None); /// ``` impl Mul(mul, checked_mul, wrapping_mul, overflowing_mul) for u128 ); forward_symmetric!( /// Checked integer multiplication with a 64-bit number. Computes `self * other`, returning /// `None` if underflow or overflow occurred. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::new(6).checked_mul_64(9), Some(u128::new(54))); /// /// let a = u128::max_value() - u128::new(2); /// assert_eq!(a.checked_mul_64(7), None); /// ``` impl Mul(mul, checked_mul_64, wrapping_mul_64, overflowing_mul_64) for u128 ); forward_assign!(MulAssign(mul_assign, mul) for u128); forward_assign!(MulAssign(mul_assign, mul) for u128); impl Mul for u64 { type Output = u128; fn mul(self, other: u128) -> u128 { other * self } } impl Mul> for Wrapping { type Output = Wrapping; fn mul(self, other: Wrapping) -> Wrapping { other * self } } impl CheckedMul for u128 { fn checked_mul(&self, other: &Self) -> Option { Self::checked_mul(*self, *other) } } #[cfg(test)] mod mul_tests { use std::u64; use u128::{u128, u64_long_mul, ZERO, ONE, MAX}; #[test] fn test_u64_long_mul() { assert_eq!(u128::from_parts(0xaaa4d56f5b2f577, 0x916fb81166049cc3), u64_long_mul(6263979403966582069, 2263184174907185431)); assert_eq!(u128::new(10), u64_long_mul(2, 5)); assert_eq!(u128::from_parts(0xfffffffffffffffe, 1), u64_long_mul(u64::MAX, u64::MAX)); } #[test] fn test_mul() { assert_eq!(u128::new(6263979403966582069) * u128::new(2263184174907185431), u128::from_parts(0xaaa4d56f5b2f577, 0x916fb81166049cc3)); assert_eq!(u128::from_parts(47984616521, 3126587552720577884) * u128::new(323057793), u128::from_parts(15501804311280354074, 13195922651658531676)); assert_eq!(ONE * ONE, ONE); assert_eq!(ZERO * ONE, ZERO); assert_eq!(ZERO * ZERO, ZERO); assert_eq!(MAX * ONE, MAX); assert_eq!(MAX * ZERO, ZERO); } #[test] #[should_panic(expected="arithmetic operation overflowed")] fn test_mul_overflow_10_10() { let _ = u128::from_parts(1, 0) * u128::from_parts(1, 0); } #[test] #[should_panic(expected="arithmetic operation overflowed")] fn test_mul_overflow_80_80() { let _ = u128::from_parts(0x80000000_00000000, 0) * u128::from_parts(0x80000000_00000000, 0); } #[test] #[should_panic(expected="arithmetic operation overflowed")] fn test_mul_overflow_max_max() { let _ = MAX * MAX; } #[test] #[should_panic(expected="arithmetic operation overflowed")] fn test_mul_overflow_max_2() { let _ = MAX * u128::new(2); } #[test] fn test_mul_64() { assert_eq!(u128::new(6263979403966582069) * 2263184174907185431u64, u128::from_parts(0xaaa4d56f5b2f577, 0x916fb81166049cc3)); assert_eq!(u128::from_parts(47984616521, 3126587552720577884) * 323057793u64, u128::from_parts(15501804311280354074, 13195922651658531676)); } #[test] #[should_panic(expected="arithmetic operation overflowed")] fn test_mul_64_overflow_max_2() { let _ = MAX * 2u64; } #[test] fn test_wrapping_overflowing_mul() { let a = u128::from_parts(0xc1b27561c3e63bad, 0x53b0ad364ee597dc); let b = u128::from_parts(0x50f5d9a72dd704f3, 0x5ecee7a38577df37); let c = u128::from_parts(0xf5651b2427082a5e, 0x0052af17d5e04444); assert_eq!(a.wrapping_mul(b), c); assert_eq!(a.overflowing_mul(b), (c, true)); assert_eq!(a.checked_mul(b), None); assert_eq!(a.saturating_mul(b), MAX); let a = u128::from_parts(15266745824950921091, 7823906177946456204); let b = u128::new(8527117857836076447); let c = u128::from_parts(15018621813448572278, 1743241062838166260); assert_eq!(a.wrapping_mul(b), c); assert_eq!(a.overflowing_mul(b), (c, true)); assert_eq!(a.checked_mul(b), None); assert_eq!(a.saturating_mul(b), MAX); assert_eq!(b.wrapping_mul(a), c); assert_eq!(b.overflowing_mul(a), (c, true)); assert_eq!(b.checked_mul(a), None); assert_eq!(b.saturating_mul(a), MAX); assert_eq!(ONE.wrapping_mul(ONE), ONE); assert_eq!(ONE.overflowing_mul(ONE), (ONE, false)); assert_eq!(ONE.checked_mul(ONE), Some(ONE)); assert_eq!(ONE.saturating_mul(ONE), ONE); assert_eq!(MAX.wrapping_mul(ONE), MAX); assert_eq!(MAX.overflowing_mul(ONE), (MAX, false)); assert_eq!(MAX.checked_mul(ONE), Some(MAX)); assert_eq!(MAX.saturating_mul(ONE), MAX); } } #[cfg(all(test, extprim_channel="unstable"))] mod mul_bench { use u128::{u128, u64_long_mul}; use test::{Bencher, black_box}; const BENCH_LONG_MUL: &'static [u64] = &[ 11738324199100816218, 3625949024665125869, 11861868675607089770, 0, 6847039601565126724, 5990205122755364850, 9702538440775714705, 1, 10515012783906113246, 124429589608972701, 16050761648142104263, 2, 5351676941151834955, 6016449362915734881, 2914632825655711546, 65536, 7683069626972557929, 2782994233456154833, 4294967296, 281474976710656, ]; const BENCH_MUL: &'static [u128] = &[ u128 { lo: 13698662153774026983, hi: 11359772643830585857 }, u128 { lo: 2369395906159065085, hi: 9392107235602601877 }, u128 { lo: 1316137604845241724, hi: 3387495557620150388 }, u128 { lo: 4377298216549927656, hi: 4459898349916441418 }, u128 { lo: 0, hi: 1 }, u128 { lo: 4002933201893849592, hi: 16874811549516268507 }, u128 { lo: 13499130554936672837, hi: 7450290244389993204 }, u128 { lo: 14853481505607028172, hi: 9904715859096779071 }, u128 { lo: 5904460318883801886, hi: 1039448585925084376 }, u128 { lo: 2, hi: 0 }, u128 { lo: 16506484467360819289, hi: 14931546970023365577 }, u128 { lo: 14721531095705410753, hi: 14699503783417097848 }, u128 { lo: 10292416800274947511, hi: 14856377574170601940 }, u128 { lo: 17255829222190888162, hi: 11606899158687852303 }, u128 { lo: 11087763062048402971, hi: 14746910067372570493 }, u128 { lo: 4294967296, hi: 4294967296 }, u128 { lo: 11389837759419328446, hi: 14469025657316200340 }, u128 { lo: 18363409626181059962, hi: 2420940920506351250 }, u128 { lo: 18224881384786225007, hi: 15381587162621094041 }, u128 { lo: 1727909608960628680, hi: 8964631137233999389 } ]; #[bench] fn bench_u64_long_mul(bencher: &mut Bencher) { bencher.iter(|| { for a in BENCH_LONG_MUL { for b in BENCH_LONG_MUL.iter() { black_box(u64_long_mul(*a, *b)); } } }); } #[bench] fn bench_mul(bencher: &mut Bencher) { bencher.iter(|| { for a in BENCH_MUL { for b in BENCH_MUL { black_box(a.wrapping_mul(*b)); } } }); } #[bench] fn bench_mul_64(bencher: &mut Bencher) { bencher.iter(|| { for a in BENCH_MUL { for b in BENCH_MUL { black_box(a.wrapping_mul_64(b.lo)); } } }); } } //}}} //{{{ Div, Rem impl u128 { /// Wrapping (modular) division. Computes `self / other`. Wrapped division on unsigned types is /// just normal division. There's no way wrapping could ever happen. This function exists, so /// that all operations are accounted for in the wrapping operations. /// /// # Panics /// /// This function will panic if `other` is 0. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::new(100).wrapping_div(u128::new(8)), u128::new(12)); /// ``` pub fn wrapping_div(self, other: u128) -> u128 { self.checked_div(other) .unwrap_or_else(|| panic!("attempted to divide by zero")) } /// Wrapping (modular) remainder. Computes `self % other`. Wrapped remainder calculation on /// unsigned types is just the regular remainder calculation. There's no way wrapping could /// ever happen. This function exists, so that all operations are accounted for in the wrapping /// operations. /// /// # Panics /// /// This function will panic if `other` is 0. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::new(100).wrapping_rem(u128::new(8)), u128::new(4)); /// ``` pub fn wrapping_rem(self, other: u128) -> u128 { self.checked_rem(other) .unwrap_or_else(|| panic!("attempted remainder with a divisor of zero")) } /// Calculates the divisor when `self` is divided by `other`. /// /// Returns a tuple of the divisor along with a boolean indicating whether /// an arithmetic overflow would occur. Note that for unsigned integers /// overflow never occurs, so the second value is always `false`. /// /// # Panics /// /// This function will panic if `other` is 0. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::new(100).overflowing_div(u128::new(8)), (u128::new(12), false)); /// ``` pub fn overflowing_div(self, other: u128) -> (u128, bool) { (self.wrapping_div(other), false) } /// Calculates the remainder when `self` is divided by `other`. /// /// Returns a tuple of the remainder along with a boolean indicating whether /// an arithmetic overflow would occur. Note that for unsigned integers /// overflow never occurs, so the second value is always `false`. /// /// # Panics /// /// This function will panic if `other` is 0. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::new(100).overflowing_rem(u128::new(8)), (u128::new(4), false)); /// ``` pub fn overflowing_rem(self, other: u128) -> (u128, bool) { (self.wrapping_rem(other), false) } /// Checked integer division. Computes `self / other`, returning `None` if `other == 0`. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::new(100).checked_div(u128::new(8)), Some(u128::new(12))); /// assert_eq!(u128::new(100).checked_div(u128::zero()), None); /// ``` pub fn checked_div(self, other: u128) -> Option { if other == ZERO { None } else { Some(udiv128(self, other)) } } /// Checked integer remainder. Computes `self % other`, returning `None` if `other == 0`. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::new(100).checked_rem(u128::new(8)), Some(u128::new(4))); /// assert_eq!(u128::new(100).checked_rem(u128::zero()), None); /// ``` pub fn checked_rem(self, other: u128) -> Option { if other == ZERO { None } else { Some(umod128(self, other)) } } } impl Div for u128 { type Output = Self; fn div(self, other: Self) -> Self { self.wrapping_div(other) } } impl Rem for u128 { type Output = Self; fn rem(self, other: Self) -> Self { self.wrapping_rem(other) } } impl Div for Wrapping { type Output = Self; fn div(self, other: Self) -> Self { Wrapping(self.0.wrapping_div(other.0)) } } impl Rem for Wrapping { type Output = Self; fn rem(self, other: Self) -> Self { Wrapping(self.0.wrapping_rem(other.0)) } } forward_assign!(DivAssign(div_assign, div) for u128); forward_assign!(RemAssign(rem_assign, rem) for u128); impl CheckedDiv for u128 { fn checked_div(&self, other: &Self) -> Option { Self::checked_div(*self, *other) } } /// Computes the divisor and remainder simultaneously. Returns `(a/b, a%b)`. /// /// Unlike the primitive types, calling this is likely faster than calling `a/b` and `a%b` /// separately. /// /// # Panics /// /// This function will panic if `denominator` is 0. /// /// # Examples /// /// ```rust /// use extprim::u128::{div_rem, u128}; /// /// assert_eq!(div_rem(u128::new(100), u128::new(8)), (u128::new(12), u128::new(4))); /// ``` pub fn div_rem(numerator: u128, denominator: u128) -> (u128, u128) { if denominator == ZERO { panic!("attempted to divide by zero"); } else { udivmod128(numerator, denominator) } } #[cfg(test)] mod div_rem_tests { use u128::{u128, ONE, ZERO, div_rem}; #[test] fn test_div() { assert_eq!(u128::from_parts(9071183389512669386, 9598842501673620991) / u128::new(6108228772930395530), u128::from_parts(1, 8948071126007945734)); assert_eq!(u128::from_parts(3450248868015763521, 12952733755616785885) / u128::new(10250320568692650382), u128::new(6209157794858157762)); assert_eq!(u128::from_parts(10328265298226767242, 6197012475834382470) / u128::from_parts(3051664430350890703, 4511783754636171344), u128::new(3)); // Test case copied from https://github.com/rust-lang/rust/issues/41228 assert_eq!(u128::from_parts(3, 1) / u128::from_parts(3, 0), ONE); } #[test] #[should_panic(expected="attempted to divide by zero")] fn test_div_by_zero() { let _ = ONE / ZERO; } #[test] fn test_rem() { assert_eq!(u128::from_parts(9071183389512669386, 9598842501673620991) % u128::new(6108228772930395530), u128::new(5166992697756803267)); assert_eq!(u128::from_parts(3450248868015763521, 12952733755616785885) % u128::new(10250320568692650382), u128::new(5507621082750620737)); assert_eq!(u128::from_parts(10328265298226767242, 6197012475834382470) % u128::from_parts(3051664430350890703, 4511783754636171344), u128::from_parts(1173272007174095132, 11108405285635420054)); } #[test] #[should_panic(expected="attempted remainder with a divisor of zero")] fn test_rem_by_zero() { let _ = ONE % ZERO; } #[test] fn test_div_rem() { assert_eq!(div_rem(u128::from_parts(10328265298226767242, 6197012475834382470), u128::from_parts(3051664430350890703, 4511783754636171344)), (u128::new(3), u128::from_parts(1173272007174095132, 11108405285635420054))); } } //}}} //{{{ Casting fn ldexp(base: f64, exp: u32) -> f64 { // TODO the built-in `ldexp` is deprecated. Find alternate native implementation instead. base * 2.0 * (1u64 << (exp-1)) as f64 } impl ToPrimitive for u128 { fn to_i64(&self) -> Option { if self.hi != 0 { None } else { self.lo.to_i64() } } fn to_u64(&self) -> Option { if self.hi != 0 { None } else { Some(self.lo) } } fn to_f64(&self) -> Option { if self.hi != 0 { let shift_size = 64 - self.hi.leading_zeros(); let truncated = (*self >> shift_size).lo as f64; Some(ldexp(truncated, shift_size)) } else { self.lo.to_f64() } } #[cfg(extprim_has_stable_i128)] fn to_i128(&self) -> Option { if self.hi < 0x80000000_00000000 { Some(self.as_built_in() as I128) } else { None } } #[cfg(extprim_has_stable_i128)] fn to_u128(&self) -> Option { Some(self.as_built_in()) } } impl FromPrimitive for u128 { fn from_u64(n: u64) -> Option { ToExtraPrimitive::to_u128(&n) } fn from_i64(n: i64) -> Option { ToExtraPrimitive::to_u128(&n) } fn from_f64(n: f64) -> Option { ToExtraPrimitive::to_u128(&n) } } impl ToExtraPrimitive for u128 { fn to_u128(&self) -> Option { Some(*self) } fn to_i128(&self) -> Option { if self.hi >= 0x8000_0000_0000_0000 { None } else { Some(i128(*self)) } } } impl From for u128 { fn from(arg: u8) -> Self { u128::new(arg as u64) } } impl From for u128 { fn from(arg: u16) -> Self { u128::new(arg as u64) } } impl From for u128 { fn from(arg: u32) -> Self { u128::new(arg as u64) } } impl From for u128 { fn from(arg: u64) -> Self { u128::new(arg) } } #[cfg(extprim_has_stable_i128)] impl From for u128 { fn from(arg: U128) -> Self { u128::from_built_in(arg) } } #[cfg(test)] mod conv_tests { use u128::{u128, MAX}; use num_traits::ToPrimitive; #[test] fn test_u128_to_f64() { assert_eq!(u128::new(0).to_f64(), Some(0.0f64)); assert_eq!(u128::new(1).to_f64(), Some(1.0f64)); assert_eq!(u128::new(2).to_f64(), Some(2.0f64)); assert_eq!(MAX.to_f64(), Some(340282366920938463463374607431768211455.0f64)); } #[test] #[cfg(extprim_has_stable_i128)] fn test_builtin_u128_to_u128() { assert_eq!(u128::from_built_in(0x35d2c4473082b8c1_8b704240ca1021b8u128), u128::from_parts(0x35d2c4473082b8c1, 0x8b704240ca1021b8)); assert_eq!(u128::from_parts(0x35d2c4473082b8c1, 0x8b704240ca1021b8).as_built_in(), 0x35d2c4473082b8c1_8b704240ca1021b8u128); } } //}}} //{{{ Constants impl u128 { /// Returns the smallest unsigned 128-bit integer (0). pub fn min_value() -> u128 { MIN } /// Returns the largest unsigned 128-bit integer /// (`340_282_366_920_938_463_463_374_607_431_768_211_455`). pub fn max_value() -> u128 { MAX } /// Returns the constant 0. pub fn zero() -> u128 { ZERO } /// Returns the constant 1. pub fn one() -> u128 { ONE } } impl Bounded for u128 { fn min_value() -> Self { MIN } fn max_value() -> Self { MAX } } impl Zero for u128 { fn zero() -> Self { ZERO } fn is_zero(&self) -> bool { *self == ZERO } } impl One for u128 { fn one() -> Self { ONE } } //}}} //{{{ PrimInt impl u128 { /// Returns the number of ones in the binary representation of `self`. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// let n = u128::from_str_radix("6f32f1ef8b18a2bc3cea59789c79d441", 16).unwrap(); /// assert_eq!(n.count_ones(), 67); /// ``` pub fn count_ones(self) -> u32 { self.lo.count_ones() + self.hi.count_ones() } /// Returns the number of zeros in the binary representation of `self` (including leading zeros). /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// let n = u128::from_str_radix("6f32f1ef8b18a2bc3cea59789c79d441", 16).unwrap(); /// assert_eq!(n.count_zeros(), 61); /// ``` pub fn count_zeros(self) -> u32 { self.lo.count_zeros() + self.hi.count_zeros() } /// Returns the number of leading zeros in the binary representation of `self`. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::zero().leading_zeros(), 128); /// assert_eq!(u128::one().leading_zeros(), 127); /// assert_eq!(u128::max_value().leading_zeros(), 0); /// assert_eq!((u128::one() << 24u32).leading_zeros(), 103); /// assert_eq!((u128::one() << 124u32).leading_zeros(), 3); /// ``` pub fn leading_zeros(self) -> u32 { if self.hi == 0 { 64 + self.lo.leading_zeros() } else { self.hi.leading_zeros() } } /// Returns the number of trailing zeros in the binary representation of `self`. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// assert_eq!(u128::zero().trailing_zeros(), 128); /// assert_eq!(u128::one().trailing_zeros(), 0); /// assert_eq!((u128::one() << 24u32).trailing_zeros(), 24); /// assert_eq!((u128::one() << 124u32).trailing_zeros(), 124); /// ``` pub fn trailing_zeros(self) -> u32 { if self.lo == 0 { 64 + self.hi.trailing_zeros() } else { self.lo.trailing_zeros() } } /// Shifts the bits to the left by a specified amount, `shift`, wrapping the truncated bits to /// the end of the resulting integer. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// let a = u128::from_str_radix("d0cf4b50cfe20765fff4b4e3f741cf6d", 16).unwrap(); /// let b = u128::from_str_radix("19e96a19fc40ecbffe969c7ee839edba", 16).unwrap(); /// assert_eq!(a.rotate_left(5), b); /// ``` pub fn rotate_left(self, shift: u32) -> Self { let rotated = match shift & 63 { 0 => self, n => u128 { lo: self.lo << n | self.hi >> 64u32.wrapping_sub(n), hi: self.hi << n | self.lo >> 64u32.wrapping_sub(n), }, }; if shift & 64 == 0 { rotated } else { u128 { lo: rotated.hi, hi: rotated.lo } } } /// Shifts the bits to the right by a specified amount, `shift`, wrapping the truncated bits to /// the beginning of the resulting integer. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// let a = u128::from_str_radix("d0cf4b50cfe20765fff4b4e3f741cf6d", 16).unwrap(); /// let b = u128::from_str_radix("6e867a5a867f103b2fffa5a71fba0e7b", 16).unwrap(); /// assert_eq!(a.rotate_right(5), b); /// ``` pub fn rotate_right(self, shift: u32) -> Self { self.rotate_left(128u32.wrapping_sub(shift)) } /// Reverses the byte order of the integer. /// /// # Examples /// /// ```rust /// use extprim::u128::u128; /// /// let a = u128::from_str_radix("0123456789abcdef1112223334445556", 16).unwrap(); /// let b = u128::from_str_radix("5655443433221211efcdab8967452301", 16).unwrap(); /// assert_eq!(a.swap_bytes(), b); /// ``` pub fn swap_bytes(self) -> Self { u128 { lo: self.hi.swap_bytes(), hi: self.lo.swap_bytes() } } /// Converts an integer from big endian to the target's endianness. /// /// On big endian this is a no-op. On little endian the bytes are swapped. pub fn from_be(x: Self) -> Self { if cfg!(target_endian="big") { x } else { x.swap_bytes() } } /// Converts an integer from little endian to the target's endianness. /// /// On little endian this is a no-op. On big endian the bytes are swapped. pub fn from_le(x: Self) -> Self { if cfg!(target_endian="little") { x } else { x.swap_bytes() } } /// Converts `self` to big endian from the target's endianness. /// /// On big endian this is a no-op. On little endian the bytes are swapped. pub fn to_be(self) -> Self { Self::from_be(self) } /// Converts self to little endian from the target's endianness. /// /// On little endian this is a no-op. On big endian the bytes are swapped. pub fn to_le(self) -> Self { Self::from_le(self) } /// Raises `self` to the power of `exp`, using exponentiation by squaring. /// /// # Examples /// /// ``` /// use extprim::u128::u128; /// use std::str::FromStr; /// /// assert_eq!(u128::new(5).pow(30), u128::from_str("931322574615478515625").unwrap()); /// ``` pub fn pow(self, exp: u32) -> Self { pow(self, exp as usize) } /// Returns `true` if and only if `self == 2**k` for some `k`. /// /// # Examples /// /// ``` /// use extprim::u128::u128; /// /// assert!(!u128::new(0).is_power_of_two()); /// assert!( u128::new(1).is_power_of_two()); /// assert!( u128::new(2).is_power_of_two()); /// assert!(!u128::new(3).is_power_of_two()); /// ``` pub fn is_power_of_two(self) -> bool { self != ZERO && (self & self.wrapping_sub(ONE)) == ZERO } /// Returns the smallest power of two greater than or equal to `self`. Unspecified behavior on /// overflow. /// /// # Examples /// /// ``` /// use extprim::u128::u128; /// /// assert_eq!(u128::zero().next_power_of_two(), u128::new(1)); /// assert_eq!(u128::one().next_power_of_two(), u128::new(1)); /// assert_eq!(u128::new(384).next_power_of_two(), u128::new(512)); /// assert_eq!(u128::new(0x80000000_00000001).next_power_of_two(), u128::from_parts(1, 0)); /// assert_eq!(u128::from_parts(0x80000000_00000000, 0).next_power_of_two(), u128::from_parts(0x80000000_00000000, 0)); /// ``` pub fn next_power_of_two(self) -> Self { let leading_zeros = self.wrapping_sub(ONE).leading_zeros(); ONE.wrapping_shl(128 - leading_zeros) } /// Returns the smallest power of two greater than or equal to `self`. If the next power of two /// is greater than the type's maximum value, `None` is returned, otherwise the power of two is /// wrapped in `Some`. /// /// # Examples /// /// ``` /// use extprim::u128::u128; /// /// assert_eq!(u128::zero().checked_next_power_of_two(), Some(u128::new(1))); /// assert_eq!(u128::one().checked_next_power_of_two(), Some(u128::new(1))); /// assert_eq!(u128::new(384).checked_next_power_of_two(), Some(u128::new(512))); /// assert_eq!(u128::new(0x80000000_00000001).checked_next_power_of_two(), Some(u128::from_parts(1, 0))); /// assert_eq!(u128::from_parts(0x80000000_00000000, 0).checked_next_power_of_two(), Some(u128::from_parts(0x80000000_00000000, 0))); /// assert_eq!(u128::from_parts(0x80000000_00000000, 1).checked_next_power_of_two(), None); /// assert_eq!(u128::max_value().checked_next_power_of_two(), None); /// ``` pub fn checked_next_power_of_two(self) -> Option { if self == ZERO { Some(ONE) } else { let leading_zeros = self.wrapping_sub(ONE).leading_zeros(); ONE.checked_shl(128 - leading_zeros) } } } impl PrimInt for u128 { fn count_ones(self) -> u32 { Self::count_ones(self) } fn count_zeros(self) -> u32 { Self::count_zeros(self) } fn leading_zeros(self) -> u32 { Self::leading_zeros(self) } fn trailing_zeros(self) -> u32 { Self::trailing_zeros(self) } fn rotate_left(self, shift: u32) -> Self { Self::rotate_left(self, shift) } fn rotate_right(self, shift: u32) -> Self { Self::rotate_right(self, shift) } fn swap_bytes(self) -> Self { Self::swap_bytes(self) } fn from_be(x: Self) -> Self { Self::from_be(x) } fn from_le(x: Self) -> Self { Self::from_le(x) } fn to_be(self) -> Self { Self::to_be(self) } fn to_le(self) -> Self { Self::to_le(self) } fn pow(self, exp: u32) -> Self { Self::pow(self, exp) } fn signed_shl(self, shift: u32) -> Self { self << (shift as usize) } fn signed_shr(self, shift: u32) -> Self { (i128(self) >> (shift as usize)).0 } fn unsigned_shl(self, shift: u32) -> Self { self << (shift as usize) } fn unsigned_shr(self, shift: u32) -> Self { self >> (shift as usize) } } impl Unsigned for u128 { } #[cfg(test)] mod prim_int_tests { use std::u64; use u128::{u128, MAX, ZERO, ONE}; #[test] fn test_rotate() { assert_eq!(u128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152).rotate_right(0), u128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152)); assert_eq!(u128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152).rotate_right(1), u128::from_parts(0xf2e3c00d872bafb, 0xa9f84ed62d9478a9)); assert_eq!(u128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152).rotate_right(3), u128::from_parts(0x43cb8f00361caebe, 0xea7e13b58b651e2a)); assert_eq!(u128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152).rotate_right(64), u128::from_parts(0x53f09dac5b28f152, 0x1e5c7801b0e575f7)); assert_eq!(u128::from_parts(0x1e5c7801b0e575f7, 0x53f09dac5b28f152).rotate_right(120), u128::from_parts(0x5c7801b0e575f753, 0xf09dac5b28f1521e)); } #[test] fn test_swap_bytes() { assert_eq!(u128::from_parts(0xf0d6891695897d01, 0xb6e2f3a4b065e277).swap_bytes(), u128::from_parts(0x77e265b0a4f3e2b6, 0x017d89951689d6f0)); } #[test] fn test_leading_zeros() { assert_eq!(u128::from_parts(1, 0).leading_zeros(), 63); assert_eq!(u128::from_parts(1, 4).leading_zeros(), 63); assert_eq!(u128::from_parts(0, 1).leading_zeros(), 127); assert_eq!(u128::from_parts(0, 0).leading_zeros(), 128); } #[test] fn test_trailing_zeros() { assert_eq!(u128::from_parts(1, 0).trailing_zeros(), 64); assert_eq!(u128::from_parts(3, 0).trailing_zeros(), 64); assert_eq!(u128::from_parts(1, 4).trailing_zeros(), 2); assert_eq!(u128::from_parts(0, 1).trailing_zeros(), 0); assert_eq!(u128::from_parts(0, 0).trailing_zeros(), 128); } #[test] fn test_checked_add() { assert_eq!(Some(u128::from_parts(u64::MAX, 0)), u128::from_parts(u64::MAX-1, u64::MAX) .checked_add(u128::new(1))); assert_eq!(Some(u128::from_parts(u64::MAX, 0)), u128::new(1) .checked_add(u128::from_parts(u64::MAX-1, u64::MAX))); assert_eq!(None, u128::from_parts(u64::MAX, 1) .checked_add(u128::from_parts(u64::MAX, 2))); assert_eq!(None, MAX.checked_add(u128::new(1))); } #[test] fn test_checked_sub() { assert_eq!(None, ZERO.checked_sub(ONE)); assert_eq!(None, ZERO.checked_sub(MAX)); assert_eq!(None, ONE.checked_sub(MAX)); assert_eq!(Some(ONE), ONE.checked_sub(ZERO)); assert_eq!(Some(MAX), MAX.checked_sub(ZERO)); assert_eq!(Some(MAX-ONE), MAX.checked_sub(ONE)); } #[test] fn test_checked_mul() { assert_eq!(Some(ONE), ONE.checked_mul(ONE)); assert_eq!(Some(MAX), MAX.checked_mul(ONE)); assert_eq!(None, MAX.checked_mul(MAX)); assert_eq!(None, MAX.checked_mul(u128::new(2))); assert_eq!(None, u128::from_parts(1, 0).checked_mul(u128::from_parts(1, 0))); let res = u128::from_parts(u64::MAX-1, 1); assert_eq!(Some(res), u128::new(u64::MAX).checked_mul(u128::new(u64::MAX))); } #[test] fn test_checked_div() { assert_eq!(Some(ONE), ONE.checked_div(ONE)); assert_eq!(Some(MAX), MAX.checked_div(ONE)); assert_eq!(Some(ZERO), ONE.checked_div(MAX)); assert_eq!(Some(ZERO), ZERO.checked_div(MAX)); assert_eq!(None, ONE.checked_div(ZERO)); assert_eq!(None, MAX.checked_div(ZERO)); } #[test] fn test_checked_next_power_of_two() { assert_eq!(u128::from_parts(0, 0x80000000_00000000).next_power_of_two(), u128::from_parts(0, 0x80000000_00000000)); assert_eq!(u128::from_parts(0, 0x80000000_00000001).next_power_of_two(), u128::from_parts(1, 0)); assert_eq!(u128::from_parts(1, 0).next_power_of_two(), u128::from_parts(1, 0)); assert_eq!(u128::from_parts(1, 1).next_power_of_two(), u128::from_parts(2, 0)); assert_eq!(u128::from_parts(0x80000000_00000000, 0).checked_next_power_of_two(), Some(u128::from_parts(0x80000000_00000000, 0))); assert_eq!(u128::from_parts(0x80000000_00000000, 1).checked_next_power_of_two(), None); assert_eq!(u128::from_parts(0x80000000_00000001, 0).checked_next_power_of_two(), None); } } #[cfg(all(test, extprim_channel="unstable"))] mod checked_add_sub_bench { use u128::u128; use test::{Bencher, black_box}; const BENCH_CHECKED_ADD_SUB: &'static [u128] = &[ u128 { lo: 8530639231766041497, hi: 1287710968871074399 }, u128 { lo: 1203542656178406941, hi: 17699966409461566340 }, u128 { lo: 718458371035876551, hi: 3606247509203879903 }, u128 { lo: 9776046594219398139, hi: 11242044896228553946 }, u128 { lo: 7902474877314354323, hi: 15571658655527718712 }, u128 { lo: 12666717328207407901, hi: 18395053205720380381 }, u128 { lo: 17339836091522731855, hi: 15731019889221707237 }, u128 { lo: 8366128025082480321, hi: 13984191269538716594 }, u128 { lo: 8593645006461074455, hi: 10189081980804969201 }, u128 { lo: 8264027155501625330, hi: 6198464561866207623 }, u128 { lo: 10849132074109635036, hi: 5777302818880052808 }, u128 { lo: 8053806942953838280, hi: 4617639587817452744 }, u128 { lo: 7575409236673560956, hi: 10773137480165156891 }, u128 { lo: 4323210863932108621, hi: 16058751318664008901 }, u128 { lo: 336314576898396552, hi: 8743495691718489785 }, u128 { lo: 6527874161908570477, hi: 926686061690459595 }, u128 { lo: 15442937728615642560, hi: 2666553580477360520 }, u128 { lo: 11855805362816810591, hi: 17643219502201004064 }, u128 { lo: 16313274500479459547, hi: 5436651574417345289 }, u128 { lo: 15008613641935618684, hi: 12105224025714335156 }, ]; #[bench] fn bench_checked_add(bencher: &mut Bencher) { bencher.iter(|| { for a in BENCH_CHECKED_ADD_SUB { for b in BENCH_CHECKED_ADD_SUB { black_box(a.checked_add(*b)); } } }) } #[bench] fn bench_checked_sub(bencher: &mut Bencher) { bencher.iter(|| { for a in BENCH_CHECKED_ADD_SUB { for b in BENCH_CHECKED_ADD_SUB { black_box(a.checked_sub(*b)); } } }) } } //}}} //{{{ FromStr, FromStrRadix impl u128 { /// Converts a string slice in a given base to an integer. /// /// Leading and trailing whitespace represent an error. /// /// # Arguments /// /// - src: A string slice /// - radix: The base to use. Must lie in the range [2 ... 36]. /// /// # Return value /// /// `Err(ParseIntError)` if the string did not represent a valid number. Otherwise, `Ok(n)` /// where `n` is the integer represented by `src`. pub fn from_str_radix(src: &str, radix: u32) -> Result { assert!(radix >= 2 && radix <= 36, "from_str_radix_int: must lie in the range `[2, 36]` - found {}", radix); if src.is_empty() { return Err(error::empty()); } let mut result = ZERO; let radix64 = radix as u64; for c in src.chars() { let digit = c.to_digit(radix).ok_or_else(error::invalid_digit)?; let int_result = result.checked_mul_64(radix64).ok_or_else(error::overflow)?; let digit128 = u128::new(digit as u64); result = int_result.checked_add(digit128).ok_or_else(error::overflow)?; } Ok(result) } } impl Num for u128 { type FromStrRadixErr = ParseIntError; fn from_str_radix(src: &str, radix: u32) -> Result { Self::from_str_radix(src, radix) } } impl FromStr for u128 { type Err = ParseIntError; fn from_str(src: &str) -> Result { Self::from_str_radix(src, 10) } } #[cfg(test)] mod from_str_tests { use u128::{u128, MAX, ZERO}; use error; #[test] fn test_from_str_radix() { const TEST_RESULTS: &'static [&'static str] = &[ "10011011100100101101000110001011110001010011011101110001100111001000101000101101010100100100010100111001011101010000110001010101", "110120222012101010211220122102022000210010022000111102212102202222012022120111212", "2123210231012023301103131301213020220231110210110321131100301111", "3330311440012420033140113104304110413013304434422141400", "13113233024433543105511522325553410033343505511205", "1634565460422653144356213116334346545422433412", "2334455061361233561471050552444247135206125", "13528171124818368023108014385382865276455", "206792664785365372185662205006093552725", "67649064a7890404084060a25479431a98470", "360187787119a95bb767ba32bb0a5b642505", "29c058245bb23487574aca216c29577b882", "3184907b028135c9183b72cdac9c103109", "4bd69b73d8a16036ebec88cd6bb33d335", "9b92d18bc537719c8a2d524539750c55", "1840gefbd6g31a6ecgg7gc50bd70g1g7", "49dheg38e0608a9f4a9267e4g4aagg5", "h0h83ahe8172ah96d68dfe26e94124", "3h0ea36ada20a526i53ee31044e1g5", "jde641e697f962kkidc27ce2edcj2", "57bb2c3jgc5h08a1ga70l48l6hc3b", "1c8ma26907bj977e8j19da70g8h9e", "b547gj6f5egh808nmcnebbeji765", "3i36o07m0i9185n46481i4noc990", "17f9kaldpa569n4p5gagei47konf", "cfq5a3mohb80l380dbnbkq58fdn", "4oqm8ncn25iij172m7giopbaol9", "1rrq11r63qkjr4s06jq142klq23", "oc5mpkf55e6kpj97prm765q0o5", "an9nde76jttn4ifukgsdinhsc8", "4rib8onh9ne6e8kbai8ksna32l", "28b35bg89n93in6l8rfpijv92b", "12ajr3pwad0qofcfuk1wbutlp7", "i3svxg6wovmba6en6lp37x4cu", "97kl2slyj5vbekzxp0lmn5v85", ]; let v = u128::from_parts(11210252820717990300, 9956704808456227925); for (base2, res) in TEST_RESULTS.iter().enumerate() { assert_eq!(Ok(v), u128::from_str_radix(*res, (base2+2) as u32)); } assert_eq!(Ok(ZERO), u128::from_str_radix("0", 2)); assert_eq!(Ok(ZERO), u128::from_str_radix("0000000000000000000000000000000000", 36)); assert_eq!(Err(error::invalid_digit()), u128::from_str_radix("123", 3)); assert_eq!(Err(error::invalid_digit()), u128::from_str_radix("-1", 10)); assert_eq!(Err(error::empty()), u128::from_str_radix("", 10)); assert_eq!(Ok(MAX), u128::from_str_radix("f5lxx1zz5pnorynqglhzmsp33", 36)); assert_eq!(Err(error::overflow()), u128::from_str_radix("f5lxx1zz5pnorynqglhzmsp34", 36)); assert_eq!(Err(error::overflow()), u128::from_str_radix("f5lxx1zz5pnorynqglhzmsp43", 36)); } } //}}} //{{{ Binary, LowerHex, UpperHex, Octal, String, Show impl fmt::Display for u128 { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { if self.hi == 0 { self.lo.fmt(formatter) } else { const TEN19: u128 = u128 { lo: 10000000000000000000, hi: 0 }; let mut buffer = [0u8; 39]; let mut buf = FormatBuffer::new(&mut buffer); let (mid, lo) = div_rem(*self, TEN19); if mid.hi == 0 { write!(&mut buf, "{}{:019}", mid.lo, lo.lo)?; } else { let (hi, mid) = div_rem(mid, TEN19); write!(&mut buf, "{}{:019}{:019}", hi.lo, mid.lo, lo.lo)?; } formatter.pad_integral(true, "", unsafe { buf.into_str() }) } } } impl fmt::Debug for u128 { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "u128!({})", self) } } impl fmt::Binary for u128 { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { if self.hi == 0 { self.lo.fmt(formatter) } else { let mut buffer = [0u8; 128]; let mut buf = FormatBuffer::new(&mut buffer); write!(&mut buf, "{:b}{:064b}", self.hi, self.lo)?; formatter.pad_integral(true, "0b", unsafe { buf.into_str() }) } } } impl fmt::LowerHex for u128 { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { if self.hi == 0 { self.lo.fmt(formatter) } else { let mut buffer = [0u8; 32]; let mut buf = FormatBuffer::new(&mut buffer); write!(&mut buf, "{:x}{:016x}", self.hi, self.lo)?; formatter.pad_integral(true, "0x", unsafe { buf.into_str() }) } } } impl fmt::UpperHex for u128 { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { if self.hi == 0 { self.lo.fmt(formatter) } else { let mut buffer = [0u8; 32]; let mut buf = FormatBuffer::new(&mut buffer); write!(&mut buf, "{:X}{:016X}", self.hi, self.lo)?; formatter.pad_integral(true, "0x", unsafe { buf.into_str() }) } } } impl fmt::Octal for u128 { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { const MASK: u64 = (1 << 63) - 1; let lo = self.lo & MASK; let mid = (self.hi << 1 | self.lo >> 63) & MASK; let hi = self.hi >> 62; let mut buffer = [0u8; 43]; let mut buf = FormatBuffer::new(&mut buffer); if hi != 0 { write!(&mut buf, "{:o}{:021o}{:021o}", hi, mid, lo)?; } else if mid != 0 { write!(&mut buf, "{:o}{:021o}", mid, lo)?; } else { return lo.fmt(formatter); } formatter.pad_integral(true, "0o", unsafe { buf.into_str() }) } } #[cfg(test)] mod show_tests { use u128::{u128, MAX}; #[test] fn test_display() { assert_fmt_eq!("0", 1, "{}", u128::new(0)); assert_fmt_eq!("10578104835920319894", 20, "{}", u128::new(10578104835920319894)); assert_fmt_eq!("91484347284476727216111035283008240438", 38, "{}", u128::from_parts(4959376403712401289, 46322452157807414)); assert_fmt_eq!("221073131124184722582670274216994227164", 39, "{}", u128::from_parts(11984398452150693167, 12960002013829219292)); assert_fmt_eq!("340282366920938463463374607431768211455", 39, "{}", MAX); assert_fmt_eq!("100000000000000000000000000000000000000", 39, "{}", u128::from_parts(5421010862427522170, 687399551400673280)); assert_fmt_eq!("+00340282366920938463463374607431768211455", 42, "{:+042}", MAX); } #[test] fn test_binary() { assert_fmt_eq!("0", 1, "{:b}", u128::new(0)); assert_fmt_eq!("111001011001111000111001100100010100111010010001110101100101011", 63, "{:b}", u128::new(8272862688628501291)); assert_fmt_eq!("10101011011101011000001011010101101001110110100010000100010001111001010100010010110000000000100100101001100100010110111010011011", 128, "{:b}", u128::from_parts(12354925006909113415, 10741859206816689819)); assert_fmt_eq!("10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 128, "{:b}", u128::from_parts(9223372036854775808, 0)); assert_fmt_eq!("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111", 128, "{:b}", MAX); } #[test] fn test_hex() { assert_fmt_eq!("0", 1, "{:x}", u128::new(0)); assert_fmt_eq!("25c22f8602efedb5", 16, "{:x}", u128::new(2720789377506602421)); assert_fmt_eq!("2c73d4b3d1a46f081a04e1ea9846faee", 32, "{:x}", u128::from_parts(3203137628772003592, 1874871742586354414)); assert_fmt_eq!("80000000000000000000000000000000", 32, "{:x}", u128::from_parts(9223372036854775808, 0)); assert_fmt_eq!(" 0xA", 4, "{:#4X}", u128::new(10)); assert_fmt_eq!("25C22F8602EFEDB5", 16, "{:X}", u128::new(2720789377506602421)); assert_fmt_eq!("2C73D4B3D1A46F081A04E1EA9846FAEE", 32, "{:X}", u128::from_parts(3203137628772003592, 1874871742586354414)); assert_fmt_eq!("C000000000000000000000000000000", 31, "{:X}", u128::from_parts(864691128455135232, 0)); } #[test] fn test_octal() { assert_fmt_eq!("0", 1, "{:o}", u128::new(0)); assert_fmt_eq!("351462366146756037170", 21, "{:o}", u128::new(4208138189379485304)); assert_fmt_eq!("7000263630010212417200", 22, "{:o}", u128::from_parts(3, 9229698078115241600)); assert_fmt_eq!("3465177151267706210351536216110755202064135", 43, "{:o}", u128::from_parts(16620520452737763444, 15533412710015854685)); assert_fmt_eq!("3777777777777777777777777777777777777777777", 43, "{:o}", u128::from_parts(18446744073709551615, 18446744073709551615)); assert_fmt_eq!("2000000000000000000000000000000000000000000", 43, "{:o}", u128::from_parts(9223372036854775808, 0)); } } //}}} //{{{ Sum, Product impl Sum for u128 { fn sum(iter: I) -> Self where I: Iterator { iter.fold(ZERO, Add::add) } } impl Product for u128 { fn product(iter: I) -> Self where I: Iterator { iter.fold(ONE, Mul::mul) } } impl<'a> Sum<&'a u128> for u128 { fn sum(iter: I) -> Self where I: Iterator { iter.fold(ZERO, |acc, elem| acc + *elem) } } impl<'a> Product<&'a u128> for u128 { fn product(iter: I) -> Self where I: Iterator { iter.fold(ONE, |acc, elem| acc * *elem) } } #[cfg(test)] mod iter_tests { use u128::{u128, ZERO, ONE, MIN, MAX}; #[test] fn test_sum() { // Sum assert_eq!(ZERO, Vec::::new().into_iter().sum()); assert_eq!(ZERO, vec![ZERO, ZERO, ZERO].into_iter().sum()); assert_eq!(ONE, vec![ONE].into_iter().sum()); assert_eq!(u128::from(3u64), vec![ONE, ONE, ONE].into_iter().sum()); assert_eq!(MAX, vec![MAX].into_iter().sum()); assert_eq!(MIN, vec![MIN].into_iter().sum()); assert_eq!(u128::from_parts(7, 42), vec![u128::from_parts(7, 42)].into_iter().sum()); // Sum<&'a u128> assert_eq!(ZERO, [].iter().sum()); assert_eq!(ZERO, [ZERO, ZERO, ZERO].iter().sum()); assert_eq!(ONE, [ONE].iter().sum()); assert_eq!(u128::from(3u64), [ONE, ONE, ONE].iter().sum()); assert_eq!(MAX, [MAX].iter().sum()); assert_eq!(MIN, [MIN].iter().sum()); assert_eq!(u128::from_parts(7, 42), [u128::from_parts(7, 42)].iter().sum()); } #[test] fn test_product() { // Product assert_eq!(ONE, Vec::::new().into_iter().product()); assert_eq!(ONE, vec![ONE, ONE, ONE, ONE, ONE, ONE].into_iter().product()); assert_eq!(ZERO, vec![ONE, MAX, ZERO].into_iter().product()); assert_eq!(MAX, vec![MAX].into_iter().product()); assert_eq!(MAX, vec![ONE, MAX].into_iter().product()); assert_eq!(MIN, vec![MIN].into_iter().product()); assert_eq!(MIN, vec![ONE, MIN].into_iter().product()); assert_eq!(MAX, vec![ u128::from(3u64), u128::from(5u64), u128::from(17u64), u128::from(257u64), u128::from(641u64), u128::from(65537u64), u128::from(274177u64), u128::from(6700417u64), u128::from(67280421310721u64), ].into_iter().product()); // Product<&'a u128> assert_eq!(ONE, [].iter().product()); assert_eq!(ONE, [ONE, ONE, ONE, ONE, ONE, ONE].iter().product()); assert_eq!(ZERO, [ONE, MAX, ZERO].iter().product()); assert_eq!(MAX, [MAX].iter().product()); assert_eq!(MAX, [ONE, MAX].iter().product()); assert_eq!(MIN, [MIN].iter().product()); assert_eq!(MIN, [ONE, MIN].iter().product()); assert_eq!(MAX, [ u128::from(3u64), u128::from(5u64), u128::from(17u64), u128::from(257u64), u128::from(641u64), u128::from(65537u64), u128::from(274177u64), u128::from(6700417u64), u128::from(67280421310721u64), ].iter().product()); } } //}}}