1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
use std::error::Error;
use std::fmt;
use std::fmt::Display;
use std::io;
use std::str;
use std::string;
use std::sync::Arc;

use jpeg::UnsupportedFeature;

use crate::decoder::{ifd::Value, ChunkType};
use crate::tags::{
    CompressionMethod, PhotometricInterpretation, PlanarConfiguration, SampleFormat, Tag,
};
use crate::ColorType;

use crate::weezl::LzwError;

/// Tiff error kinds.
#[derive(Debug)]
pub enum TiffError {
    /// The Image is not formatted properly.
    FormatError(TiffFormatError),

    /// The Decoder does not support features required by the image.
    UnsupportedError(TiffUnsupportedError),

    /// An I/O Error occurred while decoding the image.
    IoError(io::Error),

    /// The Limits of the Decoder is exceeded.
    LimitsExceeded,

    /// An integer conversion to or from a platform size failed, either due to
    /// limits of the platform size or limits of the format.
    IntSizeError,

    /// The image does not support the requested operation
    UsageError(UsageError),
}

/// The image is not formatted properly.
///
/// This indicates that the encoder producing the image might behave incorrectly or that the input
/// file has been corrupted.
///
/// The list of variants may grow to incorporate errors of future features. Matching against this
/// exhaustively is not covered by interface stability guarantees.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum TiffFormatError {
    TiffSignatureNotFound,
    TiffSignatureInvalid,
    ImageFileDirectoryNotFound,
    InconsistentSizesEncountered,
    UnexpectedCompressedData {
        actual_bytes: usize,
        required_bytes: usize,
    },
    InconsistentStripSamples {
        actual_samples: usize,
        required_samples: usize,
    },
    InvalidDimensions(u32, u32),
    InvalidTag,
    InvalidTagValueType(Tag),
    RequiredTagNotFound(Tag),
    UnknownPredictor(u16),
    UnknownPlanarConfiguration(u16),
    ByteExpected(Value),
    UnsignedIntegerExpected(Value),
    SignedIntegerExpected(Value),
    Format(String),
    RequiredTagEmpty(Tag),
    StripTileTagConflict,
    CycleInOffsets,
    JpegDecoder(JpegDecoderError),
    SamplesPerPixelIsZero,
}

impl fmt::Display for TiffFormatError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        use self::TiffFormatError::*;
        match *self {
            TiffSignatureNotFound => write!(fmt, "TIFF signature not found."),
            TiffSignatureInvalid => write!(fmt, "TIFF signature invalid."),
            ImageFileDirectoryNotFound => write!(fmt, "Image file directory not found."),
            InconsistentSizesEncountered => write!(fmt, "Inconsistent sizes encountered."),
            UnexpectedCompressedData {
                actual_bytes,
                required_bytes,
            } => {
                write!(
                    fmt,
                    "Decompression returned different amount of bytes than expected: got {}, expected {}.",
                    actual_bytes, required_bytes
                )
            }
            InconsistentStripSamples {
                actual_samples,
                required_samples,
            } => {
                write!(
                    fmt,
                    "Inconsistent elements in strip: got {}, expected {}.",
                    actual_samples, required_samples
                )
            }
            InvalidDimensions(width, height) => write!(fmt, "Invalid dimensions: {}x{}.", width, height),
            InvalidTag => write!(fmt, "Image contains invalid tag."),
            InvalidTagValueType(ref tag) => {
                write!(fmt, "Tag `{:?}` did not have the expected value type.", tag)
            }
            RequiredTagNotFound(ref tag) => write!(fmt, "Required tag `{:?}` not found.", tag),
            UnknownPredictor(ref predictor) => {
                write!(fmt, "Unknown predictor “{}” encountered", predictor)
            }
            UnknownPlanarConfiguration(ref planar_config) =>  {
                write!(fmt, "Unknown planar configuration “{}” encountered", planar_config)
            }
            ByteExpected(ref val) => write!(fmt, "Expected byte, {:?} found.", val),
            UnsignedIntegerExpected(ref val) => {
                write!(fmt, "Expected unsigned integer, {:?} found.", val)
            }
            SignedIntegerExpected(ref val) => {
                write!(fmt, "Expected signed integer, {:?} found.", val)
            }
            Format(ref val) => write!(fmt, "Invalid format: {:?}.", val),
            RequiredTagEmpty(ref val) => write!(fmt, "Required tag {:?} was empty.", val),
            StripTileTagConflict => write!(fmt, "File should contain either (StripByteCounts and StripOffsets) or (TileByteCounts and TileOffsets), other combination was found."),
            CycleInOffsets => write!(fmt, "File contained a cycle in the list of IFDs"),
            JpegDecoder(ref error) => write!(fmt, "{}",  error),
            SamplesPerPixelIsZero => write!(fmt, "Samples per pixel is zero"),
        }
    }
}

/// The Decoder does not support features required by the image.
///
/// This only captures known failures for which the standard either does not require support or an
/// implementation has been planned but not yet completed. Some variants may become unused over
/// time and will then get deprecated before being removed.
///
/// The list of variants may grow. Matching against this exhaustively is not covered by interface
/// stability guarantees.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum TiffUnsupportedError {
    FloatingPointPredictor(ColorType),
    HorizontalPredictor(ColorType),
    InconsistentBitsPerSample(Vec<u8>),
    InterpretationWithBits(PhotometricInterpretation, Vec<u8>),
    UnknownInterpretation,
    UnknownCompressionMethod,
    UnsupportedCompressionMethod(CompressionMethod),
    UnsupportedSampleDepth(u8),
    UnsupportedSampleFormat(Vec<SampleFormat>),
    UnsupportedColorType(ColorType),
    UnsupportedBitsPerChannel(u8),
    UnsupportedPlanarConfig(Option<PlanarConfiguration>),
    UnsupportedDataType,
    UnsupportedInterpretation(PhotometricInterpretation),
    UnsupportedJpegFeature(UnsupportedFeature),
}

impl fmt::Display for TiffUnsupportedError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        use self::TiffUnsupportedError::*;
        match *self {
            FloatingPointPredictor(color_type) => write!(
                fmt,
                "Floating point predictor for {:?} is unsupported.",
                color_type
            ),
            HorizontalPredictor(color_type) => write!(
                fmt,
                "Horizontal predictor for {:?} is unsupported.",
                color_type
            ),
            InconsistentBitsPerSample(ref bits_per_sample) => {
                write!(fmt, "Inconsistent bits per sample: {:?}.", bits_per_sample)
            }
            InterpretationWithBits(ref photometric_interpretation, ref bits_per_sample) => write!(
                fmt,
                "{:?} with {:?} bits per sample is unsupported",
                photometric_interpretation, bits_per_sample
            ),
            UnknownInterpretation => write!(
                fmt,
                "The image is using an unknown photometric interpretation."
            ),
            UnknownCompressionMethod => write!(fmt, "Unknown compression method."),
            UnsupportedCompressionMethod(method) => {
                write!(fmt, "Compression method {:?} is unsupported", method)
            }
            UnsupportedSampleDepth(samples) => {
                write!(fmt, "{} samples per pixel is unsupported.", samples)
            }
            UnsupportedSampleFormat(ref formats) => {
                write!(fmt, "Sample format {:?} is unsupported.", formats)
            }
            UnsupportedColorType(color_type) => {
                write!(fmt, "Color type {:?} is unsupported", color_type)
            }
            UnsupportedBitsPerChannel(bits) => {
                write!(fmt, "{} bits per channel not supported", bits)
            }
            UnsupportedPlanarConfig(config) => {
                write!(fmt, "Unsupported planar configuration “{:?}”.", config)
            }
            UnsupportedDataType => write!(fmt, "Unsupported data type."),
            UnsupportedInterpretation(interpretation) => {
                write!(
                    fmt,
                    "Unsupported photometric interpretation \"{:?}\".",
                    interpretation
                )
            }
            UnsupportedJpegFeature(ref unsupported_feature) => {
                write!(fmt, "Unsupported JPEG feature {:?}", unsupported_feature)
            }
        }
    }
}

/// User attempted to use the Decoder in a way that is incompatible with a specific image.
///
/// For example: attempting to read a tile from a stripped image.
#[derive(Debug)]
pub enum UsageError {
    InvalidChunkType(ChunkType, ChunkType),
    InvalidChunkIndex(u32),
}

impl fmt::Display for UsageError {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        use self::UsageError::*;
        match *self {
            InvalidChunkType(expected, actual) => {
                write!(
                    fmt,
                    "Requested operation is only valid for images with chunk encoding of type: {:?}, got {:?}.",
                    expected, actual
                )
            }
            InvalidChunkIndex(index) => write!(fmt, "Image chunk index ({}) requested.", index),
        }
    }
}

impl fmt::Display for TiffError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        match *self {
            TiffError::FormatError(ref e) => write!(fmt, "Format error: {}", e),
            TiffError::UnsupportedError(ref f) => write!(
                fmt,
                "The Decoder does not support the \
                 image format `{}`",
                f
            ),
            TiffError::IoError(ref e) => e.fmt(fmt),
            TiffError::LimitsExceeded => write!(fmt, "The Decoder limits are exceeded"),
            TiffError::IntSizeError => write!(fmt, "Platform or format size limits exceeded"),
            TiffError::UsageError(ref e) => write!(fmt, "Usage error: {}", e),
        }
    }
}

impl Error for TiffError {
    fn description(&self) -> &str {
        match *self {
            TiffError::FormatError(..) => "Format error",
            TiffError::UnsupportedError(..) => "Unsupported error",
            TiffError::IoError(..) => "IO error",
            TiffError::LimitsExceeded => "Decoder limits exceeded",
            TiffError::IntSizeError => "Platform or format size limits exceeded",
            TiffError::UsageError(..) => "Invalid usage",
        }
    }

    fn cause(&self) -> Option<&dyn Error> {
        match *self {
            TiffError::IoError(ref e) => Some(e),
            _ => None,
        }
    }
}

impl From<io::Error> for TiffError {
    fn from(err: io::Error) -> TiffError {
        TiffError::IoError(err)
    }
}

impl From<str::Utf8Error> for TiffError {
    fn from(_err: str::Utf8Error) -> TiffError {
        TiffError::FormatError(TiffFormatError::InvalidTag)
    }
}

impl From<string::FromUtf8Error> for TiffError {
    fn from(_err: string::FromUtf8Error) -> TiffError {
        TiffError::FormatError(TiffFormatError::InvalidTag)
    }
}

impl From<TiffFormatError> for TiffError {
    fn from(err: TiffFormatError) -> TiffError {
        TiffError::FormatError(err)
    }
}

impl From<TiffUnsupportedError> for TiffError {
    fn from(err: TiffUnsupportedError) -> TiffError {
        TiffError::UnsupportedError(err)
    }
}

impl From<UsageError> for TiffError {
    fn from(err: UsageError) -> TiffError {
        TiffError::UsageError(err)
    }
}

impl From<std::num::TryFromIntError> for TiffError {
    fn from(_err: std::num::TryFromIntError) -> TiffError {
        TiffError::IntSizeError
    }
}

impl From<LzwError> for TiffError {
    fn from(err: LzwError) -> TiffError {
        match err {
            LzwError::InvalidCode => TiffError::FormatError(TiffFormatError::Format(String::from(
                "LZW compressed data corrupted",
            ))),
        }
    }
}

#[derive(Debug, Clone)]
pub struct JpegDecoderError {
    inner: Arc<jpeg::Error>,
}

impl JpegDecoderError {
    fn new(error: jpeg::Error) -> Self {
        Self {
            inner: Arc::new(error),
        }
    }
}

impl PartialEq for JpegDecoderError {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.inner, &other.inner)
    }
}

impl Display for JpegDecoderError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.inner.fmt(f)
    }
}

impl From<JpegDecoderError> for TiffError {
    fn from(error: JpegDecoderError) -> Self {
        TiffError::FormatError(TiffFormatError::JpegDecoder(error))
    }
}

impl From<jpeg::Error> for TiffError {
    fn from(error: jpeg::Error) -> Self {
        JpegDecoderError::new(error).into()
    }
}

/// Result of an image decoding/encoding process
pub type TiffResult<T> = Result<T, TiffError>;