From 46d30c72f5d21c28768a5866a252c66de6998be0 Mon Sep 17 00:00:00 2001 From: Adam Schreck Date: Thu, 24 Jul 2025 01:11:15 +0000 Subject: [PATCH] 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 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. --- aya/src/maps/hash_map/hash_map.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/aya/src/maps/hash_map/hash_map.rs b/aya/src/maps/hash_map/hash_map.rs index e8d2c463..1e48ebe3 100644 --- a/aya/src/maps/hash_map/hash_map.rs +++ b/aya/src/maps/hash_map/hash_map.rs @@ -101,6 +101,15 @@ impl, K: Pod, V: Pod> IterableMap for HashMap } } +impl HashMap { + /// 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::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()); + } }