Преглед изворни кода

bpf: make map() and map_mut() optionally return concrete map types

map() and map_mut() used to return Ref<Map>, then to convert to a concrete
type you had to:

    let mut perf_map: PerfMap<_> = bpf.map_mut("PERF_MAP").unwrap().try_into()?;;

But the base Map type is pretty much only useful internally. This change
makes map() and map_mut() use TryInto internally, so that now
conversions can can be done with:

    let mut perf_map: PerfMap<_> = bpf.map_mut("PERF_MAP")?.unwrap();
Alessandro Decina пре 4 година
родитељ
комит
4dc01f64dd
2 измењених фајлова са 20 додато и 7 уклоњено
  1. 19 6
      src/bpf.rs
  2. 1 1
      src/programs/trace_point.rs

+ 19 - 6
src/bpf.rs

@@ -1,6 +1,7 @@
 use std::{
     cell::{Ref, RefCell, RefMut},
     collections::HashMap,
+    convert::TryFrom,
 };
 
 use thiserror::Error;
@@ -100,12 +101,24 @@ impl Bpf {
         })
     }
 
-    pub fn map(&self, name: &str) -> Option<Ref<'_, Map>> {
-        self.maps.get(name).map(|cell| cell.borrow())
-    }
-
-    pub fn map_mut(&self, name: &str) -> Option<RefMut<'_, Map>> {
-        self.maps.get(name).map(|cell| cell.borrow_mut())
+    pub fn map<'a, 'slf: 'a, T: TryFrom<Ref<'a, Map>>>(
+        &'slf self,
+        name: &str,
+    ) -> Result<Option<T>, <T as TryFrom<Ref<'a, Map>>>::Error> {
+        self.maps
+            .get(name)
+            .map(|cell| T::try_from(cell.borrow()))
+            .transpose()
+    }
+
+    pub fn map_mut<'a, 'slf: 'a, T: TryFrom<RefMut<'a, Map>>>(
+        &'slf self,
+        name: &str,
+    ) -> Result<Option<T>, <T as TryFrom<RefMut<'a, Map>>>::Error> {
+        self.maps
+            .get(name)
+            .map(|cell| T::try_from(cell.borrow_mut()))
+            .transpose()
     }
 
     pub fn program(&self, name: &str) -> Option<&Program> {

+ 1 - 1
src/programs/trace_point.rs

@@ -1,4 +1,4 @@
-use std::fs;
+use std::{convert::TryFrom, fs};
 
 use crate::{
     generated::bpf_prog_type::BPF_PROG_TYPE_TRACEPOINT, syscalls::perf_event_open_trace_point,