Debian Codegraph @

debian/rust-vendor/rustix/src/rand/getrandom.rs

raw
1 //! Wrappers for `getrandom`.
2
3 #![allow(unsafe_code)]
4
5 use crate::buffer::Buffer;
6 use crate::{backend, io};
7
8 pub use backend::rand::types::GetRandomFlags;
9
10 /// `getrandom(buf, flags)`—Reads a sequence of random bytes.
11 ///
12 /// This is a very low-level API which may be difficult to use correctly. Most
13 /// users should prefer to use [`getrandom`] or [`rand`] APIs instead.
14 ///
15 /// This function is implemented using a system call, and not the
16 /// [vDSO mechanism] introduced in Linux 6.11. See [#1185] for details.
17 ///
18 /// [`getrandom`]: https://crates.io/crates/getrandom
19 /// [`rand`]: https://crates.io/crates/rand
20 /// [vDSO mechanism]: https://lwn.net/Articles/983186/
21 /// [#1185]: https://github.com/bytecodealliance/rustix/issues/1185
22 ///
23 /// # References
24 /// - [Linux]
25 ///
26 /// [Linux]: https://man7.org/linux/man-pages/man2/getrandom.2.html
27 #[inline]
28 pub fn getrandom<Buf: Buffer<u8>>(mut buf: Buf, flags: GetRandomFlags) -> io::Result<Buf::Output> {
29 // SAFETY: `getrandom` behaves.
30 let len = unsafe { backend::rand::syscalls::getrandom(buf.parts_mut(), flags)? };
31 // SAFETY: `getrandom` behaves.
32 unsafe { Ok(buf.assume_init(len)) }
33 }