vm-virtio: Define and implement Translatable trait

This new trait simplifies the address translation of a GuestAddress by
having GuestAddress implementing it.

The three crates virtio-devices, block_util and net_util have been
updated accordingly to rely on this new trait, helping with code
readability and limiting the amount of duplicated code.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
This commit is contained in:
Sebastien Boeuf
2022-01-26 23:44:31 +01:00
committed by Rob Bradford
parent c99d637693
commit 77df4e6773
8 changed files with 106 additions and 205 deletions

View File

@@ -11,6 +11,9 @@
//! Implements virtio queues
use std::fmt::{self, Debug};
use std::sync::Arc;
use vm_memory::GuestAddress;
pub mod queue;
pub use queue::*;
@@ -94,3 +97,18 @@ pub trait AccessPlatform: Send + Sync + Debug {
/// Provide a way to translate address ranges.
fn translate(&self, base: u64, size: u64) -> std::result::Result<u64, std::io::Error>;
}
pub trait Translatable {
#[must_use]
fn translate(&self, access_platform: Option<&Arc<dyn AccessPlatform>>, len: usize) -> Self;
}
impl Translatable for GuestAddress {
fn translate(&self, access_platform: Option<&Arc<dyn AccessPlatform>>, len: usize) -> Self {
if let Some(access_platform) = access_platform {
GuestAddress(access_platform.translate(self.0, len as u64).unwrap())
} else {
*self
}
}
}