From ce3f83acb11388f2c0b07a8b1de95c7df22b97f9 Mon Sep 17 00:00:00 2001 From: Alessandro Decina Date: Sat, 6 Mar 2021 09:57:25 +0000 Subject: [PATCH] aya: add HashMap docs --- aya/src/maps/hash_map.rs | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/aya/src/maps/hash_map.rs b/aya/src/maps/hash_map.rs index f9f48ae5..29c7e7ac 100644 --- a/aya/src/maps/hash_map.rs +++ b/aya/src/maps/hash_map.rs @@ -1,3 +1,4 @@ +//! Hash map types. use std::{ convert::TryFrom, marker::PhantomData, @@ -9,13 +10,29 @@ use std::{ use crate::{ generated::bpf_map_type::BPF_MAP_TYPE_HASH, maps::{IterableMap, Map, MapError, MapIter, MapKeys, MapRef, MapRefMut}, - sys::{ - bpf_map_delete_elem, bpf_map_lookup_and_delete_elem, bpf_map_lookup_elem, - bpf_map_update_elem, - }, + sys::{bpf_map_delete_elem, bpf_map_lookup_elem, bpf_map_update_elem}, Pod, }; +/// A hash map stored inside the kernel, in which both user-space and eBPF programs can insert and +/// lookup values from. +/// +/// The types of the keys and values must be plain old data (POD), meaning that they +/// must be safely convertible to and from byte slices. +/// +/// # Example +/// +/// ```no_run +/// # let bpf = aya::Bpf::load(&[], None)?; +/// use aya::maps::HashMap; +/// use std::convert::TryFrom; +/// +/// const CONFIG_KEY_NUM_RETRIES: u8 = 1; +/// +/// let mut hm = HashMap::try_from(bpf.map_mut("CONFIG")?)?; +/// hm.insert(CONFIG_KEY_NUM_RETRIES, 3, 0 /* flags */); +/// # Ok::<(), aya::BpfError>(()) +/// ``` pub struct HashMap, K, V> { inner: T, _k: PhantomData, @@ -54,6 +71,7 @@ impl, K: Pod, V: Pod> HashMap { }) } + /// Returns a copy of the value associated with the key. pub unsafe fn get(&self, key: &K, flags: u64) -> Result, MapError> { let fd = self.inner.deref().fd_or_err()?; bpf_map_lookup_elem(fd, key, flags).map_err(|(code, io_error)| MapError::SyscallError { @@ -63,16 +81,21 @@ impl, K: Pod, V: Pod> HashMap { }) } + /// An iterator visiting all key-value pairs in arbitrary order. The + /// iterator item type is `Result<(K, V), MapError>`. pub unsafe fn iter<'coll>(&'coll self) -> MapIter<'coll, K, V> { MapIter::new(self) } + /// An iterator visiting all keys in arbitrary order. The iterator element + /// type is `Result`. pub unsafe fn keys<'coll>(&'coll self) -> MapKeys<'coll, K, V> { MapKeys::new(self) } } impl, K: Pod, V: Pod> HashMap { + /// Inserts a key-value pair into the map. pub fn insert(&mut self, key: K, value: V, flags: u64) -> Result<(), MapError> { let fd = self.inner.deref_mut().fd_or_err()?; bpf_map_update_elem(fd, &key, &value, flags).map_err(|(code, io_error)| { @@ -85,6 +108,7 @@ impl, K: Pod, V: Pod> HashMap { Ok(()) } + /// Removes a key from the map. pub fn remove(&mut self, key: &K) -> Result<(), MapError> { let fd = self.inner.deref_mut().fd_or_err()?; bpf_map_delete_elem(fd, key)