|
| 1 | +// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause |
| 3 | + |
| 4 | +//! Contains a generic implementation of `BitmapSlice`. |
| 5 | +
|
| 6 | +use std::fmt::{self, Debug}; |
| 7 | + |
| 8 | +use crate::bitmap::{Bitmap, BitmapSlice, WithBitmapSlice}; |
| 9 | + |
| 10 | +/// Represents a slice into a `Bitmap` object, starting at `base_offset`. |
| 11 | +pub struct RefSlice<'a, B> { |
| 12 | + inner: &'a B, |
| 13 | + base_offset: usize, |
| 14 | +} |
| 15 | + |
| 16 | +impl<'a, B: Bitmap + 'a> RefSlice<'a, B> { |
| 17 | + /// Create a new `BitmapSlice`, starting at the specified `offset`. |
| 18 | + pub fn new(bitmap: &'a B, offset: usize) -> Self { |
| 19 | + RefSlice { |
| 20 | + inner: bitmap, |
| 21 | + base_offset: offset, |
| 22 | + } |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +impl<'a, B: Bitmap> WithBitmapSlice<'a> for RefSlice<'_, B> { |
| 27 | + type S = Self; |
| 28 | +} |
| 29 | + |
| 30 | +impl<B: Bitmap> BitmapSlice for RefSlice<'_, B> {} |
| 31 | + |
| 32 | +impl<'a, B: Bitmap> Bitmap for RefSlice<'a, B> { |
| 33 | + /// Mark the memory range specified by the given `offset` (relative to the base offset of |
| 34 | + /// the slice) and `len` as dirtied. |
| 35 | + fn mark_dirty(&self, offset: usize, len: usize) { |
| 36 | + // The `Bitmap` operations are supposed to accompany guest memory accesses defined by the |
| 37 | + // same parameters (i.e. offset & length), so we use simple wrapping arithmetic instead of |
| 38 | + // performing additional checks. If an overflow would occur, we simply end up marking some |
| 39 | + // other region as dirty (which is just a false positive) instead of a region that could |
| 40 | + // not have been accessed to begin with. |
| 41 | + self.inner |
| 42 | + .mark_dirty(self.base_offset.wrapping_add(offset), len) |
| 43 | + } |
| 44 | + |
| 45 | + fn dirty_at(&self, offset: usize) -> bool { |
| 46 | + self.inner.dirty_at(self.base_offset.wrapping_add(offset)) |
| 47 | + } |
| 48 | + |
| 49 | + /// Create a new `BitmapSlice` starting from the specified `offset` into the current slice. |
| 50 | + fn slice_at(&self, offset: usize) -> Self { |
| 51 | + RefSlice { |
| 52 | + inner: self.inner, |
| 53 | + base_offset: self.base_offset.wrapping_add(offset), |
| 54 | + } |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +impl<'a, B> Clone for RefSlice<'a, B> { |
| 59 | + fn clone(&self) -> Self { |
| 60 | + RefSlice { |
| 61 | + inner: self.inner, |
| 62 | + base_offset: self.base_offset, |
| 63 | + } |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +impl<'a, B> Copy for RefSlice<'a, B> {} |
| 68 | + |
| 69 | +impl<'a, B> Debug for RefSlice<'a, B> { |
| 70 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 71 | + // Dummy impl for now. |
| 72 | + write!(f, "(bitmap slice)") |
| 73 | + } |
| 74 | +} |
0 commit comments