瀏覽代碼

Implement From for DeviceType rather than using transmute.

Andrew Walbran 2 年之前
父節點
當前提交
86df3df767
共有 2 個文件被更改,包括 44 次插入4 次删除
  1. 2 4
      src/transport/mmio.rs
  2. 42 0
      src/transport/mod.rs

+ 2 - 4
src/transport/mmio.rs

@@ -311,10 +311,8 @@ impl MmioTransport {
 impl Transport for MmioTransport {
 impl Transport for MmioTransport {
     fn device_type(&self) -> DeviceType {
     fn device_type(&self) -> DeviceType {
         // Safe because self.header points to a valid VirtIO MMIO region.
         // Safe because self.header points to a valid VirtIO MMIO region.
-        match unsafe { volread!(self.header, device_id) } {
-            x @ 1..=13 | x @ 16..=24 => unsafe { core::mem::transmute(x as u8) },
-            _ => DeviceType::Invalid,
-        }
+        let device_id = unsafe { volread!(self.header, device_id) };
+        device_id.into()
     }
     }
 
 
     fn read_device_features(&mut self) -> u64 {
     fn read_device_features(&mut self) -> u64 {

+ 42 - 0
src/transport/mod.rs

@@ -135,3 +135,45 @@ pub enum DeviceType {
     IOMMU = 23,
     IOMMU = 23,
     Memory = 24,
     Memory = 24,
 }
 }
+
+impl From<u32> for DeviceType {
+    fn from(virtio_device_id: u32) -> Self {
+        match virtio_device_id {
+            1 => DeviceType::Network,
+            2 => DeviceType::Block,
+            3 => DeviceType::Console,
+            4 => DeviceType::EntropySource,
+            5 => DeviceType::MemoryBalloon,
+            6 => DeviceType::IoMemory,
+            7 => DeviceType::Rpmsg,
+            8 => DeviceType::ScsiHost,
+            9 => DeviceType::_9P,
+            10 => DeviceType::Mac80211,
+            11 => DeviceType::RprocSerial,
+            12 => DeviceType::VirtioCAIF,
+            13 => DeviceType::MemoryBalloon,
+            16 => DeviceType::GPU,
+            17 => DeviceType::Timer,
+            18 => DeviceType::Input,
+            19 => DeviceType::Socket,
+            20 => DeviceType::Crypto,
+            21 => DeviceType::SignalDistributionModule,
+            22 => DeviceType::Pstore,
+            23 => DeviceType::IOMMU,
+            24 => DeviceType::Memory,
+            _ => DeviceType::Invalid,
+        }
+    }
+}
+
+impl From<u16> for DeviceType {
+    fn from(virtio_device_id: u16) -> Self {
+        u32::from(virtio_device_id).into()
+    }
+}
+
+impl From<u8> for DeviceType {
+    fn from(virtio_device_id: u8) -> Self {
+        u32::from(virtio_device_id).into()
+    }
+}