mod.rs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 url_encode(inp: &str) -> String {
  14. let mut encoded = String::new();
  15. for c in inp.as_bytes().iter() {
  16. match *c as char {
  17. 'A'..='Z' | 'a'..='z' | '0'..='9' | '-' | '_' | '.' | '~' | ':' | '/' => {
  18. encoded.push(*c as char)
  19. }
  20. c => encoded.push_str(format!("%{:02X}", c as u32).as_str()),
  21. };
  22. }
  23. encoded
  24. }
  25. pub fn powm(base: &BigUint, exp: &BigUint, modulus: &BigUint) -> BigUint {
  26. let mut base = base.clone();
  27. let mut exp = exp.clone();
  28. let mut result: BigUint = One::one();
  29. while !exp.is_zero() {
  30. if exp.is_odd() {
  31. result = result.mul(&base).rem(modulus);
  32. }
  33. exp = exp.shr(1);
  34. base = (&base).mul(&base).rem(modulus);
  35. }
  36. result
  37. }
  38. pub trait ReadSeek: ::std::io::Read + ::std::io::Seek {}
  39. impl<T: ::std::io::Read + ::std::io::Seek> ReadSeek for T {}
  40. pub trait Seq {
  41. fn next(&self) -> Self;
  42. }
  43. macro_rules! impl_seq {
  44. ($($ty:ty)*) => { $(
  45. impl Seq for $ty {
  46. fn next(&self) -> Self { (*self).wrapping_add(1) }
  47. }
  48. )* }
  49. }
  50. impl_seq!(u8 u16 u32 u64 usize);
  51. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Default)]
  52. pub struct SeqGenerator<T: Seq>(T);
  53. impl<T: Seq> SeqGenerator<T> {
  54. pub fn new(value: T) -> Self {
  55. SeqGenerator(value)
  56. }
  57. pub fn get(&mut self) -> T {
  58. let value = self.0.next();
  59. mem::replace(&mut self.0, value)
  60. }
  61. }