use std::{
borrow::{Borrow, BorrowMut},
collections::BTreeMap,
fmt,
ops::{ControlFlow, Deref, DerefMut},
};
use serde::{Deserialize, Serialize};
use crate::{crc::CRC, md5::MD5Sum};
pub mod fs;
#[cfg(feature = "common-parser")]
pub mod parser;
pub mod writer;
#[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CRCTreeNode<D> {
pub crc: CRC,
pub left: i32,
pub right: i32,
pub data: D,
}
impl<D> Borrow<D> for CRCTreeNode<D> {
fn borrow(&self) -> &D {
&self.data
}
}
impl<D> BorrowMut<D> for CRCTreeNode<D> {
fn borrow_mut(&mut self) -> &mut D {
&mut self.data
}
}
impl<D> Deref for CRCTreeNode<D> {
type Target = D;
fn deref(&self) -> &Self::Target {
&self.data
}
}
impl<D> DerefMut for CRCTreeNode<D> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.data
}
}
pub type CRCTree<T> = BTreeMap<CRC, T>;
pub trait CRCTreeVisitor<T> {
type Break;
fn visit(&mut self, crc: CRC, data: T) -> ControlFlow<Self::Break>;
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct CRCTreeCollector<T> {
inner: CRCTree<T>,
}
impl<T> CRCTreeCollector<T> {
pub fn new() -> Self {
Self {
inner: CRCTree::new(),
}
}
pub fn into_inner(self) -> CRCTree<T> {
self.inner
}
}
impl<T> CRCTreeVisitor<T> for CRCTreeCollector<T> {
type Break = ();
fn visit(&mut self, crc: CRC, data: T) -> ControlFlow<Self::Break> {
self.inner.insert(crc, data);
ControlFlow::Continue(())
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileMeta {
pub size: u32,
#[serde(with = "crate::md5::padded")]
pub hash: MD5Sum,
}
impl fmt::Display for FileMeta {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{},{}", self.size, self.hash)
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileMetaPair {
pub raw: FileMeta,
pub compressed: FileMeta,
}
impl FileMetaPair {
pub fn new(raw: FileMeta, compressed: FileMeta) -> Self {
Self { raw, compressed }
}
pub fn to_path(&self) -> String {
let hash = format!("{:?}", self.raw.hash);
let mut chars = hash.chars();
let c1 = chars.next().unwrap();
let c2 = chars.next().unwrap();
format!("{}/{}/{}.sd0", c1, c2, hash)
}
}
impl fmt::Display for FileMetaPair {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{},{}", self.raw, self.compressed)
}
}