Skip to main content

axvirtio_common/
device_type.rs

1use core::fmt;
2
3/// VirtIO device types (simplified version)
4#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
5#[repr(u32)]
6pub enum VirtioDeviceID {
7    /// Invalid/Unknown device type
8    #[default]
9    Invalid = 0,
10
11    /// Network card device
12    Network = 1,
13
14    /// Block device
15    Block   = 2,
16
17    /// Console device
18    Console = 3,
19}
20
21impl VirtioDeviceID {
22    /// Convert device ID to device type
23    pub fn from_device_id(device_id: u32) -> Self {
24        match device_id {
25            0 => Self::Invalid,
26            1 => Self::Network,
27            2 => Self::Block,
28            3 => Self::Console,
29            _ => Self::Invalid,
30        }
31    }
32
33    /// Convert device type to device ID
34    pub fn to_device_id(&self) -> u32 {
35        *self as u32
36    }
37
38    /// Get the human-readable name of the device type
39    pub fn name(&self) -> &'static str {
40        match self {
41            Self::Invalid => "Invalid",
42            Self::Network => "Network",
43            Self::Block => "Block",
44            Self::Console => "Console",
45        }
46    }
47
48    /// Check if the device type is valid (not Invalid)
49    pub fn is_valid(&self) -> bool {
50        !matches!(self, Self::Invalid)
51    }
52
53    /// Get all supported device types
54    pub fn all_types() -> &'static [VirtioDeviceID] {
55        &[Self::Network, Self::Block, Self::Console]
56    }
57}
58
59impl From<u32> for VirtioDeviceID {
60    fn from(value: u32) -> Self {
61        Self::from_device_id(value)
62    }
63}
64
65impl From<usize> for VirtioDeviceID {
66    fn from(value: usize) -> Self {
67        Self::from_device_id(value as u32)
68    }
69}
70
71impl fmt::Display for VirtioDeviceID {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        write!(f, "{} ({})", self.name(), self.to_device_id())
74    }
75}