[pvmfw] Define RangeExt trait on Range datatype
'is_within' of within RangeExt trait helps test if one range is
contained within another range. This will avoid duplicating the same
code in multiple places.
Test: m pvmfw_img
Bug: 271493784
Change-Id: I3fb76706620593efb45ce607eaf61d280c5a4a6c
diff --git a/pvmfw/src/helpers.rs b/pvmfw/src/helpers.rs
index 1f0a764..933a6aa 100644
--- a/pvmfw/src/helpers.rs
+++ b/pvmfw/src/helpers.rs
@@ -15,6 +15,7 @@
//! Miscellaneous helper functions.
use core::arch::asm;
+use core::ops::Range;
use zeroize::Zeroize;
pub const SIZE_4KB: usize = 4 << 10;
@@ -163,6 +164,18 @@
unsafe { core::slice::from_raw_parts(original.as_ptr().cast(), len) }
}
+/// Trait to check containment of one range within another.
+pub(crate) trait RangeExt {
+ /// Returns true if `self` is contained within the `other` range.
+ fn is_within(&self, other: &Self) -> bool;
+}
+
+impl<T: PartialOrd> RangeExt for Range<T> {
+ fn is_within(&self, other: &Self) -> bool {
+ self.start >= other.start && self.end <= other.end
+ }
+}
+
/// Create &CStr out of &str literal
#[macro_export]
macro_rules! cstr {
diff --git a/pvmfw/src/memory.rs b/pvmfw/src/memory.rs
index 7df25f2..714815b 100644
--- a/pvmfw/src/memory.rs
+++ b/pvmfw/src/memory.rs
@@ -16,7 +16,7 @@
#![deny(unsafe_op_in_unsafe_fn)]
-use crate::helpers::{self, align_down, align_up, page_4kb_of, SIZE_4KB, SIZE_4MB};
+use crate::helpers::{self, align_down, align_up, page_4kb_of, RangeExt, SIZE_4KB, SIZE_4MB};
use crate::mmu;
use alloc::alloc::alloc_zeroed;
use alloc::alloc::dealloc;
@@ -65,8 +65,7 @@
/// True if the instance is fully contained within the passed range.
pub fn is_within(&self, range: &MemoryRange) -> bool {
- let our: &MemoryRange = self.as_ref();
- self.as_ref() == &(max(our.start, range.start)..min(our.end, range.end))
+ self.as_ref().is_within(range)
}
}