aya_friday/maps/array/array.rs
1use std::{
2 borrow::{Borrow, BorrowMut},
3 marker::PhantomData,
4};
5
6use crate::{
7 Pod,
8 maps::{IterableMap, MapData, MapError, check_bounds, check_kv_size, hash_map},
9};
10
11/// A fixed-size array.
12///
13/// The size of the array is defined on the eBPF side using the `bpf_map_def::max_entries` field.
14/// All the entries are zero-initialized when the map is created.
15///
16/// # Minimum kernel version
17///
18/// The minimum kernel version required to use this feature is 3.19.
19///
20/// # Examples
21/// ```no_run
22/// # let mut bpf = aya::Ebpf::load(&[])?;
23/// use aya::maps::Array;
24///
25/// let mut array = Array::try_from(bpf.map_mut("ARRAY").unwrap())?;
26/// array.set(1, 42, 0)?;
27/// assert_eq!(array.get(&1, 0)?, 42);
28/// # Ok::<(), aya::EbpfError>(())
29/// ```
30#[doc(alias = "BPF_MAP_TYPE_ARRAY")]
31pub struct Array<T, V: Pod> {
32 pub(crate) inner: T,
33 _v: PhantomData<V>,
34}
35
36impl<T: Borrow<MapData>, V: Pod> Array<T, V> {
37 pub(crate) fn new(map: T) -> Result<Self, MapError> {
38 let data = map.borrow();
39 check_kv_size::<u32, V>(data)?;
40
41 Ok(Self {
42 inner: map,
43 _v: PhantomData,
44 })
45 }
46
47 /// Returns the number of elements in the array.
48 ///
49 /// This corresponds to the value of `bpf_map_def::max_entries` on the eBPF side.
50 pub fn len(&self) -> u32 {
51 self.inner.borrow().obj.max_entries()
52 }
53
54 /// Returns the value stored at the given index.
55 ///
56 /// # Errors
57 ///
58 /// Returns [`MapError::OutOfBounds`] if `index` is out of bounds, [`MapError::SyscallError`]
59 /// if `bpf_map_lookup_elem` fails.
60 pub fn get(&self, index: &u32, flags: u64) -> Result<V, MapError> {
61 let data = self.inner.borrow();
62 check_bounds(data, *index)?;
63 hash_map::get(data, index, flags)
64 }
65
66 /// An iterator over the elements of the array. The iterator item type is `Result<V,
67 /// MapError>`.
68 pub fn iter(&self) -> impl Iterator<Item = Result<V, MapError>> + '_ {
69 (0..self.len()).map(move |i| self.get(&i, 0))
70 }
71}
72
73impl<T: BorrowMut<MapData>, V: Pod> Array<T, V> {
74 /// Sets the value of the element at the given index.
75 ///
76 /// # Errors
77 ///
78 /// Returns [`MapError::OutOfBounds`] if `index` is out of bounds, [`MapError::SyscallError`]
79 /// if `bpf_map_update_elem` fails.
80 pub fn set(&mut self, index: u32, value: impl Borrow<V>, flags: u64) -> Result<(), MapError> {
81 let data = self.inner.borrow_mut();
82 check_bounds(data, index)?;
83 hash_map::insert(data, &index, value.borrow(), flags)
84 }
85}
86
87impl<T: Borrow<MapData>, V: Pod> IterableMap<u32, V> for Array<T, V> {
88 fn map(&self) -> &MapData {
89 self.inner.borrow()
90 }
91
92 fn get(&self, key: &u32) -> Result<V, MapError> {
93 self.get(key, 0)
94 }
95}