use std::fs;
use std::io::Read;
use std::path::Path;
use image::{DynamicImage, ImageBuffer, Rgb, Rgba};
use rosetta_squint_decode::{decode as rid_decode, Channels, DecodeError, DecodedImage};
use rosetta_squint_hash::ImageHashError;
pub use rosetta_squint_hash::{
hex_to_flathash, hex_to_hash, hex_to_multihash, Hash, ImageMultiHash,
};
pub const MAX_FILE_SIZE: u64 = 256 * 1024 * 1024;
#[derive(Debug, thiserror::Error)]
pub enum RosettaError {
#[error("io: {0}")]
Io(#[from] std::io::Error),
#[error("decode: {0}")]
Decode(#[from] DecodeError),
#[error("hash: {0}")]
Hash(#[from] ImageHashError),
#[error("internal: failed to construct image from decoded buffer")]
BadBuffer,
#[error("not a regular file: {path}")]
NotRegularFile { path: String },
#[error("symlink not allowed: {path}")]
SymlinkNotAllowed { path: String },
#[error(
"input file too large: {size} bytes (max {max} bytes / 256 MiB). \
For images above this threshold, decode via rosetta-squint-decode \
directly after explicit validation."
)]
FileTooLarge { size: u64, max: u64 },
}
fn decoded_to_dynamic(d: DecodedImage) -> Result<DynamicImage, RosettaError> {
let w = d.width as u32;
let h = d.height as u32;
match d.channels {
Channels::Rgb => {
let buf: ImageBuffer<Rgb<u8>, Vec<u8>> =
ImageBuffer::from_raw(w, h, d.data).ok_or(RosettaError::BadBuffer)?;
Ok(DynamicImage::ImageRgb8(buf))
}
Channels::Rgba => {
let buf: ImageBuffer<Rgba<u8>, Vec<u8>> =
ImageBuffer::from_raw(w, h, d.data).ok_or(RosettaError::BadBuffer)?;
Ok(DynamicImage::ImageRgba8(buf))
}
}
}
pub fn decode_to_image(bytes: &[u8]) -> Result<DynamicImage, RosettaError> {
let decoded = rid_decode(bytes)?;
decoded_to_dynamic(decoded)
}
fn open_no_follow(p: &Path) -> Result<fs::File, RosettaError> {
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
fs::OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW)
.open(p)
.map_err(|e| {
if e.raw_os_error() == Some(libc::ELOOP) {
RosettaError::SymlinkNotAllowed {
path: p.display().to_string(),
}
} else {
RosettaError::Io(e)
}
})
}
#[cfg(not(unix))]
{
match fs::symlink_metadata(p) {
Ok(meta) if meta.file_type().is_symlink() => {
Err(RosettaError::SymlinkNotAllowed {
path: p.display().to_string(),
})
}
Ok(_) => Ok(fs::File::open(p)?),
Err(e) => Err(RosettaError::Io(e)),
}
}
}
pub fn decode_file<P: AsRef<Path>>(path: P) -> Result<DynamicImage, RosettaError> {
let p = path.as_ref();
let mut f = open_no_follow(p)?;
let metadata = f.metadata()?;
if !metadata.is_file() {
return Err(RosettaError::NotRegularFile {
path: p.display().to_string(),
});
}
if metadata.len() > MAX_FILE_SIZE {
return Err(RosettaError::FileTooLarge {
size: metadata.len(),
max: MAX_FILE_SIZE,
});
}
let cap = std::cmp::min(metadata.len(), MAX_FILE_SIZE) as usize;
let mut bytes: Vec<u8> = Vec::with_capacity(cap);
f.by_ref()
.take(MAX_FILE_SIZE + 1)
.read_to_end(&mut bytes)?;
if bytes.len() as u64 > MAX_FILE_SIZE {
return Err(RosettaError::FileTooLarge {
size: bytes.len() as u64,
max: MAX_FILE_SIZE,
});
}
decode_to_image(&bytes)
}
pub fn phash<P: AsRef<Path>>(path: P, hash_size: usize) -> Result<Hash, RosettaError> {
let img = decode_file(path)?;
Ok(rosetta_squint_hash::phash(&img, hash_size)?)
}
pub fn phash_bytes(bytes: &[u8], hash_size: usize) -> Result<Hash, RosettaError> {
let img = decode_to_image(bytes)?;
Ok(rosetta_squint_hash::phash(&img, hash_size)?)
}
pub fn phash_simple<P: AsRef<Path>>(path: P, hash_size: usize) -> Result<Hash, RosettaError> {
let img = decode_file(path)?;
Ok(rosetta_squint_hash::phash_simple(&img, hash_size)?)
}
pub fn phash_simple_bytes(bytes: &[u8], hash_size: usize) -> Result<Hash, RosettaError> {
let img = decode_to_image(bytes)?;
Ok(rosetta_squint_hash::phash_simple(&img, hash_size)?)
}
pub fn dhash<P: AsRef<Path>>(path: P, hash_size: usize) -> Result<Hash, RosettaError> {
let img = decode_file(path)?;
Ok(rosetta_squint_hash::dhash(&img, hash_size)?)
}
pub fn dhash_bytes(bytes: &[u8], hash_size: usize) -> Result<Hash, RosettaError> {
let img = decode_to_image(bytes)?;
Ok(rosetta_squint_hash::dhash(&img, hash_size)?)
}
pub fn dhash_vertical<P: AsRef<Path>>(path: P, hash_size: usize) -> Result<Hash, RosettaError> {
let img = decode_file(path)?;
Ok(rosetta_squint_hash::dhash_vertical(&img, hash_size)?)
}
pub fn dhash_vertical_bytes(bytes: &[u8], hash_size: usize) -> Result<Hash, RosettaError> {
let img = decode_to_image(bytes)?;
Ok(rosetta_squint_hash::dhash_vertical(&img, hash_size)?)
}
pub fn average_hash<P: AsRef<Path>>(path: P, hash_size: usize) -> Result<Hash, RosettaError> {
let img = decode_file(path)?;
Ok(rosetta_squint_hash::average_hash(&img, hash_size)?)
}
pub fn average_hash_bytes(bytes: &[u8], hash_size: usize) -> Result<Hash, RosettaError> {
let img = decode_to_image(bytes)?;
Ok(rosetta_squint_hash::average_hash(&img, hash_size)?)
}
pub fn whash_haar<P: AsRef<Path>>(path: P, hash_size: usize) -> Result<Hash, RosettaError> {
let img = decode_file(path)?;
Ok(rosetta_squint_hash::whash_haar(&img, hash_size)?)
}
pub fn whash_haar_bytes(bytes: &[u8], hash_size: usize) -> Result<Hash, RosettaError> {
let img = decode_to_image(bytes)?;
Ok(rosetta_squint_hash::whash_haar(&img, hash_size)?)
}
pub fn whash_db4<P: AsRef<Path>>(path: P, hash_size: usize) -> Result<Hash, RosettaError> {
let img = decode_file(path)?;
Ok(rosetta_squint_hash::whash_db4(&img, hash_size)?)
}
pub fn whash_db4_bytes(bytes: &[u8], hash_size: usize) -> Result<Hash, RosettaError> {
let img = decode_to_image(bytes)?;
Ok(rosetta_squint_hash::whash_db4(&img, hash_size)?)
}
pub fn whash_db4_robust<P: AsRef<Path>>(path: P, hash_size: usize) -> Result<Hash, RosettaError> {
let img = decode_file(path)?;
Ok(rosetta_squint_hash::whash_db4_robust(&img, hash_size)?)
}
pub fn whash_db4_robust_bytes(bytes: &[u8], hash_size: usize) -> Result<Hash, RosettaError> {
let img = decode_to_image(bytes)?;
Ok(rosetta_squint_hash::whash_db4_robust(&img, hash_size)?)
}
pub fn colorhash<P: AsRef<Path>>(path: P, binbits: usize) -> Result<Hash, RosettaError> {
let img = decode_file(path)?;
Ok(rosetta_squint_hash::colorhash(&img, binbits)?)
}
pub fn colorhash_bytes(bytes: &[u8], binbits: usize) -> Result<Hash, RosettaError> {
let img = decode_to_image(bytes)?;
Ok(rosetta_squint_hash::colorhash(&img, binbits)?)
}
pub fn crop_resistant_hash<P: AsRef<Path>>(
path: P,
limit_segments: Option<usize>,
) -> Result<ImageMultiHash, RosettaError> {
let img = decode_file(path)?;
Ok(rosetta_squint_hash::crop_resistant_hash(&img, limit_segments)?)
}
pub fn crop_resistant_hash_bytes(
bytes: &[u8],
limit_segments: Option<usize>,
) -> Result<ImageMultiHash, RosettaError> {
let img = decode_to_image(bytes)?;
Ok(rosetta_squint_hash::crop_resistant_hash(&img, limit_segments)?)
}