1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
extern crate core;
#[cfg(feature = "unproven")]
use core::cmp;
#[cfg(feature = "unproven")]
use core::mem::transmute;
use crate::rcc::{AHB2, Clocks};
use crate::stm32::RNG;
pub trait RngExt {
fn enable(self, ahb2: &mut AHB2, clocks: Clocks) -> Rng;
}
impl RngExt for RNG {
fn enable(self, ahb2: &mut AHB2, clocks: Clocks) -> Rng {
let msi = match clocks.msi() {
Some(msi) => msi == crate::rcc::MsiFreq::RANGE48M,
None => false,
};
let hsi = clocks.hsi48();
assert!(msi || hsi);
ahb2.enr().modify(|_, w| w.rngen().set_bit());
while ahb2.enr().read().rngen().bit_is_clear() {}
self.cr.modify(|_, w| w.rngen().set_bit());
Rng {
rng: self
}
}
}
pub struct Rng {
rng: RNG,
}
impl Rng {
pub fn free(self) -> RNG {
self.rng
}
pub fn get_random_data(&self)-> u32 {
while !self.is_data_ready() {}
let word = self.possibly_invalid_random_data();
word
}
pub fn is_interrupt_enabled(&self) -> bool {
self.rng.cr.read().ie().bit()
}
pub fn is_enabled(&self) -> bool {
self.rng.cr.read().rngen().bit()
}
pub fn is_clock_error(&self) -> bool {
self.rng.sr.read().cecs().bit()
}
pub fn is_seed_error(&self) -> bool {
self.rng.sr.read().secs().bit()
}
pub fn is_data_ready(&self) -> bool {
self.rng.sr.read().drdy().bit()
}
pub fn possibly_invalid_random_data(&self) -> u32 {
self.rng.dr.read().rndata().bits()
}
}
#[derive(Debug)]
pub enum Error {}
#[cfg(feature = "unproven")]
impl crate::hal::blocking::rng::Read for Rng {
type Error = Error;
fn read(&mut self, buffer: &mut [u8]) -> Result<(), Self::Error> {
let mut i = 0usize;
while i < buffer.len() {
let random_word: u32 = self.get_random_data();
let bytes = unsafe { transmute::<u32, [u8; 4]>(random_word) };
let n = cmp::min(4, buffer.len() - i);
buffer[i..i + n].copy_from_slice(&bytes[..n]);
i += n;
}
Ok(())
}
}