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
//! HAL interface to the RNG peripheral
//!
//! See nRF52832 product specification, chapter 26.


use core::ops::Deref;

use crate::target::{
    rng,
    RNG,
};


pub trait RngExt : Deref<Target=rng::RegisterBlock> + Sized {
    fn constrain(self) -> Rng;
}

impl RngExt for RNG {
    fn constrain(self) -> Rng {
        Rng(self)
    }
}


/// Interface to the RNG peripheral
///
/// Right now, this is very basic, only providing blocking interfaces.
pub struct Rng(RNG);

impl Rng {
    /// Fill the provided buffer with random bytes
    ///
    /// Will block until the buffer is full.
    pub fn random(&mut self, buf: &mut [u8]) {
        self.0.tasks_start.write(|w| unsafe { w.bits(1) });

        for b in buf {
            // Wait for random byte to become ready, reset the flag once it is
            while self.0.events_valrdy.read().bits() == 0 {}
            self.0.events_valrdy.write(|w| unsafe { w.bits(0) });

            *b = self.0.value.read().value().bits();
        }

        self.0.tasks_stop.write(|w| unsafe { w.bits(1) });
    }

    /// Return a random `u8`
    pub fn random_u8(&mut self) -> u8 {
        let mut buf = [0; 1];
        self.random(&mut buf);
        buf[0]
    }

    /// Return a random `u16`
    pub fn random_u16(&mut self) -> u16 {
        let mut buf = [0; 2];
        self.random(&mut buf);
        buf[0] as u16 |
            (buf[1] as u16) << 8
    }

    /// Return a random `u32`
    pub fn random_u32(&mut self) -> u32 {
        let mut buf = [0; 4];
        self.random(&mut buf);
        buf[0] as u32 |
            (buf[1] as u32) <<  8 |
            (buf[2] as u32) << 16 |
            (buf[3] as u32) << 24
    }

    /// Return a random `u64`
    pub fn random_u64(&mut self) -> u64 {
        let mut buf = [0; 8];
        self.random(&mut buf);
        buf[0] as u64 |
            (buf[1] as u64) <<  8 |
            (buf[2] as u64) << 16 |
            (buf[3] as u64) << 24 |
            (buf[4] as u64) << 32 |
            (buf[5] as u64) << 40 |
            (buf[6] as u64) << 48 |
            (buf[7] as u64) << 56
    }
}