From 80c504cd950349caa96ae37898f6f3325030c615 Mon Sep 17 00:00:00 2001 From: Dario Nieuwenhuis Date: Mon, 14 Dec 2020 00:36:29 +0100 Subject: [PATCH] Add std impl for rand --- embassy/Cargo.toml | 5 ++++- embassy/src/rand.rs | 15 +++++++++++++++ {.cargo => examples/.cargo}/config | 0 test-build.sh | 5 ++++- 4 files changed, 23 insertions(+), 2 deletions(-) rename {.cargo => examples/.cargo}/config (100%) diff --git a/embassy/Cargo.toml b/embassy/Cargo.toml index 0e4c801b..08d273db 100644 --- a/embassy/Cargo.toml +++ b/embassy/Cargo.toml @@ -5,7 +5,7 @@ authors = ["Dario Nieuwenhuis "] edition = "2018" [features] -std = ["futures/std"] +std = ["futures/std", "rand_core"] defmt-trace = [] defmt-debug = [] defmt-info = [] @@ -16,6 +16,9 @@ defmt-error = [] defmt = { version = "0.1.3", optional = true } log = { version = "0.4.11", optional = true } +# std-only +rand_core = { version = "0.5.1", optional = true, features = ["std"] } + cortex-m = "0.6.4" futures = { version = "0.3.5", default-features = false } pin-project = { version = "1.0.2", default-features = false } diff --git a/embassy/src/rand.rs b/embassy/src/rand.rs index 7e378838..6e78c24a 100644 --- a/embassy/src/rand.rs +++ b/embassy/src/rand.rs @@ -4,6 +4,9 @@ pub trait Rand { fn rand(&self, buf: &mut [u8]); } +#[cfg(feature = "std")] +static mut RAND: Option<&'static dyn Rand> = Some(&if_std::Rand); +#[cfg(not(feature = "std"))] static mut RAND: Option<&'static dyn Rand> = None; pub unsafe fn set_rand(rand: &'static dyn Rand) { @@ -13,3 +16,15 @@ pub unsafe fn set_rand(rand: &'static dyn Rand) { pub fn rand(buf: &mut [u8]) { unsafe { unwrap!(RAND, "No rand set").rand(buf) } } + +#[cfg(feature = "std")] +mod if_std { + use rand_core::{OsRng, RngCore}; + + pub(crate) struct Rand; + impl super::Rand for Rand { + fn rand(&self, buf: &mut [u8]) { + OsRng.fill_bytes(buf) + } + } +} diff --git a/.cargo/config b/examples/.cargo/config similarity index 100% rename from .cargo/config rename to examples/.cargo/config diff --git a/test-build.sh b/test-build.sh index ae603b28..52bf7bb7 100755 --- a/test-build.sh +++ b/test-build.sh @@ -5,7 +5,10 @@ set -euxo pipefail # examples (cd examples; cargo build --target thumbv7em-none-eabi --bins) -# embassy +# embassy std +(cd embassy; cargo build --features log,std) + +# embassy embedded (cd embassy; cargo build --target thumbv7em-none-eabi) (cd embassy; cargo build --target thumbv7em-none-eabi --features log) (cd embassy; cargo build --target thumbv7em-none-eabi --features defmt)