use std::path::Path;
const MAX_WEBGL_GPU_TOML_BYTES: u64 = 64 * 1024;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WebGlGpuPersona {
pub vendor: &'static str,
pub renderer: &'static str,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum WebGlGpuFamily {
Intel,
Nvidia,
Amd,
Apple,
Qualcomm,
Mesa,
Brave,
Microsoft,
Other,
}
impl WebGlGpuFamily {
pub fn coherent_with_platform(self, platform: &str) -> bool {
match self {
Self::Apple => platform == "MacIntel" || platform == "iPhone" || platform == "iPad",
_ => !matches!(platform, "MacIntel" | "iPhone" | "iPad"),
}
}
}
#[derive(Debug)]
pub enum WebGlGpuLoadError {
Read(String),
TooLarge {
path: String,
bytes: u64,
},
Parse(String),
Invalid {
index: usize,
reason: String,
},
}
impl std::fmt::Display for WebGlGpuLoadError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Read(e) => write!(f, "tier-b webgl-gpu: read failed: {e}"),
Self::TooLarge { path, bytes } => write!(
f,
"tier-b webgl-gpu: {path} is {bytes} bytes, over the {MAX_WEBGL_GPU_TOML_BYTES}-byte cap"
),
Self::Parse(e) => write!(f, "tier-b webgl-gpu: TOML parse failed: {e}"),
Self::Invalid { index, reason } => {
write!(f, "tier-b webgl-gpu: entry #{index} invalid: {reason}")
}
}
}
}
impl std::error::Error for WebGlGpuLoadError {}
#[derive(serde::Deserialize)]
struct GpuDoc {
vendor: String,
renderer: String,
}
#[derive(serde::Deserialize)]
struct GpusDoc {
#[serde(default)]
gpu: Vec<GpuDoc>,
}
pub fn webgl_gpu_vendor_family(vendor: &str) -> WebGlGpuFamily {
let lower = vendor.to_ascii_lowercase();
if lower.contains("intel") {
WebGlGpuFamily::Intel
} else if lower.contains("nvidia") {
WebGlGpuFamily::Nvidia
} else if lower.contains("amd") || lower.contains("radeon") {
WebGlGpuFamily::Amd
} else if lower.contains("apple") {
WebGlGpuFamily::Apple
} else if lower.contains("qualcomm") || lower.contains("adreno") {
WebGlGpuFamily::Qualcomm
} else if lower.contains("mesa") {
WebGlGpuFamily::Mesa
} else if lower.contains("brave") {
WebGlGpuFamily::Brave
} else if lower.contains("microsoft") {
WebGlGpuFamily::Microsoft
} else {
WebGlGpuFamily::Other
}
}
pub fn load_webgl_gpus_from_toml(path: &Path) -> Result<Vec<WebGlGpuPersona>, WebGlGpuLoadError> {
let meta = std::fs::metadata(path)
.map_err(|e| WebGlGpuLoadError::Read(format!("{}: {e}", path.display())))?;
if meta.len() > MAX_WEBGL_GPU_TOML_BYTES {
return Err(WebGlGpuLoadError::TooLarge {
path: path.display().to_string(),
bytes: meta.len(),
});
}
let raw = std::fs::read_to_string(path)
.map_err(|e| WebGlGpuLoadError::Read(format!("{}: {e}", path.display())))?;
let doc: GpusDoc = toml::from_str(&raw).map_err(|e| WebGlGpuLoadError::Parse(e.to_string()))?;
let mut out = Vec::with_capacity(doc.gpu.len());
for (idx, d) in doc.gpu.into_iter().enumerate() {
let index = idx + 1;
let invalid = |reason: &str| WebGlGpuLoadError::Invalid {
index,
reason: reason.to_string(),
};
let vendor = d.vendor.trim();
let renderer = d.renderer.trim();
if vendor.is_empty() {
return Err(invalid("empty vendor"));
}
if renderer.is_empty() {
return Err(invalid("empty renderer"));
}
let family = webgl_gpu_vendor_family(vendor);
if family == WebGlGpuFamily::Other {
return Err(invalid(&format!(
"unknown GPU vendor family for vendor {vendor:?}"
)));
}
let coherent_platform = match family {
WebGlGpuFamily::Apple => "MacIntel",
_ => "Win32",
};
if !family.coherent_with_platform(coherent_platform) {
return Err(invalid(&format!(
"vendor family {family:?} is incoherent with every known platform"
)));
}
out.push(WebGlGpuPersona {
vendor: Box::leak(vendor.to_string().into_boxed_str()),
renderer: Box::leak(renderer.to_string().into_boxed_str()),
});
}
Ok(out)
}
pub fn load_webgl_gpu_directory(dir: &Path) -> Result<Vec<WebGlGpuPersona>, WebGlGpuLoadError> {
let mut entries: Vec<_> = std::fs::read_dir(dir)
.map_err(|e| WebGlGpuLoadError::Read(format!("{}: {e}", dir.display())))?
.filter_map(|e| e.ok())
.filter(|e| {
e.path()
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("toml"))
})
.map(|e| e.path())
.collect();
entries.sort();
let mut out = Vec::new();
for path in entries {
out.extend(load_webgl_gpus_from_toml(&path)?);
}
Ok(out)
}
#[cfg(test)]
#[path = "webgl_gpu_tier_b/tests.rs"]
mod tests;