smoltcp/
rand.rs

1#![allow(unsafe_code)]
2#![allow(unused)]
3
4#[derive(Debug)]
5pub(crate) struct Rand {
6    state: u64,
7}
8
9impl Rand {
10    pub(crate) const fn new(seed: u64) -> Self {
11        Self { state: seed }
12    }
13
14    pub(crate) fn rand_u32(&mut self) -> u32 {
15        // sPCG32 from https://www.pcg-random.org/paper.html
16        // see also https://nullprogram.com/blog/2017/09/21/
17        const M: u64 = 0xbb2efcec3c39611d;
18        const A: u64 = 0x7590ef39;
19
20        let s = self.state.wrapping_mul(M).wrapping_add(A);
21        self.state = s;
22
23        let shift = 29 - (s >> 61);
24        (s >> shift) as u32
25    }
26
27    pub(crate) fn rand_u16(&mut self) -> u16 {
28        let n = self.rand_u32();
29        (n ^ (n >> 16)) as u16
30    }
31
32    pub(crate) fn rand_source_port(&mut self) -> u16 {
33        loop {
34            let res = self.rand_u16();
35            if res > 1024 {
36                return res;
37            }
38        }
39    }
40}