rand.rs 919 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #![allow(unsafe_code)]
  2. #![allow(unused)]
  3. #[derive(Debug)]
  4. pub(crate) struct Rand {
  5. state: u64,
  6. }
  7. impl Rand {
  8. pub(crate) const fn new(seed: u64) -> Self {
  9. Self { state: seed }
  10. }
  11. pub(crate) fn rand_u32(&mut self) -> u32 {
  12. // sPCG32 from https://www.pcg-random.org/paper.html
  13. // see also https://nullprogram.com/blog/2017/09/21/
  14. const M: u64 = 0xbb2efcec3c39611d;
  15. const A: u64 = 0x7590ef39;
  16. let s = self.state.wrapping_mul(M).wrapping_add(A);
  17. self.state = s;
  18. let shift = 29 - (s >> 61);
  19. (s >> shift) as u32
  20. }
  21. pub(crate) fn rand_u16(&mut self) -> u16 {
  22. let n = self.rand_u32();
  23. (n ^ (n >> 16)) as u16
  24. }
  25. pub(crate) fn rand_source_port(&mut self) -> u16 {
  26. loop {
  27. let res = self.rand_u16();
  28. if res > 1024 {
  29. return res;
  30. }
  31. }
  32. }
  33. }