• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (C) 2018-2019, Cloudflare, Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright notice,
9 //       this list of conditions and the following disclaimer.
10 //
11 //     * Redistributions in binary form must reproduce the above copyright
12 //       notice, this list of conditions and the following disclaimer in the
13 //       documentation and/or other materials provided with the distribution.
14 //
15 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
16 // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
19 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 
rand_bytes(buf: &mut [u8])27 pub fn rand_bytes(buf: &mut [u8]) {
28     unsafe {
29         RAND_bytes(buf.as_mut_ptr(), buf.len());
30     }
31 }
32 
rand_u8() -> u833 pub fn rand_u8() -> u8 {
34     let mut buf = [0; 1];
35 
36     rand_bytes(&mut buf);
37 
38     buf[0]
39 }
40 
rand_u64() -> u6441 pub fn rand_u64() -> u64 {
42     let mut buf = [0; 8];
43 
44     rand_bytes(&mut buf);
45 
46     u64::from_ne_bytes(buf)
47 }
48 
rand_u64_uniform(max: u64) -> u6449 pub fn rand_u64_uniform(max: u64) -> u64 {
50     let chunk_size = u64::max_value() / max;
51     let end_of_last_chunk = chunk_size * max;
52 
53     let mut r = rand_u64();
54 
55     while r >= end_of_last_chunk {
56         r = rand_u64();
57     }
58 
59     r / chunk_size
60 }
61 
62 extern {
RAND_bytes(buf: *mut u8, len: libc::size_t) -> libc::c_int63     fn RAND_bytes(buf: *mut u8, len: libc::size_t) -> libc::c_int;
64 }
65