libfdt: Make Phandle::new() const
Decouple the definition of valid phandle values enforced by
Phandle::new() from the FdtError type and allow callers to generate a
libfdt::Result<Phandle> by implementing the standard TryFrom trait.
This was initially intended to be used in const expressions e.g.
const PHANDLE: Phandle = Phandle::new().unwrap();
but this will actually required stabilization of const_option first. For
now, the constructor is at least marked const.
Test: atest liblibfdt.integration_test
Change-Id: Ib9893595b1dd3972782e488f087fec2872679293
diff --git a/libs/libfdt/tests/api_test.rs b/libs/libfdt/tests/api_test.rs
index 61503eb..bd2b306 100644
--- a/libs/libfdt/tests/api_test.rs
+++ b/libs/libfdt/tests/api_test.rs
@@ -142,10 +142,30 @@
#[test]
fn phandle_new() {
- let phandle_u32 = 0x55;
- let phandle = Phandle::new(phandle_u32).unwrap();
+ let valid_phandles = [
+ u32::from(Phandle::MIN),
+ u32::from(Phandle::MIN).checked_add(1).unwrap(),
+ 0x55,
+ u32::from(Phandle::MAX).checked_sub(1).unwrap(),
+ u32::from(Phandle::MAX),
+ ];
- assert_eq!(u32::from(phandle), phandle_u32);
+ for value in valid_phandles {
+ let phandle = Phandle::new(value).unwrap();
+
+ assert_eq!(value.try_into(), Ok(phandle));
+ assert_eq!(u32::from(phandle), value);
+ }
+
+ let bad_phandles = [
+ u32::from(Phandle::MIN).checked_sub(1).unwrap(),
+ u32::from(Phandle::MAX).checked_add(1).unwrap(),
+ ];
+
+ for value in bad_phandles {
+ assert_eq!(Phandle::new(value), None);
+ assert_eq!(Phandle::try_from(value), Err(FdtError::BadPhandle));
+ }
}
#[test]