osom_lib_entropy/traits.rs
1//! Defines entropy traits.
2
3use osom_lib_reprc::traits::ReprC;
4
5/// Generates random type based on surrounding entropy, i.e.
6/// based on what the operating system provides as "true" randomness.
7///
8/// Similar to [`EntropyGenerator`] but works with a single type
9/// only.
10pub trait EntropyConcreteGenerator<TGenerator: EntropyGenerator>: Sized + ReprC {
11 /// Generates a new random instance of itself.
12 ///
13 /// # Errors
14 ///
15 /// The same as [`EntropyGenerator::Error`].
16 fn generate(generator: &mut TGenerator) -> Result<Self, TGenerator::Error>;
17}
18
19/// Generates randomness based on surrounding entropy, i.e.
20/// based on what the operating system provides as "true" randomness.
21/// The generator should be expected to be quite slow, but should
22/// also provide excelent randomness, as close to "true" randomness
23/// as possible.
24pub trait EntropyGenerator: Sized + ReprC + Clone {
25 /// Represents a failure of entropy generation.
26 type Error: ReprC;
27
28 /// Fills raw ptr with randomness based on surrounding entropy.
29 ///
30 /// # Errors
31 ///
32 /// See concrete [`EntropyGenerator::Error`].
33 ///
34 /// # Safety
35 ///
36 /// This function assumes that both `buffer_ptr` and `buffer_len`
37 /// point to a valid chunk of memory. Otherwise the behaviour is
38 /// undefined.
39 unsafe fn fill_raw(&mut self, buffer_ptr: *mut u8, buffer_len: usize) -> Result<(), Self::Error>;
40
41 /// Fills slice with randomness based on surrounding entropy.
42 ///
43 /// # Errors
44 ///
45 /// See concrete [`EntropyGenerator::Error`].
46 #[inline(always)]
47 fn fill(&mut self, buffer: &mut [u8]) -> Result<(), Self::Error> {
48 unsafe { self.fill_raw(buffer.as_mut_ptr(), buffer.len()) }
49 }
50
51 /// Generates random instance of given type.
52 ///
53 /// # Errors
54 ///
55 /// See concrete [`EntropyGenerator::Error`].
56 #[inline(always)]
57 fn generate<T>(&mut self) -> Result<T, Self::Error>
58 where
59 T: EntropyConcreteGenerator<Self>,
60 {
61 T::generate(self)
62 }
63}