mod.rs 1.3 KB

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