use std::fmt::Display;
use xxhash_rust::xxh64;
use crate::PathHash;
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ChunkPath(String);
impl ChunkPath {
pub fn new(path: impl AsRef<str>) -> Self {
Self(path.as_ref().to_lowercase().replace('\\', "/"))
}
pub fn hash(&self) -> PathHash {
PathHash::new(xxh64::xxh64(self.0.as_bytes(), 0))
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn into_string(self) -> String {
self.0
}
}
impl Display for ChunkPath {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl AsRef<str> for ChunkPath {
fn as_ref(&self) -> &str {
&self.0
}
}
impl From<&str> for ChunkPath {
fn from(path: &str) -> Self {
Self::new(path)
}
}
impl From<String> for ChunkPath {
fn from(path: String) -> Self {
Self::new(path)
}
}
#[cfg(test)]
mod tests {
use super::*;
const IN_WAD: &str = "ASSETS/Characters/Aatrox/Skins/Base/Aatrox.dds";
const CANONICAL: &str = "assets/characters/aatrox/skins/base/aatrox.dds";
#[test]
fn new_lowercases() {
assert_eq!(ChunkPath::new(IN_WAD).as_str(), CANONICAL);
}
#[test]
fn new_converts_backslashes() {
assert_eq!(
ChunkPath::new("assets\\characters\\aatrox\\skins\\base\\aatrox.dds").as_str(),
CANONICAL
);
}
#[test]
fn new_is_idempotent() {
let once = ChunkPath::new("ASSETS\\Characters/Aatrox\\Skins/Base/Aatrox.dds");
let twice = ChunkPath::new(once.as_str());
assert_eq!(once, twice);
}
#[test]
fn hash_is_independent_of_case_and_separator() {
let forward = ChunkPath::new(CANONICAL);
let back = ChunkPath::new("assets\\characters\\aatrox\\skins\\base\\aatrox.dds");
let mixed = ChunkPath::new("ASSETS\\Characters/Aatrox\\Skins/Base/Aatrox.dds");
assert_eq!(forward.hash(), back.hash());
assert_eq!(forward.hash(), mixed.hash());
}
#[test]
fn hash_matches_xxhash64_of_the_canonical_string() {
assert_eq!(
ChunkPath::new(IN_WAD).hash(),
PathHash::new(xxh64::xxh64(CANONICAL.as_bytes(), 0))
);
}
}