use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::fmt::{Display, Formatter};
use std::hash::{Hash, Hasher};
use std::path::PathBuf;
use std::str::FromStr;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
pub const SCHEMA_VERSION: u32 = 1;
pub(crate) fn is_unsafe_terminal_character(character: char) -> bool {
character.is_control()
|| (character.is_whitespace() && character != ' ')
|| matches!(
character,
'\u{00ad}'
| '\u{0600}'..='\u{0605}'
| '\u{061c}'
| '\u{06dd}'
| '\u{070f}'
| '\u{0890}'..='\u{0891}'
| '\u{08e2}'
| '\u{180e}'
| '\u{200b}'..='\u{200f}'
| '\u{2028}'..='\u{202e}'
| '\u{2060}'..='\u{2064}'
| '\u{2066}'..='\u{206f}'
| '\u{feff}'
| '\u{fff9}'..='\u{fffb}'
| '\u{110bd}'
| '\u{110cd}'
| '\u{13430}'..='\u{1343f}'
| '\u{1bca0}'..='\u{1bca3}'
| '\u{1d173}'..='\u{1d17a}'
| '\u{e0001}'
| '\u{e0020}'..='\u{e007f}'
)
}
#[derive(Debug, Clone)]
pub struct NumericVersion {
components: Vec<u32>,
representation: String,
}
impl NumericVersion {
pub fn new(components: Vec<u32>) -> Result<Self, VersionParseError> {
if components.is_empty() {
return Err(VersionParseError::Empty);
}
let representation = components
.iter()
.map(u32::to_string)
.collect::<Vec<_>>()
.join(".");
Ok(Self {
components,
representation,
})
}
pub fn components(&self) -> &[u32] {
&self.components
}
pub fn component(&self, index: usize) -> u32 {
self.components.get(index).copied().unwrap_or(0)
}
}
impl PartialEq for NumericVersion {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for NumericVersion {}
impl Hash for NumericVersion {
fn hash<H: Hasher>(&self, state: &mut H) {
let significant_len = self
.components
.iter()
.rposition(|component| *component != 0)
.map_or(1, |index| index + 1);
self.components[..significant_len].hash(state);
}
}
impl FromStr for NumericVersion {
type Err = VersionParseError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
let value = value.trim();
if value.is_empty() {
return Err(VersionParseError::Empty);
}
let mut components = Vec::new();
for part in value.split('.') {
if part.is_empty() || !part.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(VersionParseError::InvalidComponent(part.to_owned()));
}
components.push(
part.parse::<u32>()
.map_err(|_| VersionParseError::Overflow(part.to_owned()))?,
);
}
Ok(Self {
components,
representation: value.to_owned(),
})
}
}
impl Display for NumericVersion {
fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
formatter.write_str(&self.representation)
}
}
impl Ord for NumericVersion {
fn cmp(&self, other: &Self) -> Ordering {
let len = self.components.len().max(other.components.len());
(0..len)
.map(|index| self.component(index).cmp(&other.component(index)))
.find(|ordering| *ordering != Ordering::Equal)
.unwrap_or(Ordering::Equal)
}
}
impl PartialOrd for NumericVersion {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Serialize for NumericVersion {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.to_string())
}
}
impl<'de> Deserialize<'de> for NumericVersion {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
value.parse().map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Clone, Eq, PartialEq, thiserror::Error)]
pub enum VersionParseError {
#[error("version is empty")]
Empty,
#[error("invalid numeric version component: {0}")]
InvalidComponent(String),
#[error("numeric version component is too large: {0}")]
Overflow(String),
}
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum CudaVariant {
Cpu,
Cuda {
major: u16,
minor: u16,
},
}
impl CudaVariant {
pub fn cuda_version(&self) -> Option<(u16, u16)> {
match self {
Self::Cpu => None,
Self::Cuda { major, minor } => Some((*major, *minor)),
}
}
pub fn is_cuda(&self) -> bool {
matches!(self, Self::Cuda { .. })
}
}
impl Display for CudaVariant {
fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::Cpu => formatter.write_str("cpu"),
Self::Cuda { major, minor } => write!(formatter, "cu{major}{minor}"),
}
}
}
impl FromStr for CudaVariant {
type Err = CudaVariantParseError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
let normalized = value.trim().to_ascii_lowercase();
if normalized == "cpu" {
return Ok(Self::Cpu);
}
let digits = normalized
.strip_prefix("cu")
.ok_or_else(|| CudaVariantParseError(value.to_owned()))?;
if digits.len() < 2 || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(CudaVariantParseError(value.to_owned()));
}
let split = if digits.len() >= 3 { 2 } else { 1 };
let (major, minor) = digits.split_at(split);
let major = major
.parse::<u16>()
.map_err(|_| CudaVariantParseError(value.to_owned()))?;
let minor = minor
.parse::<u16>()
.map_err(|_| CudaVariantParseError(value.to_owned()))?;
Ok(Self::Cuda { major, minor })
}
}
impl Serialize for CudaVariant {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.to_string())
}
}
impl<'de> Deserialize<'de> for CudaVariant {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
value.parse().map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Clone, Eq, PartialEq, thiserror::Error)]
#[error("invalid CUDA variant: {0}")]
pub struct CudaVariantParseError(pub String);
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum OperatingSystem {
Linux,
Windows,
Macos,
Other(String),
}
impl Display for OperatingSystem {
fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::Linux => formatter.write_str("linux"),
Self::Windows => formatter.write_str("windows"),
Self::Macos => formatter.write_str("macos"),
Self::Other(name) => formatter.write_str(name),
}
}
}
impl Serialize for OperatingSystem {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.to_string())
}
}
impl<'de> Deserialize<'de> for OperatingSystem {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
Ok(match value.as_str() {
"linux" => Self::Linux,
"windows" => Self::Windows,
"macos" => Self::Macos,
_ => Self::Other(value),
})
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum Architecture {
X86_64,
Aarch64,
Other(String),
}
impl Display for Architecture {
fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::X86_64 => formatter.write_str("x86_64"),
Self::Aarch64 => formatter.write_str("aarch64"),
Self::Other(name) => formatter.write_str(name),
}
}
}
impl Serialize for Architecture {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.to_string())
}
}
impl<'de> Deserialize<'de> for Architecture {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
Ok(match value.as_str() {
"x86_64" | "amd64" => Self::X86_64,
"aarch64" | "arm64" => Self::Aarch64,
_ => Self::Other(value),
})
}
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct PlatformInfo {
pub os: OperatingSystem,
pub architecture: Architecture,
pub kernel_version: Option<String>,
pub distribution: Option<String>,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TagSource {
Packaging,
Builtin,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct PythonInfo {
pub executable: PathBuf,
pub implementation: String,
pub version: NumericVersion,
pub soabi: Option<String>,
pub cache_tag: Option<String>,
pub platform: String,
pub pointer_width: u16,
pub free_threaded: bool,
pub virtual_environment: Option<PathBuf>,
pub compatible_tags: Vec<String>,
pub tag_source: TagSource,
}
impl PythonInfo {
pub fn cpython_abi_tag(&self) -> Option<String> {
if self.implementation != "cpython" {
return None;
}
let suffix = if self.free_threaded { "t" } else { "" };
Some(format!(
"cp{}{}{}",
self.version.component(0),
self.version.component(1),
suffix
))
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub struct ComputeCapability {
pub major: u16,
pub minor: u16,
}
impl Display for ComputeCapability {
fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
write!(formatter, "{}.{}", self.major, self.minor)
}
}
impl FromStr for ComputeCapability {
type Err = VersionParseError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
let version: NumericVersion = value.parse()?;
Ok(Self {
major: u16::try_from(version.component(0))
.map_err(|_| VersionParseError::Overflow(value.to_owned()))?,
minor: u16::try_from(version.component(1))
.map_err(|_| VersionParseError::Overflow(value.to_owned()))?,
})
}
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct NvidiaGpu {
pub index: u32,
pub uuid: Option<String>,
pub name: String,
pub compute_capability: Option<ComputeCapability>,
pub driver_version: NumericVersion,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NvidiaDetectionStatus {
Detected,
CommandUnavailable,
NoDevices,
Failed,
TimedOut,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct NvidiaInfo {
pub status: NvidiaDetectionStatus,
pub driver_version: Option<NumericVersion>,
pub reported_cuda_version: Option<NumericVersion>,
pub gpus: Vec<NvidiaGpu>,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolkitSource {
CudaHome,
CudaPath,
Nvcc,
VersionJson,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct CudaToolkitInfo {
pub version: NumericVersion,
pub root: Option<PathBuf>,
pub source: ToolkitSource,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DiagnosticCode {
UnsupportedOperatingSystem,
UnsupportedArchitecture,
UnsupportedLibc,
GlibcUnknown,
PythonUnavailable,
UnsupportedPythonImplementation,
BuiltinPythonTags,
NvidiaSmiUnavailable,
NvidiaNoDevices,
NvidiaInspectionFailed,
NvidiaInspectionTimedOut,
ComputeCapabilityUnknown,
InvalidGpuSelection,
CudaVisibleDevicesSet,
InconsistentDriverVersions,
CudaToolkitNotFound,
CudnnInspectionFailed,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DiagnosticSeverity {
Info,
Warning,
Error,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct Diagnostic {
pub code: DiagnosticCode,
pub severity: DiagnosticSeverity,
pub details: BTreeMap<String, String>,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct Environment {
#[serde(flatten)]
pub platform: PlatformInfo,
pub glibc: Option<NumericVersion>,
pub python: Option<PythonInfo>,
pub nvidia: NvidiaInfo,
pub cuda_toolkit: Option<CudaToolkitInfo>,
pub diagnostics: Vec<Diagnostic>,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct TorchWheel {
pub package: String,
pub filename: String,
pub version: String,
pub public_version: String,
pub variant: CudaVariant,
pub python_tags: Vec<String>,
pub abi_tags: Vec<String>,
pub platform_tags: Vec<String>,
pub url: String,
pub sha256: Option<String>,
pub yanked: bool,
pub requires_python: Option<String>,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct IndexSnapshot {
pub schema_version: u32,
pub fetched_at: u64,
pub source: String,
pub packages: Vec<String>,
pub variants: Vec<CudaVariant>,
pub wheels: Vec<TorchWheel>,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MetadataOrigin {
Network,
FreshCache,
OfflineCache,
StaleIfError,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct MetadataInfo {
pub origin: MetadataOrigin,
pub fetched_at: u64,
pub age_seconds: u64,
pub stale: bool,
pub source: String,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CheckStatus {
Pass,
Fail,
Unknown,
NotApplicable,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReasonCode {
WheelExists,
WheelMissing,
PythonWheelMissing,
PythonTagMatches,
AbiTagMatches,
WheelYanked,
PlatformTagMatches,
PlatformMismatch,
GlibcTooOld,
GlibcUnknown,
DriverSupportsCudaFamily,
DriverSupportsCudaVariant,
UsesCudaMinorCompatibility,
DriverTooOld,
DriverUnknown,
DriverNotRequired,
GpuArchitectureSupported,
GpuArchitectureUnsupported,
GpuArchitectureUnknown,
NvidiaGpuUnavailable,
VersionConstraintMatches,
VersionConstraintMismatch,
StableRelease,
Prerelease,
OfficialReleaseConfiguration,
NotOfficialReleaseConfiguration,
OfficialPreferenceUnknown,
RuntimeVerified,
RuntimeNotRun,
RuntimeVerificationFailed,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WarningCode {
PtxOrNewDriverFeatureMayFail,
GpuArchitectureUnknown,
StaleMetadata,
NvidiaDetectionIncomplete,
BuiltinPythonTags,
OfficialPreferenceUnknown,
NotOfficialReleaseConfiguration,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct DecisionReason {
pub code: ReasonCode,
pub details: BTreeMap<String, String>,
}
impl DecisionReason {
pub fn new(code: ReasonCode) -> Self {
Self {
code,
details: BTreeMap::new(),
}
}
pub fn with_detail(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.details.insert(key.into(), value.into());
self
}
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct CandidateWarning {
pub code: WarningCode,
pub details: BTreeMap<String, String>,
}
impl CandidateWarning {
pub fn new(code: WarningCode) -> Self {
Self {
code,
details: BTreeMap::new(),
}
}
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct CompatibilityCheck {
pub status: CheckStatus,
pub reasons: Vec<DecisionReason>,
}
impl CompatibilityCheck {
pub fn new(status: CheckStatus, reasons: Vec<DecisionReason>) -> Self {
Self { status, reasons }
}
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct CompatibilityChecks {
pub wheel: CompatibilityCheck,
pub python: CompatibilityCheck,
pub platform: CompatibilityCheck,
pub gpu_architecture: CompatibilityCheck,
pub driver: CompatibilityCheck,
pub runtime: CompatibilityCheck,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum CompatibilityStatus {
Verified,
DirectCompatible,
MinorCompatible,
Unverified,
Incompatible,
Unavailable,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct Candidate {
pub torch_version: String,
pub variant: CudaVariant,
pub compatibility: CompatibilityStatus,
pub checks: CompatibilityChecks,
pub wheel: Option<TorchWheel>,
pub stable: bool,
pub official_preference: Option<u16>,
pub warnings: Vec<CandidateWarning>,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct CommandSpec {
pub program: String,
pub args: Vec<String>,
pub display: String,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Installer {
Pip,
Uv,
UvAdd,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct RecommendationReport {
pub schema_version: u32,
pub environment: Environment,
pub metadata: MetadataInfo,
pub recommendation: Option<Candidate>,
pub alternatives: Vec<Candidate>,
pub excluded: Vec<Candidate>,
pub install: Option<CommandSpec>,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct CandidatesReport {
pub schema_version: u32,
pub environment: Environment,
pub metadata: MetadataInfo,
pub candidates: Vec<Candidate>,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct ExplainReport {
pub schema_version: u32,
pub environment: Environment,
pub metadata: MetadataInfo,
pub candidate: Candidate,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct InspectReport {
pub schema_version: u32,
pub environment: Environment,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorKind {
Usage,
Detection,
Metadata,
Resolution,
Verification,
Internal,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct ErrorBody {
pub kind: ErrorKind,
pub code: String,
pub message: String,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct ErrorReport {
pub schema_version: u32,
pub error: ErrorBody,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct VerificationCheck {
pub name: String,
pub passed: bool,
pub detail: Option<String>,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct VerifiedDevice {
pub index: u32,
pub name: String,
pub capability: ComputeCapability,
pub operations_ok: bool,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct VerificationGpuMapping {
pub physical_index: u32,
pub logical_index: u32,
pub uuid: Option<String>,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct VerificationReport {
pub schema_version: u32,
pub python_executable: PathBuf,
pub status: CompatibilityStatus,
pub torch_version: Option<String>,
pub compiled_cuda: Option<String>,
pub cuda_available: Option<bool>,
pub device_count: Option<u32>,
pub arch_list: Vec<String>,
pub devices: Vec<VerifiedDevice>,
pub gpu_selection: Vec<VerificationGpuMapping>,
pub cudnn_available: Option<bool>,
pub checks: Vec<VerificationCheck>,
pub diagnostics: Vec<Diagnostic>,
pub error: Option<String>,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[repr(i32)]
pub enum ExitCode {
Success = 0,
Warning = 1,
Incompatible = 2,
MetadataFailure = 3,
InternalError = 4,
}
impl ExitCode {
pub const fn as_i32(self) -> i32 {
self as i32
}
}
#[cfg(test)]
mod tests {
use proptest::prelude::*;
use super::*;
#[test]
fn numeric_versions_ignore_insignificant_trailing_zeroes_for_ordering() {
let short: NumericVersion = "525.60".parse().expect("valid version");
let long: NumericVersion = "525.60.0".parse().expect("valid version");
assert_eq!(short.cmp(&long), Ordering::Equal);
assert_eq!(short, long);
assert_eq!(long.to_string(), "525.60.0");
}
#[test]
fn numeric_versions_compare_each_component_numerically() {
let older: NumericVersion = "530.9.99".parse().expect("valid version");
let newer: NumericVersion = "530.30.2".parse().expect("valid version");
assert!(older < newer);
}
#[test]
fn numeric_versions_preserve_reported_zero_padding() {
for reported in ["530.30.02", "575.57.08"] {
let version: NumericVersion = reported.parse().expect("valid version");
assert_eq!(version.to_string(), reported);
assert_eq!(
serde_json::to_string(&version).expect("serialize"),
format!("\"{reported}\"")
);
}
let padded: NumericVersion = "530.30.02".parse().expect("valid version");
let canonical: NumericVersion = "530.30.2".parse().expect("valid version");
assert_eq!(padded, canonical, "zero padding must not affect comparison");
}
#[test]
fn terminal_unsafe_characters_cover_controls_formats_and_non_ascii_separators() {
for character in [
'\n',
'\u{001b}',
'\u{00a0}',
'\u{061c}',
'\u{1680}',
'\u{2007}',
'\u{2028}',
'\u{2029}',
'\u{202e}',
'\u{202f}',
'\u{205f}',
'\u{3000}',
'\u{e0001}',
] {
assert!(
is_unsafe_terminal_character(character),
"U+{:04X} should be unsafe",
u32::from(character)
);
}
for character in [' ', 'a', '日', '🙂'] {
assert!(
!is_unsafe_terminal_character(character),
"U+{:04X} should be preserved",
u32::from(character)
);
}
}
#[test]
fn cuda_variants_round_trip() {
for value in ["cpu", "cu92", "cu118", "cu124", "cu132"] {
let parsed: CudaVariant = value.parse().expect("valid CUDA variant");
assert_eq!(parsed.to_string(), value);
}
}
#[test]
fn invalid_cuda_variants_are_rejected() {
for value in ["", "cuda124", "cu", "cu12x", "rocm6.3"] {
assert!(value.parse::<CudaVariant>().is_err(), "accepted {value}");
}
}
proptest! {
#[test]
fn numeric_version_order_matches_zero_padded_tuple_order(
left in prop::collection::vec(any::<u16>(), 1..8),
right in prop::collection::vec(any::<u16>(), 1..8),
) {
let left = left.into_iter().map(u32::from).collect::<Vec<_>>();
let right = right.into_iter().map(u32::from).collect::<Vec<_>>();
let width = left.len().max(right.len());
let expected = (0..width)
.map(|index| {
left.get(index)
.copied()
.unwrap_or(0)
.cmp(&right.get(index).copied().unwrap_or(0))
})
.find(|ordering| *ordering != Ordering::Equal)
.unwrap_or(Ordering::Equal);
let left = NumericVersion::new(left).expect("non-empty generated version");
let right = NumericVersion::new(right).expect("non-empty generated version");
prop_assert_eq!(left.cmp(&right), expected);
prop_assert_eq!(left == right, expected == Ordering::Equal);
}
}
}