Skip to content

Commit 4904d3c

Browse files
committed
mock: introduce RingAccess trait for endianness conversion
Implements a trait for generic conversion to and from little-endian for ring element types. This allows future safe handling of endianness for all queue fields. Signed-off-by: Nelson Wong <[email protected]>
1 parent d3795a5 commit 4904d3c

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

virtio-queue/src/mock.rs

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,9 +117,37 @@ impl<'a, M: GuestMemory, T: ByteValued> ArrayRef<'a, M, T> {
117117
}
118118
}
119119

120+
/// Trait for converting queue values to and from little-endian representation.
121+
pub trait RingAccess: ByteValued + Copy {
122+
/// Convert from host to little-endian.
123+
fn to_le(self) -> Self;
124+
/// Convert from little-endian to host.
125+
fn from_le(val: Self) -> Self;
126+
}
127+
128+
impl RingAccess for u16 {
129+
fn to_le(self) -> Self {
130+
u16::to_le(self)
131+
}
132+
133+
fn from_le(val: Self) -> Self {
134+
u16::from_le(val)
135+
}
136+
}
137+
138+
impl RingAccess for VirtqUsedElem {
139+
fn to_le(self) -> Self {
140+
self
141+
}
142+
143+
fn from_le(val: Self) -> Self {
144+
val
145+
}
146+
}
147+
120148
/// Represents a virtio queue ring. The only difference between the used and available rings,
121149
/// is the ring element type.
122-
pub struct SplitQueueRing<'a, M, T: ByteValued> {
150+
pub struct SplitQueueRing<'a, M, T: RingAccess> {
123151
flags: Ref<'a, M, u16>,
124152
// The value stored here should more precisely be a `Wrapping<u16>`, but that would require a
125153
// `ByteValued` impl for this type, which is not provided in vm-memory. Implementing the trait
@@ -131,7 +159,7 @@ pub struct SplitQueueRing<'a, M, T: ByteValued> {
131159
event: Ref<'a, M, u16>,
132160
}
133161

134-
impl<'a, M: GuestMemory, T: ByteValued> SplitQueueRing<'a, M, T> {
162+
impl<'a, M: GuestMemory, T: RingAccess> SplitQueueRing<'a, M, T> {
135163
/// Create a new `SplitQueueRing` instance
136164
pub fn new(mem: &'a M, base: GuestAddress, len: u16) -> Self {
137165
let event_addr = base

0 commit comments

Comments
 (0)