Skip to content

Commit 5a3a0bf

Browse files
roypatbonzini
authored andcommitted
Clarify behavior of VolatileMemory::compute_end_offset
Fix the doc comment, and add a unit test for this functions. Particularly the "allow length 0 accesses at the end of the slice" behavior was undocumented before. Signed-off-by: Patrick Roy <roypat@amazon.co.uk>
1 parent 5ebe19d commit 5a3a0bf

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

src/volatile_memory.rs

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,18 @@ pub trait VolatileMemory {
276276
unsafe { Ok(&*(slice.addr as *const T)) }
277277
}
278278

279-
/// Returns the sum of `base` and `offset` if the resulting address is valid.
279+
/// Returns the sum of `base` and `offset` if it is valid to access a range of `offset`
280+
/// bytes starting at `base`.
281+
///
282+
/// Specifically, allows accesses of length 0 at the end of a slice:
283+
///
284+
/// ```rust
285+
/// # use vm_memory::{VolatileMemory, VolatileSlice};
286+
/// let mut arr = [1, 2, 3];
287+
/// let slice = VolatileSlice::from(arr.as_mut_slice());
288+
///
289+
/// assert_eq!(slice.compute_end_offset(3, 0).unwrap(), 3);
290+
/// ```
280291
fn compute_end_offset(&self, base: usize, offset: usize) -> Result<usize> {
281292
let mem_end = compute_offset(base, offset)?;
282293
if mem_end > self.len() {
@@ -1662,6 +1673,28 @@ mod tests {
16621673

16631674
const DEFAULT_PAGE_SIZE: NonZeroUsize = unsafe { NonZeroUsize::new_unchecked(0x1000) };
16641675

1676+
#[test]
1677+
fn test_compute_end_offset() {
1678+
let mut array = [1, 2, 3, 4, 5];
1679+
let slice = VolatileSlice::from(array.as_mut_slice());
1680+
1681+
// Iterate over all valid ranges, assert that they pass validation.
1682+
// This includes edge cases such as len = 0 and base = 5!
1683+
for len in 0..slice.len() {
1684+
for base in 0..=slice.len() - len {
1685+
assert_eq!(
1686+
slice.compute_end_offset(base, len).unwrap(),
1687+
len + base,
1688+
"compute_end_offset rejected valid base/offset pair {base} + {len}"
1689+
);
1690+
}
1691+
}
1692+
1693+
// Check invalid configurations
1694+
slice.compute_end_offset(5, 1).unwrap_err();
1695+
slice.compute_end_offset(6, 0).unwrap_err();
1696+
}
1697+
16651698
#[test]
16661699
fn test_display_error() {
16671700
assert_eq!(

0 commit comments

Comments
 (0)