sodium_sys/crypto/utils/
randombytes.rs

1//! Utility functions for generating random values and byte sequences.
2use libc::{c_void, size_t, uint32_t};
3
4extern "C" {
5    fn randombytes_buf(buf: *mut c_void, size: size_t) -> ();
6    fn randombytes_random() -> uint32_t;
7    fn randombytes_uniform(upper_bound: uint32_t) -> uint32_t;
8}
9
10/// The *random()* function returns an unpredictable value between 0 and
11/// 0xffffffff (included).
12///
13/// # Examples
14///
15/// ```
16/// use sodium_sys::crypto::utils::randombytes;
17///
18/// let r0 = randombytes::random();
19/// let r1 = randombytes::random();
20/// assert!(r0 != r1);
21/// ```
22pub fn random() -> uint32_t {
23    unsafe {
24        randombytes_random()
25    }
26}
27
28/// The *uniform()* function returns an unpredictable value between 0 and
29/// upper_bound (excluded). Unlike *random()* % upper_bound, it does its best
30/// to guarantee a uniform distribution of the possible output values.
31///
32/// The *uniform()* function safely wraps the *randombytes_uniform()* function.
33///
34/// # Examples
35///
36/// ```
37/// use sodium_sys::crypto::utils::randombytes;
38///
39/// let r0 = randombytes::uniform(10);
40/// assert!(r0 < 10);
41/// ```
42pub fn uniform(upper_bound: uint32_t) -> uint32_t {
43    unsafe {
44        randombytes_uniform(upper_bound)
45    }
46}
47
48/// The *random_byte_array()* function fills the given mutable byte array with
49/// an unpredictable sequence of bytes.
50///
51/// The *random_byte_array()* function safely wrap the *randombytes_buf()*
52/// function.
53///
54/// # Examples
55///
56/// ```
57/// use sodium_sys::crypto::utils::randombytes;
58///
59/// let mut ra0 = [0; 16];
60/// randombytes::random_byte_array(&mut ra0);
61/// assert!(ra0 != [0; 16]);
62/// ```
63pub fn random_byte_array(buf: &mut [u8]) {
64    unsafe {
65        randombytes_buf(buf.as_mut_ptr() as *mut c_void,
66                        buf.len() as size_t);
67    }
68}