#![forbid(unsafe_code)]
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
struct ReadmeDoctests;
pub mod convert;
mod image;
#[cfg(any(test, feature = "test-support"))]
#[doc(hidden)]
pub mod invariants;
pub mod luminance;
mod pixel;
pub mod segment;
pub use image::{ImageBuf, ImageRef};
pub use pixel::{
Bilevel, Cmyk8, ColorModel, Gray8, Gray16, GrayAlpha8, GrayAlpha16, Indexed8, Pixel,
PixelFormat, Rgb8, Rgb16, Rgba8, Rgba16, Sample,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[repr(u32)]
pub enum ErrorKind {
InvalidInput = 1,
Unsupported = 2,
Io = 3,
}
const _: () = {
assert!(ErrorKind::InvalidInput as u32 == 1);
assert!(ErrorKind::Unsupported as u32 == 2);
assert!(ErrorKind::Io as u32 == 3);
};
#[derive(Debug)]
#[non_exhaustive]
pub struct Diagnostic {
source: Error,
origin: Option<&'static str>,
byte_offset: Option<u64>,
detail: Option<Box<str>>,
}
impl Diagnostic {
#[must_use]
pub fn source_error(&self) -> &Error {
&self.source
}
#[must_use]
pub fn origin(&self) -> Option<&'static str> {
self.origin
}
#[must_use]
pub fn byte_offset(&self) -> Option<u64> {
self.byte_offset
}
#[must_use]
pub fn detail(&self) -> Option<&str> {
self.detail.as_deref()
}
}
impl core::fmt::Display for Diagnostic {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", self.source)?;
if self.origin.is_some() || self.byte_offset.is_some() {
f.write_str(" [")?;
if let Some(origin) = self.origin {
write!(f, "origin: {origin}")?;
if self.byte_offset.is_some() {
f.write_str(", ")?;
}
}
if let Some(offset) = self.byte_offset {
write!(f, "byte offset: {offset}")?;
}
f.write_str("]")?;
}
if let Some(detail) = &self.detail {
write!(f, ": {detail}")?;
}
Ok(())
}
}
impl std::error::Error for Diagnostic {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.source)
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("invalid input: {0}")]
InvalidInput(&'static str),
#[error("unsupported: {0}")]
Unsupported(&'static str),
#[error("i/o error: {0}")]
Io(#[from] std::io::Error),
#[error("{0}")]
Context(#[source] Box<Diagnostic>),
}
impl Error {
#[must_use]
pub fn invalid_input(origin: &'static str, message: &'static str) -> Self {
Self::InvalidInput(message).with_origin(origin)
}
#[must_use]
pub fn unsupported(origin: &'static str, message: &'static str) -> Self {
Self::Unsupported(message).with_origin(origin)
}
#[must_use]
pub fn kind(&self) -> ErrorKind {
match self {
Self::InvalidInput(_) => ErrorKind::InvalidInput,
Self::Unsupported(_) => ErrorKind::Unsupported,
Self::Io(_) => ErrorKind::Io,
Self::Context(diagnostic) => diagnostic.source.kind(),
}
}
#[must_use]
pub fn static_message(&self) -> Option<&'static str> {
match self {
Self::InvalidInput(message) | Self::Unsupported(message) => Some(message),
Self::Io(_) => None,
Self::Context(diagnostic) => diagnostic.source.static_message(),
}
}
#[must_use]
pub fn origin(&self) -> Option<&'static str> {
match self {
Self::Context(diagnostic) => diagnostic.origin(),
_ => None,
}
}
#[must_use]
pub fn byte_offset(&self) -> Option<u64> {
match self {
Self::Context(diagnostic) => diagnostic.byte_offset(),
_ => None,
}
}
#[must_use]
pub fn detail(&self) -> Option<&str> {
match self {
Self::Context(diagnostic) => diagnostic.detail(),
_ => None,
}
}
#[must_use]
pub fn with_origin(self, origin: &'static str) -> Self {
self.with_diagnostic(|diagnostic| {
if diagnostic.origin.is_none() {
diagnostic.origin = Some(origin);
}
})
}
#[must_use]
pub fn with_byte_offset(self, byte_offset: u64) -> Self {
self.with_diagnostic(|diagnostic| {
if diagnostic.byte_offset.is_none() {
diagnostic.byte_offset = Some(byte_offset);
}
})
}
#[must_use]
pub fn with_detail(self, detail: impl Into<Box<str>>) -> Self {
self.with_diagnostic(|diagnostic| {
if diagnostic.detail.is_none() {
diagnostic.detail = Some(detail.into());
}
})
}
fn with_diagnostic(self, update: impl FnOnce(&mut Diagnostic)) -> Self {
match self {
Self::Context(mut diagnostic) => {
update(&mut diagnostic);
Self::Context(diagnostic)
}
source => {
let mut diagnostic = Diagnostic {
source,
origin: None,
byte_offset: None,
detail: None,
};
update(&mut diagnostic);
Self::Context(Box::new(diagnostic))
}
}
}
}
pub type Result<T> = core::result::Result<T, Error>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(C)]
pub struct Dimensions {
pub width: u32,
pub height: u32,
}
impl Dimensions {
pub fn new(width: u32, height: u32) -> Result<Self> {
if width == 0 || height == 0 {
return Err(Error::InvalidInput("zero-sized image").with_origin(env!("CARGO_PKG_NAME")));
}
Ok(Self { width, height })
}
#[must_use]
pub fn num_pixels(self) -> Option<usize> {
(self.width as usize).checked_mul(self.height as usize)
}
#[must_use]
pub fn sample_count(self, channels: usize) -> Option<usize> {
self.num_pixels()?.checked_mul(channels)
}
#[must_use]
pub fn is_empty(self) -> bool {
self.width == 0 || self.height == 0
}
}
pub trait EncodeImage<P: Pixel> {
fn encode_image(&self, image: ImageRef<'_, P>, out: &mut Vec<u8>) -> Result<usize>;
fn encode_to_vec(&self, image: ImageRef<'_, P>) -> Result<Vec<u8>> {
let mut out = Vec::new();
self.encode_image(image, &mut out)?;
Ok(out)
}
}
pub trait DecodeImage<P: Pixel> {
fn decode_image(&self, data: &[u8]) -> Result<ImageBuf<P>>;
fn decode_image_into(&self, data: &[u8], dst: &mut ImageBuf<P>) -> Result<()> {
*dst = self.decode_image(data)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn error_displays_and_dimensions_fields() {
assert!(!Error::Unsupported("x").to_string().is_empty());
assert!(!Error::InvalidInput("y").to_string().is_empty());
let d = Dimensions {
width: 1920,
height: 1080,
};
assert_eq!(d.width, 1920);
assert_eq!(d.height, 1080);
}
#[test]
fn io_error_converts_and_displays() {
let io = std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "short read");
let err: Error = io.into();
assert!(matches!(err, Error::Io(_)));
assert!(err.to_string().contains("short read"));
}
#[test]
fn legacy_error_variants_keep_their_public_shape() {
let invalid = Error::InvalidInput("bad bytes");
let unsupported = Error::Unsupported("future profile");
assert!(matches!(invalid, Error::InvalidInput("bad bytes")));
assert!(matches!(unsupported, Error::Unsupported("future profile")));
assert_eq!(invalid.kind(), ErrorKind::InvalidInput);
assert_eq!(unsupported.kind(), ErrorKind::Unsupported);
assert_eq!(invalid.static_message(), Some("bad bytes"));
assert_eq!(unsupported.static_message(), Some("future profile"));
assert_eq!(invalid.origin(), None);
}
#[test]
fn context_is_structured_first_write_wins_and_keeps_the_source() {
use std::error::Error as _;
let err = Error::InvalidInput("bad box")
.with_origin("gamut-isobmff")
.with_origin("gamut-avif")
.with_byte_offset(17)
.with_byte_offset(99)
.with_detail("declared size exceeds input")
.with_detail("replacement");
assert_eq!(err.kind(), ErrorKind::InvalidInput);
assert_eq!(err.static_message(), Some("bad box"));
assert_eq!(err.origin(), Some("gamut-isobmff"));
assert_eq!(err.byte_offset(), Some(17));
assert_eq!(err.detail(), Some("declared size exceeds input"));
assert_eq!(
err.to_string(),
"invalid input: bad box [origin: gamut-isobmff, byte offset: 17]: declared size exceeds input"
);
let diagnostic = match &err {
Error::Context(diagnostic) => diagnostic,
other => panic!("expected contextual error, got {other:?}"),
};
assert!(matches!(
diagnostic.source_error(),
Error::InvalidInput("bad box")
));
assert!(err.source().is_some());
}
#[test]
fn partial_context_displays_without_empty_separators() {
assert_eq!(
Error::Unsupported("future profile")
.with_byte_offset(3)
.to_string(),
"unsupported: future profile [byte offset: 3]"
);
assert_eq!(
Error::InvalidInput("bad bytes")
.with_detail("decoder rejected marker")
.to_string(),
"invalid input: bad bytes: decoder rejected marker"
);
assert_eq!(
Error::unsupported("gamut-test", "future profile").to_string(),
"unsupported: future profile [origin: gamut-test]"
);
}
#[test]
fn contextual_io_keeps_its_kind_and_source_chain() {
use std::error::Error as _;
let err = Error::Io(std::io::Error::other("disk on fire"))
.with_origin("gamut-ifd")
.with_byte_offset(4096);
assert_eq!(err.kind(), ErrorKind::Io);
assert_eq!(err.static_message(), None);
assert_eq!(err.origin(), Some("gamut-ifd"));
assert_eq!(err.byte_offset(), Some(4096));
let diagnostic = err.source().expect("diagnostic source");
let io = diagnostic.source().expect("io source");
assert_eq!(io.to_string(), "i/o error: disk on fire");
}
#[test]
fn errors_remain_send_and_sync() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<Error>();
}
#[test]
fn dimensions_new_rejects_zero() {
assert!(Dimensions::new(0, 4).is_err());
assert!(Dimensions::new(4, 0).is_err());
assert!(Dimensions::new(0, 0).is_err());
let d = Dimensions::new(4, 3).unwrap();
assert_eq!((d.width, d.height), (4, 3));
}
#[test]
fn dimensions_pixel_and_sample_counts() {
let d = Dimensions {
width: 4,
height: 3,
};
assert_eq!(d.num_pixels(), Some(12));
assert_eq!(d.sample_count(3), Some(36));
assert_eq!(d.sample_count(1), Some(12));
assert!(!d.is_empty());
}
#[test]
fn dimensions_is_empty() {
assert!(
Dimensions {
width: 0,
height: 5
}
.is_empty()
);
assert!(
Dimensions {
width: 5,
height: 0
}
.is_empty()
);
assert!(
!Dimensions {
width: 5,
height: 5
}
.is_empty()
);
}
#[test]
fn dimensions_sample_count_overflow_is_none() {
let d = Dimensions {
width: 0xFFFF,
height: 0xFFFF,
};
assert_eq!(d.num_pixels(), Some(0xFFFF * 0xFFFF));
assert_eq!(d.sample_count(usize::MAX), None);
}
}
#[cfg(test)]
mod trait_tests {
use super::*;
struct Trivial;
impl EncodeImage<Gray8> for Trivial {
fn encode_image(&self, image: ImageRef<'_, Gray8>, out: &mut Vec<u8>) -> Result<usize> {
out.extend_from_slice(image.as_samples());
Ok(image.as_samples().len())
}
}
impl DecodeImage<Gray8> for Trivial {
fn decode_image(&self, _data: &[u8]) -> Result<ImageBuf<Gray8>> {
ImageBuf::<Gray8>::new(vec![42u8], Dimensions::new(1, 1)?)
}
}
struct Failing;
impl EncodeImage<Gray8> for Failing {
fn encode_image(&self, _image: ImageRef<'_, Gray8>, _out: &mut Vec<u8>) -> Result<usize> {
Err(Error::Unsupported("nope"))
}
}
#[test]
fn encode_image_appends_and_counts() {
let img = ImageBuf::<Gray8>::new(vec![1, 2, 3, 4], Dimensions::new(2, 2).unwrap()).unwrap();
let mut out = vec![0xFF];
let n = Trivial.encode_image(img.as_ref(), &mut out).unwrap();
assert_eq!(n, 4);
assert_eq!(out, vec![0xFF, 1, 2, 3, 4]);
}
#[test]
fn encode_to_vec_returns_fresh_exact_bytes() {
let img = ImageBuf::<Gray8>::new(vec![1, 2, 3, 4], Dimensions::new(2, 2).unwrap()).unwrap();
assert_eq!(
Trivial.encode_to_vec(img.as_ref()).unwrap(),
vec![1, 2, 3, 4]
);
}
#[test]
fn encode_to_vec_propagates_errors() {
let img = ImageBuf::<Gray8>::new(vec![0], Dimensions::new(1, 1).unwrap()).unwrap();
assert!(Failing.encode_to_vec(img.as_ref()).is_err());
}
#[test]
fn decode_image_into_default_forwards() {
let mut dst = ImageBuf::<Gray8>::zeroed(Dimensions::new(1, 1).unwrap()).unwrap();
Trivial.decode_image_into(&[], &mut dst).unwrap();
assert_eq!(dst.as_samples(), &[42]);
}
#[test]
fn traits_are_object_safe() {
let enc: &dyn EncodeImage<Gray8> = &Trivial;
let dec: &dyn DecodeImage<Gray8> = &Trivial;
let img = ImageBuf::<Gray8>::new(vec![7u8], Dimensions::new(1, 1).unwrap()).unwrap();
let mut out = Vec::new();
assert_eq!(enc.encode_image(img.as_ref(), &mut out).unwrap(), 1);
assert_eq!(dec.decode_image(&[]).unwrap().as_samples(), &[42]);
}
}