use crate::{Bytes, Result};
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Gpu {
pub name: String,
pub vendor: GpuVendor,
pub kind: GpuKind,
pub vendor_id: Option<u16>,
pub device_id: Option<u16>,
pub memory: Option<Bytes>,
pub driver: Option<String>,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[non_exhaustive]
pub enum GpuVendor {
Nvidia,
Amd,
Intel,
Apple,
Qualcomm,
Arm,
Microsoft,
Vmware,
Other,
}
impl GpuVendor {
#[must_use]
pub const fn from_pci(id: u16) -> GpuVendor {
match id {
0x10de => Self::Nvidia,
0x1002 | 0x1022 => Self::Amd,
0x8086 => Self::Intel,
0x106b => Self::Apple,
0x5143 | 0x17cb => Self::Qualcomm,
0x13b5 => Self::Arm,
0x1414 => Self::Microsoft,
0x15ad => Self::Vmware,
_ => Self::Other,
}
}
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::Nvidia => "NVIDIA",
Self::Amd => "AMD",
Self::Intel => "Intel",
Self::Apple => "Apple",
Self::Qualcomm => "Qualcomm",
Self::Arm => "Arm",
Self::Microsoft => "Microsoft",
Self::Vmware => "VMware",
Self::Other => "Other",
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[non_exhaustive]
pub enum GpuKind {
Integrated,
Discrete,
Virtual,
Unknown,
}
#[allow(dead_code)] pub(crate) const fn kind_of(vendor: GpuVendor) -> GpuKind {
match vendor {
GpuVendor::Intel | GpuVendor::Apple | GpuVendor::Qualcomm | GpuVendor::Arm => {
GpuKind::Integrated
}
GpuVendor::Nvidia => GpuKind::Discrete,
GpuVendor::Microsoft | GpuVendor::Vmware => GpuKind::Virtual,
GpuVendor::Amd | GpuVendor::Other => GpuKind::Unknown,
}
}
pub fn list() -> Result<Vec<Gpu>> {
crate::sys::gpus()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_gpu_vendor_from_pci() {
assert_eq!(GpuVendor::from_pci(0x10de), GpuVendor::Nvidia);
assert_eq!(GpuVendor::from_pci(0x1002), GpuVendor::Amd);
assert_eq!(GpuVendor::from_pci(0x8086), GpuVendor::Intel);
assert_eq!(GpuVendor::from_pci(0x1234), GpuVendor::Other);
assert_eq!(kind_of(GpuVendor::Nvidia), GpuKind::Discrete);
assert_eq!(kind_of(GpuVendor::Amd), GpuKind::Unknown);
}
#[test]
fn test_gpu_live_list_or_unavailable() {
match list() {
Ok(list) => {
for g in list {
assert!(!g.name.is_empty(), "{g:?}");
}
}
Err(e) => assert!(e.is_unavailable(), "{e}"),
}
}
}