Guest User

Untitled

a guest
May 27th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. #![feature(test)]
  2.  
  3. extern crate num_bigint;
  4. extern crate num_traits;
  5. extern crate test;
  6.  
  7. use num_bigint::{BigInt, BigUint};
  8. use num_traits::ToPrimitive;
  9.  
  10. use std::u32;
  11.  
  12. fn truncate_biguint_to_u32(a: &BigUint) -> u32 {
  13. use std::u32;
  14. let mask = BigUint::from(u32::MAX);
  15. (a & mask).to_u32().unwrap()
  16. }
  17.  
  18. fn truncate_bigint_to_u32(a: &BigInt) -> u32 {
  19. use num_traits::Signed;
  20.  
  21. let was_negative = a.is_negative();
  22. let abs = a.abs().to_biguint().unwrap();
  23. let mut truncated = truncate_biguint_to_u32(&abs);
  24. if was_negative {
  25. truncated = (!truncated).wrapping_add(1);
  26. }
  27. truncated
  28. }
  29.  
  30. #[bench]
  31. fn bench_truncate_biguint(bencher: &mut test::Bencher) {
  32. let b = BigUint::parse_bytes(b"423445324324324324234324", 10).unwrap();
  33. let c = BigUint::parse_bytes(b"76543210fedcba98", 16).unwrap();
  34. let d = BigUint::parse_bytes(&vec![b'8'; 1000], 36).unwrap();
  35. let e = (BigUint::from(1u32) << d.bits()) - &d;
  36. bencher.iter(|| {
  37. assert_eq!(truncate_biguint_to_u32(&b), 43078740);
  38. assert_eq!(truncate_biguint_to_u32(&c), 0xfedcba98);
  39. assert_eq!(truncate_biguint_to_u32(&d), 2822407080);
  40. assert_eq!(truncate_biguint_to_u32(&e), 1472560216);
  41. });
  42. bencher.bytes = (b.bits() + c.bits() + d.bits() + e.bits()) as u64 / 8;
  43. }
  44.  
  45. #[bench]
  46. fn bench_truncate_bigint(bencher: &mut test::Bencher) {
  47. let b = BigInt::parse_bytes(b"423445324324324324234324", 10).unwrap();
  48. let c = BigInt::parse_bytes(b"76543210fedcba98", 16).unwrap();
  49. let d = BigInt::parse_bytes(&vec![b'8'; 1000], 36).unwrap();
  50. let e = -&d;
  51. bencher.iter(|| {
  52. assert_eq!(truncate_bigint_to_u32(&b), 43078740);
  53. assert_eq!(truncate_bigint_to_u32(&c), 0xfedcba98);
  54. assert_eq!(truncate_bigint_to_u32(&d), 2822407080);
  55. assert_eq!(truncate_bigint_to_u32(&e), 1472560216);
  56. });
  57. bencher.bytes = (b.bits() + c.bits() + d.bits() + e.bits()) as u64 / 8;
  58. }
  59.  
  60. #[test] fn test() {}
Add Comment
Please, Sign In to add comment