Merge pull request #379 from bobmcwhirter/random_range

Random range
This commit is contained in:
Dario Nieuwenhuis 2021-09-01 22:53:10 +02:00 committed by GitHub
commit bc68657c23
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 104 additions and 10 deletions

View file

@ -19,11 +19,11 @@ pub enum Error {
ClockError,
}
pub struct Random<T: Instance> {
pub struct Rng<T: Instance> {
_inner: T,
}
impl<T: Instance> Random<T> {
impl<T: Instance> Rng<T> {
pub fn new(inner: impl Unborrow<Target = T>) -> Self {
T::enable();
T::reset();
@ -49,7 +49,7 @@ impl<T: Instance> Random<T> {
}
}
impl<T: Instance> RngCore for Random<T> {
impl<T: Instance> RngCore for Rng<T> {
fn next_u32(&mut self) -> u32 {
loop {
let bits = unsafe { T::regs().sr().read() };
@ -80,9 +80,9 @@ impl<T: Instance> RngCore for Random<T> {
}
}
impl<T: Instance> CryptoRng for Random<T> {}
impl<T: Instance> CryptoRng for Rng<T> {}
impl<T: Instance> traits::rng::Rng for Random<T> {
impl<T: Instance> traits::rng::Rng for Rng<T> {
type Error = Error;
#[rustfmt::skip]
type RngFuture<'a> where Self: 'a = impl Future<Output=Result<(), Self::Error>> + 'a;

View file

@ -4,9 +4,10 @@ use core::future::Future;
pub trait Rng {
type Error;
type RngFuture<'a>: Future<Output = Result<(), Self::Error>> + 'a
#[rustfmt::skip]
type RngFuture<'a>: Future<Output = Result<(), Self::Error> > + 'a
where
Self: 'a;
Self: 'a;
/// Completely fill the provided buffer with random bytes.
///
@ -15,3 +16,61 @@ pub trait Rng {
/// filled or an error will have been reported.
fn fill_bytes<'a>(&'a mut self, dest: &'a mut [u8]) -> Self::RngFuture<'a>;
}
pub struct Random<T: Rng> {
rng: T,
}
impl<T: Rng> Random<T> {
pub fn new(rng: T) -> Self {
Self { rng }
}
pub async fn next_u8<'a>(&'a mut self, range: u8) -> Result<u8, T::Error> {
// Lemire's method
let t = (-(range as i8) % (range as i8)) as u8;
loop {
let mut buf = [0; 1];
self.rng.fill_bytes(&mut buf).await?;
let x = u8::from_le_bytes(buf);
let m = x as u16 * range as u16;
let l = m as u8;
if l < t {
continue;
}
return Ok((m >> 8) as u8);
}
}
pub async fn next_u16<'a>(&'a mut self, range: u16) -> Result<u16, T::Error> {
// Lemire's method
let t = (-(range as i16) % (range as i16)) as u16;
loop {
let mut buf = [0; 2];
self.rng.fill_bytes(&mut buf).await?;
let x = u16::from_le_bytes(buf);
let m = x as u32 * range as u32;
let l = m as u16;
if l < t {
continue;
}
return Ok((m >> 16) as u16);
}
}
pub async fn next_u32<'a>(&'a mut self, range: u32) -> Result<u32, T::Error> {
// Lemire's method
let t = (-(range as i32) % (range as i32)) as u32;
loop {
let mut buf = [0; 4];
self.rng.fill_bytes(&mut buf).await?;
let x = u32::from_le_bytes(buf);
let m = x as u64 * range as u64;
let l = m as u32;
if l < t {
continue;
}
return Ok((m >> 32) as u32);
}
}
}

View file

@ -21,7 +21,7 @@ use embassy_net::{
};
use embassy_stm32::eth::lan8742a::LAN8742A;
use embassy_stm32::eth::{Ethernet, State};
use embassy_stm32::rng::Random;
use embassy_stm32::rng::Rng;
use embassy_stm32::{interrupt, peripherals};
use heapless::Vec;
use panic_probe as _;
@ -81,7 +81,7 @@ fn _embassy_rand(buf: &mut [u8]) {
});
}
static mut RNG_INST: Option<Random<RNG>> = None;
static mut RNG_INST: Option<Rng<RNG>> = None;
static EXECUTOR: Forever<Executor> = Forever::new();
static STATE: Forever<State<'static, 4, 4>> = Forever::new();
@ -97,7 +97,7 @@ fn main() -> ! {
let p = embassy_stm32::init(config());
let rng = Random::new(p.RNG);
let rng = Rng::new(p.RNG);
unsafe {
RNG_INST.replace(rng);
}

View file

@ -0,0 +1,35 @@
#![no_std]
#![no_main]
#![feature(trait_alias)]
#![feature(type_alias_impl_trait)]
#![allow(incomplete_features)]
#[path = "../example_common.rs"]
mod example_common;
use embassy::executor::Spawner;
use embassy::time::{Duration, Timer};
use embassy::traits::rng::Random;
use embassy_stm32::gpio::{Level, Output, Speed};
use embassy_stm32::rng::Rng;
use embassy_stm32::Peripherals;
use embedded_hal::digital::v2::OutputPin;
use example_common::*;
#[embassy::main]
async fn main(_spawner: Spawner, p: Peripherals) {
info!("Hello World!");
let mut led = Output::new(p.PB14, Level::High, Speed::Low);
let mut rng = Random::new(Rng::new(p.RNG));
loop {
info!("high {}", unwrap!(rng.next_u8(16).await));
unwrap!(led.set_high());
Timer::after(Duration::from_millis(500)).await;
info!("low {}", unwrap!(rng.next_u8(16).await));
unwrap!(led.set_low());
Timer::after(Duration::from_millis(500)).await;
}
}