Skip to main content

register_custom_entropy_source

Function register_custom_entropy_source 

Source
pub unsafe fn register_custom_entropy_source(source: *const CustomEntropySource)
Expand description

Register a custom entropy source for the current thread

This function allows developers to register a custom entropy source that will be used by NoStdRng when generating random bytes. The entropy source must remain valid for the lifetime of the registration.

§Arguments

  • source - The custom entropy source to register

§Safety

The source must remain valid for the lifetime of the registration. The caller is responsible for ensuring the source is not dropped while registered.

§Examples

use lib_q_random::custom_entropy::{
    CustomEntropyConfig,
    CustomEntropySource,
    EntropyContext,
    EntropyQuality,
};
use lib_q_random::{
    register_custom_entropy_source,
    unregister_custom_entropy_source,
};
use rand_core::Rng;

// Define a custom entropy callback
unsafe extern "C" fn my_entropy_callback(
    dest: *mut u8,
    len: usize,
    _context: *mut u8,
) -> i32 {
    // Fill dest with len bytes of entropy
    // Return 0 on success, non-zero on failure
    0
}

// Create and register the entropy source
let context = EntropyContext::empty();
let config = CustomEntropyConfig::default();
let source = unsafe {
    CustomEntropySource::new(
        my_entropy_callback,
        context,
        EntropyQuality::User,
        config,
        "my_custom_source",
    )
};

unsafe {
    register_custom_entropy_source(&source);
}

// Now NoStdRng will use the custom entropy source
// (In no_std environments, use new_secure_rng_no_std())
// let mut rng = new_secure_rng_no_std().unwrap();
// let mut bytes = [0u8; 32];
// rng.fill_bytes(&mut bytes);

// Clean up
unregister_custom_entropy_source();