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
#![no_std]
pub enum DecodeErrorPPM {
NotPPM,
BadNum,
}
impl ::core::fmt::Debug for DecodeErrorPPM {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "Couldn't parse PPM because: {}", match *self {
DecodeErrorPPM::NotPPM => "Not a PPM file (bad header)",
DecodeErrorPPM::BadNum => "Dimensions are not numbers",
})
}
}
fn skip_line(ppm: &'static [u8], index: &mut usize) {
while ppm[*index] != b'\n' {
*index += 1;
}
*index += 1;
}
fn utf8_to_u32(ppm: &'static [u8], index: &mut usize, until: u8)
-> Result<u32, DecodeErrorPPM>
{
let zero = b'0';
let mut number = 0;
while ppm[*index] != until {
let digit = ppm[*index];
number *= 10;
if digit != zero {
if digit < zero || digit > zero + 9 {
return Err(DecodeErrorPPM::BadNum);
}
number += (digit - zero) as u32;
}
*index += 1;
}
*index += 1;
Ok(number)
}
pub fn decode(ppm: &'static [u8])
-> Result<(u32, u32, &'static [u8]), DecodeErrorPPM>
{
let mut index = 3;
if ppm[0] != b'P' || ppm[1] != b'6' {
return Err(DecodeErrorPPM::NotPPM);
}
if ppm[index] == b'#' {
skip_line(ppm, &mut index);
}
let width = utf8_to_u32(ppm, &mut index, b' ')?;
let height = utf8_to_u32(ppm, &mut index, b'\n')?;
skip_line(ppm, &mut index);
Ok((width, height, &ppm[index..]))
}