use super::ChangesParseError;
use crate::control::{DigestMd5, Priority, def_serde_traits_for};
use std::str::FromStr;
#[derive(Clone, Debug, PartialEq)]
pub struct File {
pub digest: DigestMd5,
pub size: usize,
pub path: String,
pub section: String,
pub priority: Option<Priority>,
}
def_serde_traits_for!(File);
impl std::fmt::Display for File {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(
f,
"{} {} {} {} {}",
self.digest,
self.size,
self.section,
self.priority
.map(|v| v.to_string())
.unwrap_or("-".to_string()),
self.path,
)
}
}
impl FromStr for File {
type Err = ChangesParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let [digest, size, section, priority, path] = s
.split(" ")
.collect::<Vec<_>>()
.try_into()
.map_err(|_| ChangesParseError::Malformed)?;
let priority: Option<Priority> = if priority != "-" {
Some(
priority
.parse()
.map_err(ChangesParseError::InvalidPriority)?,
)
} else {
None
};
Ok(File {
digest: digest.parse().map_err(|_| ChangesParseError::InvalidHash)?,
size: size.parse().map_err(|_| ChangesParseError::Malformed)?,
section: section.to_owned(),
priority,
path: path.to_owned(),
})
}
}
#[cfg(feature = "hex")]
mod hex {
#![cfg_attr(docsrs, doc(cfg(feature = "hex")))]
#[test]
fn hex_digest_file() {
use super::super::*;
use crate::control::Priority;
use ::hex;
let file = File {
digest: "e7bd195571b19d33bd83d1c379fe6432".parse().unwrap(),
size: 1183,
path: "hello_2.10-3.dsc".to_owned(),
section: "devel".to_owned(),
priority: Some(Priority::Optional),
};
assert_eq!(
hex::decode("e7bd195571b19d33bd83d1c379fe6432").unwrap(),
file.digest.digest(),
);
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_parse() {
let file: File =
"16678389ba7fddcdfa05e0707d61f043 12688 devel optional hello_2.10-3.debian.tar.xz"
.parse()
.unwrap();
assert_eq!(Priority::Optional, file.priority.unwrap());
assert_eq!(12688, file.size);
}
}