Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #![feature(test)]
- extern crate num_bigint;
- extern crate num_traits;
- extern crate test;
- use num_bigint::{BigInt, BigUint};
- use num_traits::ToPrimitive;
- use std::u32;
- fn truncate_biguint_to_u32(a: &BigUint) -> u32 {
- use std::u32;
- let mask = BigUint::from(u32::MAX);
- (a & mask).to_u32().unwrap()
- }
- fn truncate_bigint_to_u32(a: &BigInt) -> u32 {
- use num_traits::Signed;
- let was_negative = a.is_negative();
- let abs = a.abs().to_biguint().unwrap();
- let mut truncated = truncate_biguint_to_u32(&abs);
- if was_negative {
- truncated = (!truncated).wrapping_add(1);
- }
- truncated
- }
- #[bench]
- fn bench_truncate_biguint(bencher: &mut test::Bencher) {
- let b = BigUint::parse_bytes(b"423445324324324324234324", 10).unwrap();
- let c = BigUint::parse_bytes(b"76543210fedcba98", 16).unwrap();
- let d = BigUint::parse_bytes(&vec![b'8'; 1000], 36).unwrap();
- let e = (BigUint::from(1u32) << d.bits()) - &d;
- bencher.iter(|| {
- assert_eq!(truncate_biguint_to_u32(&b), 43078740);
- assert_eq!(truncate_biguint_to_u32(&c), 0xfedcba98);
- assert_eq!(truncate_biguint_to_u32(&d), 2822407080);
- assert_eq!(truncate_biguint_to_u32(&e), 1472560216);
- });
- bencher.bytes = (b.bits() + c.bits() + d.bits() + e.bits()) as u64 / 8;
- }
- #[bench]
- fn bench_truncate_bigint(bencher: &mut test::Bencher) {
- let b = BigInt::parse_bytes(b"423445324324324324234324", 10).unwrap();
- let c = BigInt::parse_bytes(b"76543210fedcba98", 16).unwrap();
- let d = BigInt::parse_bytes(&vec![b'8'; 1000], 36).unwrap();
- let e = -&d;
- bencher.iter(|| {
- assert_eq!(truncate_bigint_to_u32(&b), 43078740);
- assert_eq!(truncate_bigint_to_u32(&c), 0xfedcba98);
- assert_eq!(truncate_bigint_to_u32(&d), 2822407080);
- assert_eq!(truncate_bigint_to_u32(&e), 1472560216);
- });
- bencher.bytes = (b.bits() + c.bits() + d.bits() + e.bits()) as u64 / 8;
- }
- #[test] fn test() {}
Add Comment
Please, Sign In to add comment