use super::encoding::EncodablePackage;
use crate::{
error::{Error, Result},
metadata::Metadata,
};
use serde::{Deserialize, Serialize};
use std::str::FromStr;
#[derive(Copy, Clone, Debug, Deserialize, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize)]
#[non_exhaustive]
#[repr(u32)]
pub enum ResolveVersion {
V1 = 1,
V2 = 2,
V3 = 3,
}
impl ResolveVersion {
pub(super) fn detect(packages: &[EncodablePackage], metadata: &Metadata) -> Result<Self> {
let is_v1 = metadata.keys().any(|key| key.is_checksum());
let is_v2 = packages.iter().any(|package| package.checksum.is_some());
if is_v1 && is_v2 {
return Err(Error::Parse("malformed lockfile: contains checksums in both [[package]] and [[metadata]] sections".to_string()));
}
if is_v1 {
Ok(ResolveVersion::V1)
} else {
Ok(ResolveVersion::V2)
}
}
pub(super) fn is_explicit(self) -> bool {
u32::from(self) >= 3
}
}
impl Default for ResolveVersion {
fn default() -> Self {
ResolveVersion::V3
}
}
impl From<ResolveVersion> for u32 {
fn from(version: ResolveVersion) -> u32 {
version as u32
}
}
impl FromStr for ResolveVersion {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
u32::from_str(s)
.map_err(|_| Error::Parse(format!("invalid Cargo.lock format version: `{}`", s)))
.and_then(Self::try_from)
}
}
impl TryFrom<u32> for ResolveVersion {
type Error = Error;
fn try_from(num: u32) -> Result<Self> {
match num {
1 => Ok(ResolveVersion::V1),
2 => Ok(ResolveVersion::V2),
3 => Ok(ResolveVersion::V3),
_ => Err(Error::Parse(format!(
"invalid Cargo.lock format version: `{}`",
num
))),
}
}
}