bpf_api/collections/
array.rs

1use crate::error::Error;
2use crate::platform::{Map, MapType};
3
4/// An array that exposes an idiomatic Rust interface to an underlying BPF array.
5pub struct Array<V: Copy + Default> {
6    map: Map<u32, V>,
7}
8
9impl<V: Copy + Default> Array<V> {
10    /// Creates a new BPF array with `entries` elements. The kernel
11    /// zero-initializes all elements on creation.
12    ///
13    /// # Arguments
14    ///
15    /// * `entries` - The number of elements in the array.
16    ///
17    /// # Example
18    /// ```
19    /// use bpf_api::collections::Array;
20    ///
21    /// let array = Array::<u32>::with_capacity(10).expect("Failed to create array");
22    /// ```
23    pub fn with_capacity(entries: u32) -> Result<Self, Error> {
24        Ok(Self {
25            map: Map::with_capacity(MapType::Array, entries)?,
26        })
27    }
28
29    /// Retrieves the value for a given element.
30    ///
31    /// # Arguments
32    ///
33    /// * `index` - The element index to retrieve.
34    ///
35    /// # Example
36    /// ```
37    /// use bpf_api::collections::Array;
38    ///
39    /// let array = Array::<u32>::with_capacity(10).expect("Failed to create array");
40    /// assert_eq!(array.get(5).expect("Failed to get element 5"), 0);
41    /// ```
42    pub fn get(&self, index: u32) -> Result<V, Error> {
43        self.map.get(&index)
44    }
45
46    /// Sets the value at a given index.
47    ///
48    /// # Arguments
49    ///
50    /// * `index` - The element index to retrieve.
51    /// * `value` - The new value.
52    ///
53    /// # Example
54    /// ```
55    /// use bpf_api::collections::Array;
56    ///
57    /// let array = Array::<u32>::with_capacity(10).expect("Failed to create array");
58    /// assert_eq!(array.get(5).expect("Failed to get element 5"), 0);
59    /// assert!(matches!(array.set(5, 10), Ok(_)));
60    /// assert_eq!(array.get(5).expect("Failed to get element 5"), 10);
61    /// ```
62    pub fn set(&self, index: u32, value: V) -> Result<(), Error> {
63        self.map.set(&index, &value)
64    }
65
66    /// Retrieve the BPF identifier for this map. This is the underlying file
67    /// descriptor that's used in eBPF programs.
68    ///
69    /// # Example
70    /// ```
71    /// use bpf_api::collections::Array;
72    ///
73    /// let array = Array::<u32>::with_capacity(10).expect("Failed to create array");
74    /// array.get_identifier();
75    /// ```
76    pub fn get_identifier(&self) -> u32 {
77        self.map.get_identifier()
78    }
79}