osom_lib_entropy/
traits.rs

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