You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
aya/bpf/aya-bpf/src/maps/array.rs

61 lines
1.7 KiB
Rust

use core::{cell::UnsafeCell, marker::PhantomData, mem, ptr::NonNull};
use aya_bpf_cty::c_void;
use crate::{
bindings::{bpf_map_def, bpf_map_type::BPF_MAP_TYPE_ARRAY},
helpers::bpf_map_lookup_elem,
maps::PinningType,
};
#[repr(transparent)]
pub struct Array<T> {
def: UnsafeCell<bpf_map_def>,
_t: PhantomData<T>,
}
unsafe impl<T: Sync> Sync for Array<T> {}
impl<T> Array<T> {
pub const fn with_max_entries(max_entries: u32, flags: u32) -> Array<T> {
Array {
def: UnsafeCell::new(bpf_map_def {
type_: BPF_MAP_TYPE_ARRAY,
key_size: mem::size_of::<u32>() as u32,
value_size: mem::size_of::<T>() as u32,
max_entries,
map_flags: flags,
id: 0,
pinning: PinningType::None as u32,
}),
_t: PhantomData,
}
}
pub const fn pinned(max_entries: u32, flags: u32) -> Array<T> {
Array {
def: UnsafeCell::new(bpf_map_def {
type_: BPF_MAP_TYPE_ARRAY,
key_size: mem::size_of::<u32>() as u32,
value_size: mem::size_of::<T>() as u32,
max_entries,
map_flags: flags,
id: 0,
pinning: PinningType::ByName as u32,
}),
_t: PhantomData,
}
}
pub fn get(&self, index: u32) -> Option<&T> {
unsafe {
let value = bpf_map_lookup_elem(
self.def.get() as *mut _,
&index as *const _ as *const c_void,
);
// FIXME: alignment
NonNull::new(value as *mut T).map(|p| p.as_ref())
}
}
}