Skip to main content

ditherlib/
lib.rs

1#![warn(missing_docs)]
2#![doc = include_str!("../README.md")]
3
4use std::fmt;
5
6mod effects;
7mod io;
8mod pipeline;
9mod renderer;
10mod selection;
11
12pub use effects::{
13    Blur, Color, Colour, DiffusionAlgorithm, DiffusionKernel, DiffusionScan, DiffusionTap,
14    ErrorDiffusion, Greyscale, OrderedDither, Palette, Threshold, ThresholdMap, ThresholdRotation,
15};
16pub use io::{read, write};
17pub use pipeline::{Pipeline, PipelineStep};
18pub use renderer::{Effect, RenderedImage, Renderer};
19pub use selection::{Mask, Point, Polygon, Selection};
20
21/// A result returned by Ditherlib operations.
22pub type Result<T> = std::result::Result<T, DitherError>;
23
24/// A category describing why a Ditherlib operation failed.
25#[derive(Clone, Copy, Debug, Eq, PartialEq)]
26#[non_exhaustive]
27pub enum ErrorKind {
28    /// An image file could not be accessed.
29    FileAccess,
30    /// The requested image format is unsupported or disabled.
31    UnsupportedFormat,
32    /// An image could not be decoded.
33    Decode,
34    /// An image could not be encoded.
35    Encode,
36    /// A polygon is malformed.
37    InvalidPolygon,
38    /// A mask's dimensions and coverage length do not agree.
39    DimensionMismatch,
40    /// An effect could not be rendered.
41    Effect,
42    /// An effect parameter is invalid.
43    InvalidParameter,
44}
45
46/// An error returned by a Ditherlib operation.
47#[derive(Debug)]
48pub struct DitherError {
49    kind: ErrorKind,
50    message: String,
51    source: Option<Box<dyn std::error::Error + Send + Sync>>,
52}
53
54impl DitherError {
55    /// Returns the stable category for this error.
56    pub const fn kind(&self) -> ErrorKind {
57        self.kind
58    }
59
60    /// Creates an error with a stable category and descriptive message.
61    pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
62        Self {
63            kind,
64            message: message.into(),
65            source: None,
66        }
67    }
68
69    fn from_image_decode(source: image::ImageError) -> Self {
70        let kind = match &source {
71            image::ImageError::IoError(_) => ErrorKind::FileAccess,
72            image::ImageError::Unsupported(_) => ErrorKind::UnsupportedFormat,
73            _ => ErrorKind::Decode,
74        };
75        let message = match kind {
76            ErrorKind::FileAccess => "could not access image file",
77            ErrorKind::UnsupportedFormat => "unsupported image format",
78            ErrorKind::Decode => "could not decode image",
79            _ => unreachable!(),
80        };
81
82        Self {
83            kind,
84            message: message.into(),
85            source: Some(Box::new(source)),
86        }
87    }
88
89    fn from_image_encode(source: image::ImageError) -> Self {
90        let kind = match &source {
91            image::ImageError::IoError(_) => ErrorKind::FileAccess,
92            image::ImageError::Unsupported(_) => ErrorKind::UnsupportedFormat,
93            _ => ErrorKind::Encode,
94        };
95        let message = match kind {
96            ErrorKind::FileAccess => "could not access image file",
97            ErrorKind::UnsupportedFormat => "unsupported image format",
98            ErrorKind::Encode => "could not encode image",
99            _ => unreachable!(),
100        };
101
102        Self {
103            kind,
104            message: message.into(),
105            source: Some(Box::new(source)),
106        }
107    }
108}
109
110impl fmt::Display for DitherError {
111    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
112        match &self.source {
113            Some(source) => write!(formatter, "{}: {source}", self.message),
114            None => formatter.write_str(&self.message),
115        }
116    }
117}
118
119impl std::error::Error for DitherError {
120    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
121        self.source
122            .as_ref()
123            .map(|source| source.as_ref() as &(dyn std::error::Error + 'static))
124    }
125}
126
127/// An image loaded into memory by Ditherlib.
128pub struct SourceImage {
129    width: u32,
130    height: u32,
131    pixels: Box<[u8]>,
132}
133
134impl SourceImage {
135    /// Returns the image width in pixels.
136    pub const fn width(&self) -> u32 {
137        self.width
138    }
139
140    /// Returns the image height in pixels.
141    pub const fn height(&self) -> u32 {
142        self.height
143    }
144
145    /// Returns the image dimensions as `(width, height)`.
146    pub const fn dimensions(&self) -> (u32, u32) {
147        (self.width, self.height)
148    }
149
150    /// Returns the row-major RGBA8 pixel bytes.
151    pub fn rgba8_bytes(&self) -> &[u8] {
152        &self.pixels
153    }
154
155    /// Returns the RGBA8 value at `(x, y)`, or `None` when it is out of bounds.
156    pub fn pixel(&self, x: u32, y: u32) -> Option<[u8; 4]> {
157        if x >= self.width || y >= self.height {
158            return None;
159        }
160
161        let index = (y as usize * self.width as usize + x as usize) * 4;
162        Some([
163            self.pixels[index],
164            self.pixels[index + 1],
165            self.pixels[index + 2],
166            self.pixels[index + 3],
167        ])
168    }
169}
170
171impl fmt::Debug for SourceImage {
172    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
173        formatter
174            .debug_struct("SourceImage")
175            .field("width", &self.width())
176            .field("height", &self.height())
177            .finish_non_exhaustive()
178    }
179}
180
181#[cfg(test)]
182mod tests {
183    use super::{ErrorKind, read};
184    use std::path::Path;
185
186    #[cfg(feature = "jpeg")]
187    #[test]
188    fn reads_jpeg() {
189        let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/valid.jpg");
190        let image = read(path).expect("valid.jpg should be a valid JPEG image");
191
192        assert_eq!(image.width(), 2000);
193        assert_eq!(image.height(), 3000);
194        assert_eq!(image.dimensions(), (2000, 3000));
195
196        let pixels: &[u8] = image.rgba8_bytes();
197        assert_eq!(pixels.len(), 2000 * 3000 * 4);
198        assert_eq!(image.pixel(0, 0), Some([192, 168, 164, 255]));
199        assert_eq!(image.pixel(1000, 1500), Some([129, 128, 124, 255]));
200        assert_eq!(image.pixel(1999, 2999), Some([40, 40, 28, 255]));
201        assert_eq!(image.pixel(2000, 0), None);
202        assert_eq!(image.pixel(0, 3000), None);
203    }
204
205    #[test]
206    fn reports_file_access_errors() {
207        let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("missing.jpg");
208        let error = read(path).expect_err("missing.jpg should not exist");
209
210        assert_eq!(error.kind(), ErrorKind::FileAccess);
211    }
212
213    #[test]
214    fn reports_unsupported_format_errors() {
215        let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
216        let error = read(path).expect_err("Cargo.toml should not be a supported image format");
217
218        assert_eq!(error.kind(), ErrorKind::UnsupportedFormat);
219    }
220
221    #[cfg(feature = "jpeg")]
222    #[test]
223    fn reports_decode_errors() {
224        let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/invalid.jpg");
225        let error = read(path).expect_err("invalid.jpg should not decode");
226
227        assert_eq!(error.kind(), ErrorKind::Decode);
228    }
229}