Function set_coap_prng

Source
pub fn set_coap_prng<RNG: RngCore + CryptoRng + Send + Sync + 'static>(
    rng: RNG,
) -> Result<(), RngError>
Expand description

Configures libcoap to use the provided rng for pseudo-random number generation instead of its default PRNG.

The provided PRNG will be used globally across all contexts.

§Errors

May return an error if the underlying mutex protecting the RNG is poisoned, i.e. a thread panicked while holding the lock (which should only happen if the previously set RNG panicked).

§Example

use rand_core::{CryptoRng, Error, RngCore};
use libcoap_rs::error::RngError;
use libcoap_rs::prng::{coap_prng_try_fill, set_coap_prng};

pub struct NullRng {}

impl RngCore for NullRng {
    fn next_u32(&mut self) -> u32 {
        0
    }

    fn next_u64(&mut self) -> u64 {
        0
    }

    fn fill_bytes(&mut self, dest: &mut [u8]) {
        dest.fill(0);
    }

    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
        dest.fill(0);
        Ok(())
    }
}

// Obviously, this is just for demonstration purposes and should not actually be done.
impl CryptoRng for NullRng {}

set_coap_prng(NullRng{})?;
let mut token = [1u8; 8];
coap_prng_try_fill(&mut token)?;

assert_eq!(&token, &[0u8; 8]);