Skip to content

Commit ca46815

Browse files
committed
Use SmallRng instead of thread_rng which is not available on no_std
The RNG is seeded from the current time and an counter increasing with each call to yield different random values on each invocation. Signed-off-by: Daniel Egger <[email protected]>
1 parent f6902b4 commit ca46815

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

cortex-m-rt/macros/src/lib.rs

+23-1
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,19 @@ extern crate proc_macro;
44
extern crate rand;
55
#[macro_use]
66
extern crate quote;
7+
extern crate core;
78
extern crate proc_macro2;
89
extern crate syn;
910

1011
use proc_macro2::Span;
1112
use rand::Rng;
13+
use rand::SeedableRng;
14+
use std::sync::atomic::{AtomicUsize, Ordering};
15+
use std::time::{SystemTime, UNIX_EPOCH};
1216
use syn::{FnArg, Ident, Item, ItemFn, ItemStatic, ReturnType, Stmt, Type, Visibility};
1317

18+
static CALL_COUNT: AtomicUsize = AtomicUsize::new(0);
19+
1420
use proc_macro::TokenStream;
1521

1622
/// Attribute to declare the entry point of the program
@@ -492,7 +498,23 @@ pub fn pre_init(args: TokenStream, input: TokenStream) -> TokenStream {
492498

493499
// Creates a random identifier
494500
fn random_ident() -> Ident {
495-
let mut rng = rand::thread_rng();
501+
let secs = SystemTime::now()
502+
.duration_since(UNIX_EPOCH)
503+
.unwrap()
504+
.as_secs();
505+
506+
let count: u64 = CALL_COUNT.fetch_add(1, Ordering::SeqCst) as u64;
507+
let mut seed: [u8; 16] = [0; 16];
508+
509+
for (i, v) in seed.iter_mut().take(8).enumerate() {
510+
*v = ((secs >> (i * 8)) & 0xFF) as u8
511+
}
512+
513+
for (i, v) in seed.iter_mut().skip(8).enumerate() {
514+
*v = ((count >> (i * 8)) & 0xFF) as u8
515+
}
516+
517+
let mut rng = rand::rngs::SmallRng::from_seed(seed);
496518
Ident::new(
497519
&(0..16)
498520
.map(|i| {

0 commit comments

Comments
 (0)