haggis-rs/src/checksum.rs

73 lines
2.0 KiB
Rust
Raw Normal View History

2023-07-04 00:51:47 -04:00
use {
crate::Error,
std::io::{Read, Write},
};
2023-07-05 13:35:37 -04:00
#[derive(Clone, Copy, Debug)]
pub enum Algorithm {
Md5,
Sha1,
Sha256,
Skip,
}
/// Optional checksumming for individual files
2023-07-04 00:51:47 -04:00
#[derive(Debug)]
pub enum Checksum {
/// Md5 checksumming, fastest
2023-07-04 00:51:47 -04:00
Md5([u8; 16]),
/// Sha1 checksumming. On par with md5.
2023-07-04 00:51:47 -04:00
Sha1([u8; 20]),
/// The most thorough checksumming offered. Use this if data integrity is of
/// utmost importance and computational overhead is of lesser importance.
2023-07-04 00:51:47 -04:00
Sha256([u8; 32]),
/// Do not use checksumming. If this option is selected it is recommended that
/// the entire archive is downloaded in entirety and checksummed to ensure it's
/// integrity, as was the pattern with Unix 'tar' archives and 'iso' images
2023-07-04 00:51:47 -04:00
Skip,
}
impl Checksum {
2023-07-05 13:35:37 -04:00
pub(crate) fn read<T: Read>(reader: &mut T) -> Result<Self, Error> {
2023-07-04 00:51:47 -04:00
let mut buf = [0; 1];
reader.read_exact(&mut buf)?;
match buf[0] {
0 => {
let mut sum = [0; 16];
reader.read_exact(&mut sum)?;
Ok(Self::Md5(sum))
}
1 => {
let mut sum = [0; 20];
reader.read_exact(&mut sum)?;
Ok(Self::Sha1(sum))
}
2 => {
let mut sum = [0; 32];
reader.read_exact(&mut sum)?;
Ok(Self::Sha256(sum))
}
_ => Ok(Self::Skip),
}
}
2023-07-05 13:35:37 -04:00
pub(crate) fn write<T: Write>(&self, writer: &mut T) -> Result<(), Error> {
2023-07-04 00:51:47 -04:00
match self {
Self::Md5(sum) => {
writer.write_all(&[b'0'])?;
writer.write_all(&sum[..])?;
}
Self::Sha1(sum) => {
writer.write_all(&[b'1'])?;
writer.write_all(&sum[..])?;
}
Self::Sha256(sum) => {
writer.write_all(&[b'2'])?;
writer.write_all(&sum[..])?;
}
Self::Skip => writer.write_all(&[b'3'])?,
}
Ok(())
}
}