Skip to content

Commit bb0e282

Browse files
d-e-s-oinsearchoflosttime
authored andcommitted
libbpf-cargo: Shorten some condition checks
We use the anyhow bail macro in ways that seem a bit convoluted in the presence of ensure (which is also already being used). Shorten some checks by switching over to using ensure instead. Signed-off-by: Daniel Müller <deso@posteo.net>
1 parent 721f42c commit bb0e282

File tree

1 file changed

+8
-16
lines changed

1 file changed

+8
-16
lines changed

libbpf-cargo/src/gen.rs

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -147,9 +147,7 @@ fn capitalize_first_letter(s: &str) -> String {
147147

148148
fn get_raw_map_name(map: *const libbpf_sys::bpf_map) -> Result<String> {
149149
let name_ptr = unsafe { libbpf_sys::bpf_map__name(map) };
150-
if name_ptr.is_null() {
151-
bail!("Map name unknown");
152-
}
150+
ensure!(!name_ptr.is_null(), "Map name unknown");
153151

154152
Ok(unsafe { CStr::from_ptr(name_ptr) }.to_str()?.to_string())
155153
}
@@ -182,10 +180,7 @@ fn get_map_name(map: *const libbpf_sys::bpf_map) -> Result<Option<String>> {
182180

183181
fn get_prog_name(prog: *const libbpf_sys::bpf_program) -> Result<String> {
184182
let name_ptr = unsafe { libbpf_sys::bpf_program__name(prog) };
185-
186-
if name_ptr.is_null() {
187-
bail!("Prog name unknown");
188-
}
183+
ensure!(!name_ptr.is_null(), "Prog name unknown");
189184

190185
Ok(unsafe { CStr::from_ptr(name_ptr) }.to_str()?.to_string())
191186
}
@@ -615,9 +610,7 @@ fn open_bpf_object(name: &str, data: &[u8]) -> Result<BpfObj> {
615610
&obj_opts,
616611
)
617612
};
618-
if object.is_null() {
619-
bail!("Failed to bpf_object__open_mem()");
620-
}
613+
ensure!(!object.is_null(), "Failed to bpf_object__open_mem()");
621614

622615
Ok(BpfObj(ptr::NonNull::new(object).unwrap()))
623616
}
@@ -857,9 +850,7 @@ fn gen_skel(
857850
out: OutputDest,
858851
rustfmt_path: Option<&PathBuf>,
859852
) -> Result<()> {
860-
if name.is_empty() {
861-
bail!("Object file has no name");
862-
}
853+
ensure!(!name.is_empty(), "Object file has no name");
863854

864855
let skel = gen_skel_contents(debug, name, obj)?;
865856
let skel = try_rustfmt(&skel, rustfmt_path)?;
@@ -946,9 +937,10 @@ pub fn gen_single(
946937

947938
let name = match filename.to_str() {
948939
Some(n) => {
949-
if !n.ends_with(".o") {
950-
bail!("Object file does not have `.o` suffix: {}", n);
951-
}
940+
ensure!(
941+
n.ends_with(".o"),
942+
"Object file does not have `.o` suffix: {n}"
943+
);
952944

953945
n.split('.').next().unwrap()
954946
}

0 commit comments

Comments
 (0)