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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
use std::path::Path;

use naut_core::image;

use crate::errors::{FormatError, SicIoError};

pub trait EncodingFormatByExtension {
    /// Determine the encoding format based on the extension of a file path.
    fn by_extension<P: AsRef<Path>>(&self, path: P)
        -> Result<image::ImageOutputFormat, SicIoError>;
}

pub trait EncodingFormatByIdentifier {
    /// Determine the encoding format based on the method of exporting.
    /// Determine the encoding format based on a recognized given identifier.
    fn by_identifier(&self, identifier: &str) -> Result<image::ImageOutputFormat, SicIoError>;
}

pub trait EncodingFormatJPEGQuality {
    /// Returns a validated jpeg quality value.
    /// If no such value exists, it will return an error instead.
    fn jpeg_quality(&self) -> Result<JPEGQuality, SicIoError>;
}

pub trait EncodingFormatPNMSampleEncoding {
    /// Returns a pnm sample encoding type.
    /// If no such value exists, it will return an error instead.
    fn pnm_encoding_type(&self) -> Result<image::pnm::SampleEncoding, SicIoError>;
}

/// This struct ensures no invalid JPEG qualities can be stored.
/// Using this struct instead of `u8` directly should ensure no panics occur because of invalid
/// quality values.
#[derive(Debug, Clone, Copy, Ord, PartialOrd, Eq, PartialEq)]
pub struct JPEGQuality {
    quality: u8,
}

impl Default for JPEGQuality {
    /// The default JPEG quality is `80`.
    fn default() -> Self {
        Self { quality: 80 }
    }
}

impl JPEGQuality {
    /// Returns an Ok result if the quality requested is between 1 and 100 (inclusive).
    pub fn try_from(quality: u8) -> Result<Self, SicIoError> {
        if (1u8..=100u8).contains(&quality) {
            Ok(JPEGQuality { quality })
        } else {
            Err(SicIoError::FormatError(
                FormatError::JPEGQualityLevelNotInRange,
            ))
        }
    }

    /// Return the valid quality value.
    pub fn as_u8(self) -> u8 {
        self.quality
    }
}

impl EncodingFormatByExtension for DetermineEncodingFormat {
    /// Determines the encoding format based on the extension of the given path.
    /// If the path has no extension, it will return an error.
    /// The extension if existing is matched against the identifiers, which currently
    /// are the extensions used.
    fn by_extension<P: AsRef<Path>>(
        &self,
        path: P,
    ) -> Result<image::ImageOutputFormat, SicIoError> {
        let extension = path.as_ref().extension().and_then(|v| v.to_str());

        match extension {
            Some(some) => self.by_identifier(some),
            None => Err(SicIoError::UnableToDetermineImageFormatFromFileExtension(
                path.as_ref().to_path_buf(),
            )),
        }
    }
}

impl EncodingFormatByIdentifier for DetermineEncodingFormat {
    /// Determines an image output format based on a given `&str` identifier.
    /// Identifiers are based on common output file extensions.
    fn by_identifier(&self, identifier: &str) -> Result<image::ImageOutputFormat, SicIoError> {
        match identifier.to_ascii_lowercase().as_str() {
            "avif" => {
                // FIXME: Dirty hack
                //  - https://github.com/foresterre/naut/issues/597
                std::env::set_var("SIC_AVIF_HACK", "1");
                Ok(image::ImageOutputFormat::Farbfeld)
            }
            "bmp" => Ok(image::ImageOutputFormat::Bmp),
            "farbfeld" => Ok(image::ImageOutputFormat::Farbfeld),
            "gif" => Ok(image::ImageOutputFormat::Gif),
            "ico" => Ok(image::ImageOutputFormat::Ico),
            "jpeg" | "jpg" => Ok(image::ImageOutputFormat::Jpeg(self.jpeg_quality()?.as_u8())),
            "pam" => Ok(image::ImageOutputFormat::Pnm(
                image::pnm::PNMSubtype::ArbitraryMap,
            )),
            "pbm" => Ok(image::ImageOutputFormat::Pnm(
                image::pnm::PNMSubtype::Bitmap(self.pnm_encoding_type()?),
            )),
            "pgm" => Ok(image::ImageOutputFormat::Pnm(
                image::pnm::PNMSubtype::Graymap(self.pnm_encoding_type()?),
            )),
            "png" => Ok(image::ImageOutputFormat::Png),
            "ppm" => Ok(image::ImageOutputFormat::Pnm(
                image::pnm::PNMSubtype::Pixmap(self.pnm_encoding_type()?),
            )),
            "tga" => Ok(image::ImageOutputFormat::Tga),
            _ => Err(SicIoError::UnknownImageIdentifier(identifier.to_string())),
        }
    }
}

pub struct DetermineEncodingFormat {
    pub pnm_sample_encoding: Option<image::pnm::SampleEncoding>,
    pub jpeg_quality: Option<JPEGQuality>,
}

impl Default for DetermineEncodingFormat {
    fn default() -> Self {
        Self {
            pnm_sample_encoding: Some(image::pnm::SampleEncoding::Binary),
            jpeg_quality: Some(Default::default()),
        }
    }
}

impl EncodingFormatPNMSampleEncoding for DetermineEncodingFormat {
    fn pnm_encoding_type(&self) -> Result<image::pnm::SampleEncoding, SicIoError> {
        self.pnm_sample_encoding
            .ok_or_else(|| SicIoError::FormatError(FormatError::PNMSamplingEncodingNotSet))
    }
}

impl EncodingFormatJPEGQuality for DetermineEncodingFormat {
    fn jpeg_quality(&self) -> Result<JPEGQuality, SicIoError> {
        self.jpeg_quality
            .ok_or_else(|| SicIoError::FormatError(FormatError::JPEGQualityLevelNotSet))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const INPUT_FORMATS: &[&str] = &[
        //"avif",
        "bmp", "farbfeld", "gif", "ico", "jpg", "jpeg", "png", "pbm", "pgm", "ppm", "pam", "tga",
    ];

    const EXPECTED_VALUES: &[image::ImageOutputFormat] = &[
        // image::ImageOutputFormat::Avif,
        image::ImageOutputFormat::Bmp,
        image::ImageOutputFormat::Farbfeld,
        image::ImageOutputFormat::Gif,
        image::ImageOutputFormat::Ico,
        image::ImageOutputFormat::Jpeg(80),
        image::ImageOutputFormat::Jpeg(80),
        image::ImageOutputFormat::Png,
        image::ImageOutputFormat::Pnm(image::pnm::PNMSubtype::Bitmap(
            image::pnm::SampleEncoding::Binary,
        )),
        image::ImageOutputFormat::Pnm(image::pnm::PNMSubtype::Graymap(
            image::pnm::SampleEncoding::Binary,
        )),
        image::ImageOutputFormat::Pnm(image::pnm::PNMSubtype::Pixmap(
            image::pnm::SampleEncoding::Binary,
        )),
        image::ImageOutputFormat::Pnm(image::pnm::PNMSubtype::ArbitraryMap),
        image::ImageOutputFormat::Tga,
    ];

    fn setup_default_format_determiner() -> DetermineEncodingFormat {
        DetermineEncodingFormat {
            pnm_sample_encoding: Some(image::pnm::SampleEncoding::Binary),
            jpeg_quality: Some(JPEGQuality::try_from(80).unwrap()),
        }
    }

    //
    fn test_with_extensions(ext: &str, expected: &image::ImageOutputFormat) {
        let path = format!("w_ext.{}", ext);

        let format_determiner = setup_default_format_determiner();
        let result = format_determiner.by_extension(path.as_str());

        assert_eq!(result.unwrap(), *expected);
    }

    #[test]
    fn extension_with_defaults() {
        let zipped = INPUT_FORMATS.iter().zip(EXPECTED_VALUES.iter());

        for (ext, exp) in zipped {
            test_with_extensions(ext, exp);
        }
    }

    //
    #[test]
    #[should_panic]
    fn extension_unknown_extension() {
        let path = "w_ext.h";
        let format_determiner = setup_default_format_determiner();
        let result = format_determiner.by_extension(path);

        result.unwrap();
    }

    //
    #[test]
    #[should_panic]
    fn extension_no_extension() {
        let path = "png";
        let format_determiner = setup_default_format_determiner();
        let result = format_determiner.by_extension(path);

        result.unwrap();
    }

    //
    #[test]
    #[should_panic]
    fn extension_invalid_extension() {
        let path = ".png";
        let format_determiner = setup_default_format_determiner();
        let result = format_determiner.by_extension(path);

        result.unwrap();
    }

    //
    fn test_with_identifier(identifier: &str, expected: &image::ImageOutputFormat) {
        let format_determiner = setup_default_format_determiner();
        let result = format_determiner.by_identifier(identifier);

        assert_eq!(result.unwrap(), *expected);
    }

    #[test]
    fn identifier_with_defaults() {
        let zipped = INPUT_FORMATS.iter().zip(EXPECTED_VALUES.iter());

        for (id, exp) in zipped {
            test_with_identifier(id, exp);
        }
    }
    #[test]
    fn uppercase_formats() {
        let uppercase_formats = INPUT_FORMATS
            .iter()
            .map(|v| v.to_ascii_uppercase())
            .zip(EXPECTED_VALUES.iter());

        for (id, exp) in uppercase_formats {
            test_with_identifier(id.as_str(), exp);
        }
    }

    //
    #[test]
    #[should_panic]
    fn identifier_unknown_identifier() {
        let format_determiner = setup_default_format_determiner();
        let result = format_determiner.by_identifier("");

        result.unwrap();
    }

    // non default: pnm ascii + "pbm"
    #[test]
    fn identifier_custom_pnm_sample_encoding_ascii_pbm() {
        let format_determiner = DetermineEncodingFormat {
            pnm_sample_encoding: Some(image::pnm::SampleEncoding::Ascii),
            jpeg_quality: None,
        };

        let result = format_determiner.by_identifier("pbm").unwrap();
        let expected = image::ImageOutputFormat::Pnm(image::pnm::PNMSubtype::Bitmap(
            image::pnm::SampleEncoding::Ascii,
        ));

        assert_eq!(result, expected);
    }

    // non default: pnm ascii + "pgm"
    #[test]
    fn identifier_custom_pnm_sample_encoding_ascii_pgm() {
        let format_determiner = DetermineEncodingFormat {
            pnm_sample_encoding: Some(image::pnm::SampleEncoding::Ascii),
            jpeg_quality: None,
        };

        let result = format_determiner.by_identifier("pgm").unwrap();
        let expected = image::ImageOutputFormat::Pnm(image::pnm::PNMSubtype::Graymap(
            image::pnm::SampleEncoding::Ascii,
        ));

        assert_eq!(result, expected);
    }

    // non default: pnm ascii + "ppm"
    #[test]
    fn identifier_custom_pnm_sample_encoding_ascii_ppm() {
        let format_determiner = DetermineEncodingFormat {
            pnm_sample_encoding: Some(image::pnm::SampleEncoding::Ascii),
            jpeg_quality: None,
        };

        let result = format_determiner.by_identifier("ppm").unwrap();
        let expected = image::ImageOutputFormat::Pnm(image::pnm::PNMSubtype::Pixmap(
            image::pnm::SampleEncoding::Ascii,
        ));

        assert_eq!(result, expected);
    }

    // non default: jpeg custom, quality lower bound
    #[test]
    fn identifier_custom_jpeg_quality_in_range_lower() {
        let format_determiner = DetermineEncodingFormat {
            pnm_sample_encoding: None,
            jpeg_quality: Some(JPEGQuality::try_from(1).unwrap()),
        };

        let result = format_determiner.by_identifier("jpg").unwrap();
        let expected = image::ImageOutputFormat::Jpeg(1);

        assert_eq!(result, expected);
    }

    // non default: jpeg custom, quality upper bound
    #[test]
    fn identifier_custom_jpeg_quality_in_range_upper() {
        let format_determiner = DetermineEncodingFormat {
            pnm_sample_encoding: None,
            jpeg_quality: Some(JPEGQuality::try_from(100).unwrap()),
        };

        let result = format_determiner.by_identifier("jpg").unwrap();
        let expected = image::ImageOutputFormat::Jpeg(100);

        assert_eq!(result, expected);
    }

    // if we were to test 'identifier_custom_jpeg_quality_OUT_range_[lower/upper]'
    //                                                    ^^^
    // our DetermineEncodingFormat would fail on creation by JPEGQuality::try_from which fails
    // on outbound ranges

    //
    #[test]
    fn jpeg_quality_in_range_lower() {
        let result = JPEGQuality::try_from(1).unwrap();
        let expected = JPEGQuality { quality: 1 };

        assert_eq!(result, expected);
    }

    //
    #[test]
    fn jpeg_quality_in_range_upper() {
        let result = JPEGQuality::try_from(100).unwrap();
        let expected = JPEGQuality { quality: 100 };

        assert_eq!(result, expected);
    }

    //
    #[test]
    #[should_panic]
    fn jpeg_quality_out_range_lower() {
        let result = JPEGQuality::try_from(0).unwrap();
        let expected = JPEGQuality { quality: 0 };

        assert_eq!(result, expected);
    }

    //
    #[test]
    #[should_panic]
    fn jpeg_quality_out_range_upper() {
        let result = JPEGQuality::try_from(101).unwrap();
        let expected = JPEGQuality { quality: 101 };

        assert_eq!(result, expected);
    }

    // DetermineEncodingFormat has None, while Some required: pbm
    #[test]
    #[should_panic]
    fn identifier_requires_pnm_sample_encoding_to_be_set_pbm() {
        let format_determiner = DetermineEncodingFormat {
            pnm_sample_encoding: None,
            jpeg_quality: None,
        };

        format_determiner.by_identifier("pbm").unwrap();
    }

    // DetermineEncodingFormat has None, while Some required: pbm
    #[test]
    #[should_panic]
    fn identifier_requires_pnm_sample_encoding_to_be_set_pgm() {
        let format_determiner = DetermineEncodingFormat {
            pnm_sample_encoding: None,
            jpeg_quality: None,
        };

        format_determiner.by_identifier("pgm").unwrap();
    }

    // DetermineEncodingFormat has None, while Some required: ppm
    #[test]
    #[should_panic]
    fn identifier_requires_pnm_sample_encoding_to_be_set_ppm() {
        let format_determiner = DetermineEncodingFormat {
            pnm_sample_encoding: None,
            jpeg_quality: None,
        };

        format_determiner.by_identifier("ppm").unwrap();
    }

    // DetermineEncodingFormat has None, while Some required: jpg
    #[test]
    #[should_panic]
    fn identifier_requires_pnm_sample_encoding_to_be_set_jpg() {
        let format_determiner = DetermineEncodingFormat {
            pnm_sample_encoding: None,
            jpeg_quality: None,
        };

        format_determiner.by_identifier("jpg").unwrap();
    }
}