Debian Codegraph @

third_party/rust/rustix/src/rand/getrandom.rs

raw
1 //! Wrappers for `getrandom`.
2
3 #![allow(unsafe_code)]
4
5 use crate::buffer::split_init;
6 use crate::{backend, io};
7 use core::mem::MaybeUninit;
8
9 pub use backend::rand::types::GetRandomFlags;
10
11 /// `getrandom(buf, flags)`—Reads a sequence of random bytes.
12 ///
13 /// This is a very low-level API which may be difficult to use correctly. Most
14 /// users should prefer to use [`getrandom`] or [`rand`] APIs instead.
15 ///
16 /// This takes a `&mut [u8]` which Rust requires to contain initialized memory.
17 /// To use an uninitialized buffer, use [`getrandom_uninit`].
18 ///
19 /// [`getrandom`]: https://crates.io/crates/getrandom
20 /// [`rand`]: https://crates.io/crates/rand
21 ///
22 /// # References
23 /// - [Linux]
24 ///
25 /// [Linux]: https://man7.org/linux/man-pages/man2/getrandom.2.html
26 #[inline]
27 pub fn getrandom(buf: &mut [u8], flags: GetRandomFlags) -> io::Result<usize> {
28 unsafe { backend::rand::syscalls::getrandom(buf.as_mut_ptr(), buf.len(), flags) }
29 }
30
31 /// `getrandom(buf, flags)`—Reads a sequence of random bytes.
32 ///
33 /// This is identical to [`getrandom`], except that it can read into
34 /// uninitialized memory. It returns the slice that was initialized by this
35 /// function and the slice that remains uninitialized.
36 #[inline]
37 pub fn getrandom_uninit(
38 buf: &mut [MaybeUninit<u8>],
39 flags: GetRandomFlags,
40 ) -> io::Result<(&mut [u8], &mut [MaybeUninit<u8>])> {
41 // Get number of initialized bytes.
42 let length = unsafe {
43 backend::rand::syscalls::getrandom(buf.as_mut_ptr().cast::<u8>(), buf.len(), flags)
44 };
45
46 // Split into the initialized and uninitialized portions.
47 Ok(unsafe { split_init(buf, length?) })
48 }