pseudorandom_conversion.rs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. //! Functionality to convert random seeds into a pseudorandom value.
  2. //!
  3. //! Used for the Half-Tree implementation.
  4. use crate::field::FromPrg;
  5. use core::num::Wrapping;
  6. /// Trait describing a functionality to convert a 128 bit random seed into a pseudorandom value of
  7. /// type `T`.
  8. pub trait PRConvertTo<T> {
  9. /// Convert random seed into an instance of type `T`.
  10. fn convert(randomness: u128) -> T;
  11. }
  12. /// Helper struct for the pseudorandom conversion.
  13. pub struct PRConverter {}
  14. impl PRConvertTo<u8> for PRConverter {
  15. fn convert(randomness: u128) -> u8 {
  16. (randomness & 0xff) as u8
  17. }
  18. }
  19. impl PRConvertTo<u16> for PRConverter {
  20. fn convert(randomness: u128) -> u16 {
  21. (randomness & 0xffff) as u16
  22. }
  23. }
  24. impl PRConvertTo<u32> for PRConverter {
  25. fn convert(randomness: u128) -> u32 {
  26. (randomness & 0xffffffff) as u32
  27. }
  28. }
  29. impl PRConvertTo<u64> for PRConverter {
  30. fn convert(randomness: u128) -> u64 {
  31. (randomness & 0xffffffffffffffff) as u64
  32. }
  33. }
  34. impl<T> PRConvertTo<Wrapping<T>> for PRConverter
  35. where
  36. PRConverter: PRConvertTo<T>,
  37. {
  38. fn convert(randomness: u128) -> Wrapping<T> {
  39. Wrapping(<Self as PRConvertTo<T>>::convert(randomness))
  40. }
  41. }
  42. impl<F: FromPrg> PRConvertTo<F> for PRConverter {
  43. fn convert(randomness: u128) -> F {
  44. F::expand(randomness)
  45. }
  46. }