1pub mod byte_order;
6pub mod net;
8pub mod signal;
10pub mod sm;
12
13use std::fs::{File, OpenOptions};
14use std::num::Wrapping;
15use std::os::unix::fs::OpenOptionsExt;
16use std::path::Path;
17use std::result::Result;
18
19use libc::O_NONBLOCK;
20
21const MIB_TO_BYTES_SHIFT: usize = 20;
23
24pub fn get_page_size() -> Result<usize, vmm_sys_util::errno::Error> {
26 match unsafe { libc::sysconf(libc::_SC_PAGESIZE) } {
28 -1 => Err(vmm_sys_util::errno::Error::last()),
29 ps => Ok(usize::try_from(ps).unwrap()),
30 }
31}
32
33#[cfg(target_pointer_width = "64")]
36#[inline]
37#[allow(clippy::cast_possible_truncation)]
38pub const fn u64_to_usize(num: u64) -> usize {
39 num as usize
40}
41
42#[cfg(target_pointer_width = "64")]
45#[inline]
46#[allow(clippy::cast_possible_truncation)]
47pub const fn usize_to_u64(num: usize) -> u64 {
48 num as u64
49}
50
51#[inline]
53pub const fn wrap_usize_to_u32(num: usize) -> Wrapping<u32> {
54 Wrapping(((num as u64) & 0xFFFFFFFF) as u32)
55}
56
57pub const fn mib_to_bytes(mib: usize) -> usize {
59 mib << MIB_TO_BYTES_SHIFT
60}
61
62pub const fn bytes_to_mib(bytes: usize) -> usize {
64 bytes >> MIB_TO_BYTES_SHIFT
65}
66
67pub const fn align_up(addr: u64, align: u64) -> u64 {
69 debug_assert!(align != 0);
70 (addr + align - 1) & !(align - 1)
71}
72
73pub const fn align_down(addr: u64, align: u64) -> u64 {
75 debug_assert!(align != 0);
76 addr & !(align - 1)
77}
78
79pub fn open_file_write_nonblock(path: &Path) -> Result<File, std::io::Error> {
84 OpenOptions::new()
85 .custom_flags(O_NONBLOCK)
86 .create(true)
87 .write(true)
88 .open(path)
89}