Skip to content

Commit 1b2fa2d

Browse files
rbartlenskydanielocfb
authored andcommitted
Implement conversions between u32 and Linkage.
Tests ensure that we didn't mess anything up.
1 parent a0ce085 commit 1b2fa2d

File tree

1 file changed

+32
-5
lines changed

1 file changed

+32
-5
lines changed

libbpf-rs/src/btf/types.rs

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,6 @@ use std::fmt;
55
use std::fmt::Display;
66
use std::ops::Deref;
77

8-
use num_enum::IntoPrimitive;
9-
use num_enum::TryFromPrimitive;
10-
118
use super::BtfKind;
129
use super::BtfType;
1310
use super::HasSize;
@@ -277,7 +274,7 @@ impl MemberAttr {
277274
}
278275

279276
/// The kind of linkage a variable of function can have.
280-
#[derive(TryFromPrimitive, IntoPrimitive, Debug, Clone, Copy, PartialEq, Eq, Hash)]
277+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
281278
#[repr(u32)]
282279
pub enum Linkage {
283280
/// Static linkage
@@ -290,6 +287,25 @@ pub enum Linkage {
290287
Unknown,
291288
}
292289

290+
impl From<u32> for Linkage {
291+
fn from(value: u32) -> Self {
292+
use Linkage::*;
293+
294+
match value {
295+
x if x == Static as u32 => Static,
296+
x if x == Global as u32 => Global,
297+
x if x == Extern as u32 => Extern,
298+
_ => Unknown,
299+
}
300+
}
301+
}
302+
303+
impl From<Linkage> for u32 {
304+
fn from(value: Linkage) -> Self {
305+
value as u32
306+
}
307+
}
308+
293309
impl Display for Linkage {
294310
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
295311
write!(
@@ -679,7 +695,7 @@ impl Func<'_> {
679695
/// This function's linkage.
680696
#[inline]
681697
pub fn linkage(&self) -> Linkage {
682-
self.source.vlen().try_into().unwrap_or(Linkage::Unknown)
698+
self.source.vlen().into()
683699
}
684700
}
685701

@@ -1157,4 +1173,15 @@ mod test {
11571173
}
11581174
});
11591175
}
1176+
1177+
#[test]
1178+
fn linkage_type() {
1179+
use std::mem::discriminant;
1180+
use Linkage::*;
1181+
1182+
for t in [Static, Global, Extern, Unknown] {
1183+
// check if discriminants match after a roundtrip conversion
1184+
assert_eq!(discriminant(&t), discriminant(&Linkage::from(t as u32)));
1185+
}
1186+
}
11601187
}

0 commit comments

Comments
 (0)