mod.rs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. use num_bigint::BigUint;
  2. use num_integer::Integer;
  3. use num_traits::{One, Zero};
  4. use rand::{Rand, Rng};
  5. use std::mem;
  6. use std::ops::{Mul, Rem, Shr};
  7. mod int128;
  8. pub use util::int128::u128;
  9. pub fn rand_vec<G: Rng, R: Rand>(rng: &mut G, size: usize) -> Vec<R> {
  10. rng.gen_iter().take(size).collect()
  11. }
  12. pub fn powm(base: &BigUint, exp: &BigUint, modulus: &BigUint) -> BigUint {
  13. let mut base = base.clone();
  14. let mut exp = exp.clone();
  15. let mut result: BigUint = One::one();
  16. while !exp.is_zero() {
  17. if exp.is_odd() {
  18. result = result.mul(&base).rem(modulus);
  19. }
  20. exp = exp.shr(1);
  21. base = (&base).mul(&base).rem(modulus);
  22. }
  23. result
  24. }
  25. pub trait ReadSeek: ::std::io::Read + ::std::io::Seek {}
  26. impl<T: ::std::io::Read + ::std::io::Seek> ReadSeek for T {}
  27. pub trait Seq {
  28. fn next(&self) -> Self;
  29. }
  30. macro_rules! impl_seq {
  31. ($($ty:ty)*) => { $(
  32. impl Seq for $ty {
  33. fn next(&self) -> Self { *self + 1 }
  34. }
  35. )* }
  36. }
  37. impl_seq!(u8 u16 u32 u64 usize);
  38. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Default)]
  39. pub struct SeqGenerator<T: Seq>(T);
  40. impl<T: Seq> SeqGenerator<T> {
  41. pub fn new(value: T) -> Self {
  42. SeqGenerator(value)
  43. }
  44. pub fn get(&mut self) -> T {
  45. let value = self.0.next();
  46. mem::replace(&mut self.0, value)
  47. }
  48. }