aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / vendor / uefi / src / util.rs
| 1 | // SPDX-License-Identifier: MIT OR Apache-2.0 |
| 2 | |
| 3 | use core::ptr::{self, NonNull}; |
| 4 | |
| 5 | /// Copy the bytes of `val` to `ptr`, then advance pointer to just after the |
| 6 | /// newly-copied bytes. |
| 7 | pub const unsafe fn ptr_write_unaligned_and_add<T>(ptr: &mut *mut u8, val: T) { |
| 8 | // SAFETY: The memory is valid. |
| 9 | unsafe { |
| 10 | ptr.cast::<T>().write_unaligned(val); |
| 11 | *ptr = ptr.add(size_of::<T>()); |
| 12 | } |
| 13 | } |
| 14 | |
| 15 | /// Converts a `u32` to `usize`. |
| 16 | /// |
| 17 | /// Panics if `val` does not fit in `usize`. |
| 18 | /// |
| 19 | /// On targets where `usize` is at least 32 bits wide, this never panics. |
| 20 | /// |
| 21 | /// Unlike `as`, this does not silently truncate on narrow `usize` targets. |
| 22 | /// Unlike `usize::try_from(...).unwrap()`, this works in `const` contexts. |
| 23 | pub const fn usize_from_u32(val: u32) -> usize { |
| 24 | if size_of::<usize>() < size_of::<u32>() && val > usize::MAX as u32 { |
| 25 | panic!("value does not fit in usize"); |
| 26 | } |
| 27 | |
| 28 | val as usize |
| 29 | } |
| 30 | |
| 31 | /// Get the raw pointer from `opt`, defaulting to `null_mut`. |
| 32 | pub fn opt_nonnull_to_ptr<T>(opt: Option<NonNull<T>>) -> *mut T { |
| 33 | opt.map(NonNull::as_ptr).unwrap_or(ptr::null_mut()) |
| 34 | } |
| 35 | |
| 36 | #[cfg(test)] |
| 37 | mod tests { |
| 38 | use super::*; |
| 39 | |
| 40 | #[test] |
| 41 | fn test_usize_from_u32() { |
| 42 | assert_eq!(usize_from_u32(0), 0usize); |
| 43 | assert_eq!(usize_from_u32(u32::MAX), 4294967295usize); |
| 44 | } |
| 45 | } |