Add HashMap::from_map_data to allow safe creation from pinned maps

Issue: https://github.com/aya-rs/aya/issues/1305

This change introduces a public constructor `HashMap::from_map_data`, enabling safe and ergonomic creation of HashMap<MapData, K, V> from a pinned BPF map. Previously, this required reloading the full BPF object or using unsafe/private APIs.

Motivation:
- Simplifies accessing pinned maps in multi-threaded user space
- Avoids full BPF reloads and potential deadlocks
- Matches existing ergonomic APIs like LruHashMap::try_from
- Keeps user code safe and idiomatic

Includes test coverage to validate the new API.
reviewable/pr1306/r1
Adam Schreck 3 days ago
parent 44ec978bd3
commit 46d30c72f5

@ -101,6 +101,15 @@ impl<T: Borrow<MapData>, K: Pod, V: Pod> IterableMap<K, V> for HashMap<T, K, V>
}
}
impl<K: Pod, V: Pod> HashMap<MapData, K, V> {
/// Creates a `HashMap` from `MapData`, typically loaded from a pinned path.
///
/// This is useful when accessing a map from user-space without reloading the entire BPF object.
pub fn from_map_data(map_data: MapData) -> Result<Self, MapError> {
Self::new(map_data)
}
}
#[cfg(test)]
mod tests {
use std::io;
@ -514,4 +523,12 @@ mod tests {
assert_matches!(iter.next(), Some(Ok((30, 300))));
assert_matches!(iter.next(), None);
}
#[test]
fn test_from_map_data() {
let map = new_map(new_obj_map());
let map_data = map; // already a MapData
let map = HashMap::<_, u32, u32>::from_map_data(map_data);
assert!(map.is_ok());
}
}

Loading…
Cancel
Save