From 4dc01f64dd3b9decd6893d2f373cc1595fdeef88 Mon Sep 17 00:00:00 2001 From: Alessandro Decina Date: Thu, 21 Jan 2021 08:07:36 +0000 Subject: [PATCH] bpf: make map() and map_mut() optionally return concrete map types map() and map_mut() used to return Ref, 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(); --- src/bpf.rs | 25 +++++++++++++++++++------ src/programs/trace_point.rs | 2 +- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/src/bpf.rs b/src/bpf.rs index e4221de3..00439a1f 100644 --- a/src/bpf.rs +++ b/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> { - self.maps.get(name).map(|cell| cell.borrow()) - } - - pub fn map_mut(&self, name: &str) -> Option> { - self.maps.get(name).map(|cell| cell.borrow_mut()) + pub fn map<'a, 'slf: 'a, T: TryFrom>>( + &'slf self, + name: &str, + ) -> Result, >>::Error> { + self.maps + .get(name) + .map(|cell| T::try_from(cell.borrow())) + .transpose() + } + + pub fn map_mut<'a, 'slf: 'a, T: TryFrom>>( + &'slf self, + name: &str, + ) -> Result, >>::Error> { + self.maps + .get(name) + .map(|cell| T::try_from(cell.borrow_mut())) + .transpose() } pub fn program(&self, name: &str) -> Option<&Program> { diff --git a/src/programs/trace_point.rs b/src/programs/trace_point.rs index d7f2fe60..474edd2a 100644 --- a/src/programs/trace_point.rs +++ b/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,