use std::any::type_name;
use std::ffi::CStr;
use std::ffi::CString;
use std::io;
use std::mem::transmute;
use std::ops::Deref;
use std::os::raw::c_char;
use std::path::Path;
use std::ptr::NonNull;
use std::sync::OnceLock;
use crate::Error;
use crate::Result;
pub fn str_to_cstring(s: &str) -> Result<CString> {
CString::new(s).map_err(|e| Error::with_invalid_data(e.to_string()))
}
pub fn path_to_cstring<P: AsRef<Path>>(path: P) -> Result<CString> {
let path_str = path.as_ref().to_str().ok_or_else(|| {
Error::with_invalid_data(format!("{} is not valid unicode", path.as_ref().display()))
})?;
str_to_cstring(path_str)
}
pub fn c_ptr_to_string(p: *const c_char) -> Result<String> {
if p.is_null() {
return Err(Error::with_invalid_data("Null string"));
}
let c_str = unsafe { CStr::from_ptr(p) };
Ok(c_str
.to_str()
.map_err(|e| Error::with_invalid_data(e.to_string()))?
.to_owned())
}
pub fn c_char_slice_to_cstr(s: &[c_char]) -> Option<&CStr> {
let nul_idx = s
.iter()
.enumerate()
.find_map(|(idx, b)| (*b == 0).then_some(idx))?;
let cstr =
CStr::from_bytes_with_nul(unsafe { transmute::<&[c_char], &[u8]>(&s[0..=nul_idx]) })
.unwrap();
Some(cstr)
}
pub fn roundup(num: usize, r: usize) -> usize {
((num + (r - 1)) / r) * r
}
pub fn num_possible_cpus() -> Result<usize> {
let ret = unsafe { libbpf_sys::libbpf_num_possible_cpus() };
parse_ret(ret).map(|()| ret as usize)
}
pub fn parse_ret(ret: i32) -> Result<()> {
if ret < 0 {
Err(Error::from_raw_os_error(-ret))
} else {
Ok(())
}
}
pub fn parse_ret_i32(ret: i32) -> Result<i32> {
parse_ret(ret).map(|()| ret)
}
pub fn create_bpf_entity_checked<B: 'static, F: FnOnce() -> *mut B>(f: F) -> Result<NonNull<B>> {
create_bpf_entity_checked_opt(f).and_then(|ptr| {
ptr.ok_or_else(|| {
Error::with_io_error(
io::ErrorKind::Other,
format!(
"bpf call {:?} returned NULL",
type_name::<F>() ),
)
})
})
}
pub fn create_bpf_entity_checked_opt<B: 'static, F: FnOnce() -> *mut B>(
f: F,
) -> Result<Option<NonNull<B>>> {
let ptr = f();
if ptr.is_null() {
return Ok(None);
}
match unsafe { libbpf_sys::libbpf_get_error(ptr as *const _) } {
0 => Ok(Some(unsafe {
NonNull::new_unchecked(ptr)
})),
err => Err(Error::from_raw_os_error(-err as i32)),
}
}
pub(crate) struct LazyLock<T> {
cell: OnceLock<T>,
init: fn() -> T,
}
impl<T> LazyLock<T> {
pub const fn new(f: fn() -> T) -> Self {
Self {
cell: OnceLock::new(),
init: f,
}
}
}
impl<T> Deref for LazyLock<T> {
type Target = T;
#[inline]
fn deref(&self) -> &T {
self.cell.get_or_init(self.init)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_roundup() {
for i in 1..=256 {
let up = roundup(i, 8);
assert!(up % 8 == 0);
assert!(i <= up);
assert!(up - i < 8);
}
}
#[test]
fn test_roundup_multiples() {
for i in (8..=256).step_by(8) {
assert_eq!(roundup(i, 8), i);
}
}
#[test]
fn test_num_possible_cpus() {
let num = num_possible_cpus().unwrap();
assert!(num > 0);
}
#[test]
fn c_char_slice_conversion() {
let slice = [];
assert_eq!(c_char_slice_to_cstr(&slice), None);
let slice = [0];
assert_eq!(
c_char_slice_to_cstr(&slice).unwrap(),
CStr::from_bytes_with_nul(b"\0").unwrap()
);
let slice = ['a' as _, 'b' as _, 'c' as _, 0 as _];
assert_eq!(
c_char_slice_to_cstr(&slice).unwrap(),
CStr::from_bytes_with_nul(b"abc\0").unwrap()
);
let slice = ['a' as _, 'b' as _, 'c' as _];
assert_eq!(c_char_slice_to_cstr(&slice), None);
}
}