rand.rs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #![allow(unsafe_code)]
  2. #![allow(unused)]
  3. #[cfg(not(any(test, feature = "std", feature = "rand-custom-impl")))]
  4. compile_error!("None of the Cargo features `std` or `rand-custom-impl` is enabled. smoltcp needs a `rand` implementation to work. If your target supports `std`, enable the `std` feature to use the OS's RNG. Otherwise, you must enable the `rand-custom-impl` Cargo feature, and supply your own custom implementation using the `smoltcp::rand_custom_impl!()` macro");
  5. pub fn rand_u32() -> u32 {
  6. let mut val = [0; 4];
  7. rand_bytes(&mut val);
  8. u32::from_ne_bytes(val)
  9. }
  10. /// Fill `buf` with random bytes.
  11. pub fn rand_bytes(buf: &mut [u8]) {
  12. extern "Rust" {
  13. fn _smoltcp_rand(buf: &mut [u8]);
  14. }
  15. unsafe { _smoltcp_rand(buf) }
  16. }
  17. /// Methods required for a custom rand implementation.
  18. ///
  19. /// This trait is not intended to be used directly, just to supply a custom rand implementation to smoltcp.
  20. #[cfg(feature = "rand-custom-impl")]
  21. pub trait Rand {
  22. /// Fill `buf` with random bytes.
  23. fn rand_bytes(buf: &mut [u8]);
  24. }
  25. /// Set the custom rand implementation.
  26. ///
  27. /// # Example
  28. ///
  29. /// ```
  30. /// struct Rand;
  31. /// smoltcp::rand_custom_impl!(Rand);
  32. /// impl smoltcp::Rand for Rand {
  33. /// fn rand_bytes(buf: &mut [u8]) {
  34. /// // TODO
  35. /// }
  36. /// }
  37. ///
  38. #[macro_export]
  39. #[cfg(feature = "rand-custom-impl")]
  40. macro_rules! rand_custom_impl {
  41. ($t: ty) => {
  42. #[no_mangle]
  43. fn _smoltcp_rand(buf: &mut [u8]) {
  44. <$t as $crate::Rand>::rand_bytes(buf)
  45. }
  46. };
  47. }
  48. #[cfg(all(feature = "std", not(feature = "rand-custom-impl"), not(test)))]
  49. #[no_mangle]
  50. fn _smoltcp_rand(buf: &mut [u8]) {
  51. use rand_core::RngCore;
  52. rand_core::OsRng.fill_bytes(buf)
  53. }
  54. #[cfg(test)]
  55. #[no_mangle]
  56. fn _smoltcp_rand(buf: &mut [u8]) {
  57. panic!("Rand should not be used when testing");
  58. }