include-pnm 1.0.0

Include PNM images directly in Rust code.
Documentation
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
//! PNM parsing.

use std::{
    convert::Infallible,
    fmt,
    fs::File,
    io::{BufRead, BufReader, Read},
    num::NonZero,
    path::Path,
    rc::Rc,
};

use proc_macro::Span;

use crate::cold;

/// PNM magic number.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[repr(u8)]
pub(crate) enum Magic {
    P1 = b'1',
    P2 = b'2',
    P3 = b'3',
    P4 = b'4',
    P5 = b'5',
    P6 = b'6',
    P7 = b'7',
}

/// Reader for file.
pub(crate) struct Reader {
    /// Path of file.
    path: Rc<Path>,

    /// Reader for file.
    reader: BufReader<File>,
}
impl Reader {
    /// Load file.
    pub(crate) fn open(path: &str) -> Reader {
        let span = Span::call_site();
        let mut source = span.local_file().unwrap_or_else(|| {
            panic!(
                "can't include file {path:?} from non-file {:?}",
                span.file()
            )
        });
        source.pop();
        source.push(path);
        let path = <Rc<Path>>::from(source);
        let file = File::open(&path).unwrap_or_else(|e| cold::io_failure("open", &path, &e));
        let reader = BufReader::new(file);
        Reader { path, reader }
    }

    /// Read magic number.
    pub(crate) fn read_magic(&mut self) -> Magic {
        let mut magic = [0; 2];
        self.reader
            .read_exact(&mut magic)
            .unwrap_or_else(|e| cold::io_failure("read", &self.path, &e));
        assert!(
            magic[0] == b'P',
            "{} wasn't a PNM file",
            self.path.display()
        );
        match magic[1] {
            b'1' => Magic::P1,
            b'2' => Magic::P2,
            b'3' => Magic::P3,
            b'4' => Magic::P4,
            b'5' => Magic::P5,
            b'6' => Magic::P6,
            b'7' => Magic::P7,
            _ => panic!("{} wasn't a PNM file", self.path.display()),
        }
    }

    /// Read token.
    pub(crate) fn read_token<T: IntoTokenizer>(
        &mut self,
        into_tokenizer: T,
    ) -> <<T as IntoTokenizer>::Output as Tokenizer>::Output {
        let mut token = into_tokenizer.into_tokenizer();
        let mut token_started = false;
        let mut buf = [0u8];
        loop {
            self.reader
                .read_exact(&mut buf)
                .unwrap_or_else(|e| cold::io_failure("read", &self.path, &e));
            let b = buf[0];
            if b.is_ascii_whitespace() {
                if token_started {
                    return token.finish();
                }
            } else if b == b'#' {
                self.reader
                    .skip_until(b'\n')
                    .unwrap_or_else(|e| cold::io_failure("read", &self.path, &e));
                if token_started {
                    return token.finish();
                }
            } else {
                token_started = true;
                if let Err(e) = token.receive(b) {
                    cold::io_failure("parse", &self.path, &e);
                }
            }
        }
    }

    /// Read several tokens.
    pub(crate) fn read_tokens<T: IntoTokenizer + Clone>(
        &mut self,
        into_tokenizer: T,
    ) -> Tokens<'_, T> {
        Tokens {
            reader: self,
            into_tokenizer,
        }
    }

    /// Read bytes.
    pub(crate) fn read_bytes(&mut self) -> impl Iterator<Item = u8> {
        self.reader
            .by_ref()
            .bytes()
            .map(|b| b.unwrap_or_else(|e| cold::io_failure("read", &self.path, &e)))
    }

    /// Path to file.
    pub(crate) fn path(&self) -> Rc<Path> {
        self.path.clone()
    }
}
impl fmt::Display for Reader {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.path.display(), f)
    }
}
impl fmt::Debug for Reader {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Reader")
            .field("path", &self.path)
            .finish_non_exhaustive()
    }
}

/// Read multiple tokens.
#[derive(Debug)]
pub(crate) struct Tokens<'a, T> {
    /// Reader doing the reads.
    reader: &'a mut Reader,

    /// Tokenizer doing the tokenizing.
    into_tokenizer: T,
}
impl<T: IntoTokenizer + Clone> Iterator for Tokens<'_, T> {
    type Item = <<T as IntoTokenizer>::Output as Tokenizer>::Output;
    fn next(&mut self) -> Option<Self::Item> {
        Some(self.reader.read_token(self.into_tokenizer.clone()))
    }
}

/// Converts into `Tokenizer`.
pub(crate) trait IntoTokenizer {
    /// Resulting tokenizer.
    type Output: Tokenizer;

    /// Conversion.
    fn into_tokenizer(self) -> Self::Output;
}

impl IntoTokenizer for u16 {
    type Output = ParseNum;

    fn into_tokenizer(self) -> Self::Output {
        ParseNum::new(self)
    }
}

/// Parser for token.
pub(crate) trait Tokenizer {
    /// Result token.
    type Output;

    /// Error tokenizing.
    type Error: fmt::Display;

    /// Receive one byte, returning whether it was okay to parse.
    fn receive(&mut self, b: u8) -> Result<(), Self::Error>;

    /// Yield resulting token.
    fn finish(self) -> Self::Output;
}

/// Parse numeric tokens.
#[derive(Debug)]
pub(crate) struct ParseNum {
    /// Maximum value.
    max_value: u16,

    /// Read number.
    num: u16,
}
impl ParseNum {
    /// Create new tokenizer.
    pub(crate) fn new(max_value: u16) -> ParseNum {
        ParseNum { max_value, num: 0 }
    }
}

/// Error tokenizing number.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub(crate) enum NumError {
    /// Non-digit byte.
    NonDigit(u8),

    /// Overflow in computation.
    Overflow(u16),
}
impl fmt::Display for NumError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            NumError::NonDigit(b) => write!(f, "expected digit, found '{}'", b.escape_ascii()),
            NumError::Overflow(max_value) => {
                write!(f, "numeric value exceeded maximum of {}", max_value)
            }
        }
    }
}

impl Tokenizer for ParseNum {
    type Output = u16;
    type Error = NumError;

    fn receive(&mut self, b: u8) -> Result<(), NumError> {
        if !b.is_ascii_digit() {
            return Err(NumError::NonDigit(b));
        }
        self.num = self
            .num
            .checked_mul(10)
            .and_then(|num| num.checked_add((b - b'0') as u16))
            .ok_or(NumError::Overflow(self.max_value))?;
        if self.num > self.max_value {
            Err(NumError::Overflow(self.max_value))
        } else {
            Ok(())
        }
    }

    fn finish(self) -> Self::Output {
        self.num
    }
}

#[test]
fn test_read_num_depth_one() {
    let mut zero = 1u16.into_tokenizer();
    zero.receive(b'0').unwrap();
    assert_eq!(zero.finish(), 0);

    let mut one = 1u16.into_tokenizer();
    one.receive(b'0').unwrap();
    one.receive(b'1').unwrap();
    assert_eq!(one.finish(), 1);

    let mut two = 1u16.into_tokenizer();
    assert_eq!(two.receive(b'2'), Err(NumError::Overflow(1)));

    let mut period = 1u16.into_tokenizer();
    assert_eq!(period.receive(b'.'), Err(NumError::NonDigit(b'.')));
}

#[test]
fn test_read_num_depth_eight() {
    let mut zero = 255u16.into_tokenizer();
    zero.receive(b'0').unwrap();
    assert_eq!(zero.finish(), 0);

    let mut twenty_five = 255u16.into_tokenizer();
    twenty_five.receive(b'2').unwrap();
    twenty_five.receive(b'5').unwrap();
    assert_eq!(twenty_five.finish(), 25);

    let mut three_hundred = 255u16.into_tokenizer();
    three_hundred.receive(b'3').unwrap();
    three_hundred.receive(b'0').unwrap();
    assert_eq!(three_hundred.receive(b'0'), Err(NumError::Overflow(255)));

    let mut period = 255u16.into_tokenizer();
    assert_eq!(period.receive(b'.'), Err(NumError::NonDigit(b'.')));
}

#[test]
fn test_read_num_depth_sixteen() {
    let mut zero = 65535u16.into_tokenizer();
    zero.receive(b'0').unwrap();
    assert_eq!(zero.finish(), 0);

    let mut sixty_five_thousand = 65535u16.into_tokenizer();
    sixty_five_thousand.receive(b'6').unwrap();
    sixty_five_thousand.receive(b'5').unwrap();
    sixty_five_thousand.receive(b'0').unwrap();
    sixty_five_thousand.receive(b'0').unwrap();
    sixty_five_thousand.receive(b'0').unwrap();
    assert_eq!(sixty_five_thousand.finish(), 65000);

    let mut seventy_thousand = 65535u16.into_tokenizer();
    seventy_thousand.receive(b'7').unwrap();
    seventy_thousand.receive(b'0').unwrap();
    seventy_thousand.receive(b'0').unwrap();
    seventy_thousand.receive(b'0').unwrap();
    assert_eq!(
        seventy_thousand.receive(b'0'),
        Err(NumError::Overflow(65535))
    );

    let mut period = 65535u16.into_tokenizer();
    assert_eq!(period.receive(b'.'), Err(NumError::NonDigit(b'.')));
}

/// Parse TUPLTYPE.
///
/// (Accepts all strings.)
pub(crate) struct TuplType;
impl IntoTokenizer for TuplType {
    type Output = TuplType;
    fn into_tokenizer(self) -> Self::Output {
        self
    }
}
impl Tokenizer for TuplType {
    type Output = ();
    type Error = Infallible;

    fn receive(&mut self, _: u8) -> Result<(), Self::Error> {
        Ok(())
    }

    fn finish(self) {}
}

/// Parse PAM header.
pub(crate) struct Header;
impl IntoTokenizer for Header {
    type Output = ParseHeader;
    fn into_tokenizer(self) -> Self::Output {
        ParseHeader::new()
    }
}

/// PAM header directive.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub(crate) enum HeaderDirective {
    /// `ENDHDR`.
    EndHdr,

    /// `HEIGHT`.
    Height,

    /// `WIDTH`.
    Width,

    /// `DEPTH`.
    Depth,

    /// `MAXVAL`.
    MaxVal,

    /// `TUPLTYPE`.
    TuplType,
}
impl HeaderDirective {
    /// Gets string for directive.
    fn as_str(self) -> &'static str {
        match self {
            HeaderDirective::EndHdr => "ENDHDR",
            HeaderDirective::Height => "HEIGHT",
            HeaderDirective::Width => "WIDTH",
            HeaderDirective::Depth => "DEPTH",
            HeaderDirective::MaxVal => "MAXVAL",
            HeaderDirective::TuplType => "TUPLTYPE",
        }
    }
}

/// Error parsing PAM header.
pub(crate) struct HeaderError {
    /// Valid prefix that was read.
    prefix: &'static str,

    /// Invalid character after valid prefix.
    b: u8,
}
impl fmt::Display for HeaderError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "unknown PAM header directive starting with \"{}{}\"",
            self.prefix,
            self.b.escape_ascii()
        )
    }
}

/// Parse PAM header directive.
pub(crate) struct ParseHeader {
    /// Current header directive being read.
    ///
    /// The `read` variable indicates how many characters of the directive have been read so far.
    /// This is just a best guess, but since all the headers start with a different letter, it
    /// will be the correct header in all cases except before anything has been parsed.
    head: HeaderDirective,

    /// Number of characters read, including the currently read character.
    read: NonZero<usize>,
}
impl ParseHeader {
    /// Creates a new [`ParseHeader`].
    fn new() -> ParseHeader {
        ParseHeader {
            head: HeaderDirective::EndHdr,
            read: const { NonZero::new(1).unwrap() },
        }
    }
}

impl Tokenizer for ParseHeader {
    type Output = HeaderDirective;
    type Error = HeaderError;
    fn receive(&mut self, b: u8) -> Result<(), HeaderError> {
        self.head = match (self.head, self.read.get(), b) {
            (_, 1, b'E')
            | (HeaderDirective::EndHdr, 2, b'N')
            | (HeaderDirective::EndHdr, 3, b'D')
            | (HeaderDirective::EndHdr, 4, b'H')
            | (HeaderDirective::EndHdr, 5, b'D')
            | (HeaderDirective::EndHdr, 6, b'R') => HeaderDirective::EndHdr,
            (_, 1, b'H')
            | (HeaderDirective::Height, 2, b'E')
            | (HeaderDirective::Height, 3, b'I')
            | (HeaderDirective::Height, 4, b'G')
            | (HeaderDirective::Height, 5, b'H')
            | (HeaderDirective::Height, 6, b'T') => HeaderDirective::Height,
            (_, 1, b'W')
            | (HeaderDirective::Width, 2, b'I')
            | (HeaderDirective::Width, 3, b'D')
            | (HeaderDirective::Width, 4, b'T')
            | (HeaderDirective::Width, 5, b'H') => HeaderDirective::Width,
            (_, 1, b'D')
            | (HeaderDirective::Depth, 2, b'E')
            | (HeaderDirective::Depth, 3, b'P')
            | (HeaderDirective::Depth, 4, b'T')
            | (HeaderDirective::Depth, 5, b'H') => HeaderDirective::Depth,
            (_, 1, b'M')
            | (HeaderDirective::MaxVal, 2, b'A')
            | (HeaderDirective::MaxVal, 3, b'X')
            | (HeaderDirective::MaxVal, 4, b'V')
            | (HeaderDirective::MaxVal, 5, b'A')
            | (HeaderDirective::MaxVal, 6, b'L') => HeaderDirective::MaxVal,
            (_, 1, b'T')
            | (HeaderDirective::TuplType, 2, b'U')
            | (HeaderDirective::TuplType, 3, b'P')
            | (HeaderDirective::TuplType, 4, b'L')
            | (HeaderDirective::TuplType, 5, b'T')
            | (HeaderDirective::TuplType, 6, b'Y')
            | (HeaderDirective::TuplType, 7, b'P')
            | (HeaderDirective::TuplType, 8, b'E') => HeaderDirective::TuplType,
            (head, idx, b) => {
                return Err(HeaderError {
                    prefix: &head.as_str()[..idx - 1],
                    b,
                });
            }
        };
        self.read = NonZero::new(self.read.get() + 1).unwrap();
        Ok(())
    }
    fn finish(self) -> Self::Output {
        self.head
    }
}