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
//! [Portable BitMap Format](https://en.wikipedia.org/wiki/Netpbm#PBM_example) black and white image encoding and decoding.
//!
//! Unstable api.
pub type Input<'a> = Image<&'a [bool], 1>;
pub type Output = Image<Vec<bool>, 1>;
pub type Uninit = fimg::uninit::Image<bool, 1>;
use crate::encode::{encodeu32, P};
use atools::prelude::*;
use fimg::Image;

#[cfg(test)]
fn tdata() -> Vec<bool> {
    include_bytes!("../tdata/fimg.imgbuf")
        .iter()
        .map(|&x| x <= 128)
        .collect::<Vec<_>>()
}

/// Module for handling plain ascii (human readable) [PBM](https://en.wikipedia.org/wiki/Netpbm#PBM_example) (black and white) images.
pub mod plain {
    use crate::encode::encode_bool;

    use super::*;
    pub const MAGIC: u8 = 1;

    /// Encode an <code>[Image]<[bool], 1></code> into a [PBM](https://en.wikipedia.org/wiki/Netpbm#PBM_example) ASCII Image.
    pub fn encode<T: AsRef<[bool]>>(x: Image<T, 1>) -> String {
        let mut y = Vec::with_capacity(size(x.as_ref()));
        let n = unsafe { encode_into(x.as_ref(), y.as_mut_ptr()) };
        unsafe { y.set_len(n) };
        unsafe { String::from_utf8_unchecked(y) }
    }

    crate::decode::dec_fn! {
        "Decode an ASCII [PBM](https://en.wikipedia.org/wiki/Netpbm#PBM_example) image into an <code>[Image]<[Box]<[bool]>, 1></code>"
    }

    #[doc = include_str!("decode_body_into.md")]
    pub fn decode_body_into(x: &[u8], mut into: Uninit) -> Result<Output> {
        let mut out = into.buf().as_mut_ptr() as *mut bool;
        let pixels = into.width() * into.height();
        for &b in x
            .iter()
            .filter(|&&x| matches!(x, b'0' | b'1'))
            .take(pixels as usize)
        {
            // SAFETY: iterator over `pixels` elements.
            unsafe { out.push(b == b'1') };
        }
        if unsafe { out.sub_ptr(into.buf().as_mut_ptr().cast()) < pixels as usize } {
            return Err(Error::MissingData);
        }
        // SAFETY: checked that the pixels have been initialized.
        Ok(unsafe { into.assume_init() })
    }

    /// Converts 0 to 255 and 1 to 0, for your u8 image experience.
    pub fn decode_body_into_u8(
        x: &[u8],
        mut into: fimg::uninit::Image<u8, 1>,
    ) -> Result<Image<Vec<u8>, 1>> {
        let mut out = into.buf().as_mut_ptr() as *mut u8;
        let pixels = into.width() * into.height();
        for &b in x
            .iter()
            .filter(|&&x| matches!(x, b'0' | b'1'))
            .take(pixels as usize)
        {
            // SAFETY: iterator over `pixels` elements.
            unsafe { out.push((b == b'0') as u8 * 0xff) };
        }
        if unsafe { out.sub_ptr(into.buf().as_mut_ptr().cast()) < pixels as usize } {
            return Err(Error::MissingData);
        }
        // SAFETY: checked that the pixels have been initialized.
        Ok(unsafe { into.assume_init() })
    }

    #[doc = include_str!("encode_into.md")]
    pub unsafe fn encode_into(x: Input, out: *mut u8) -> usize {
        let mut o = out;
        o.put(b'P'.join(MAGIC + b'0'));
        o.push(b' ');
        encodeu32(x.width(), &mut o);
        o.push(b' ');
        encodeu32(x.height(), &mut o);
        o.push(b'\n');
        for row in x.buffer().chunks_exact(x.width() as _) {
            for &on in row {
                o.push(encode_bool(on));
                // cosmetic
                o.push(b' ');
            }
            // cosmetic
            o.push(b'\n');
        }
        o.sub_ptr(out)
    }

    #[doc = include_str!("est.md")]
    pub fn size(x: Input) -> usize {
        2 // P1
            + 23 // \n4294967295 4294967295\n
            + x.height() as usize // \n
            + x.len() * 2 // ' 1'
    }

    #[test]
    fn test_encode() {
        assert_eq!(
            encode(Image::build(20, 15).buf(tdata())),
            include_str!("../tdata/fimgA.pbm")
        );
    }

    #[test]
    fn test_decode() {
        assert_eq!(
            &**decode(include_bytes!("../tdata/fimgA.pbm"))
                .unwrap()
                .buffer(),
            tdata()
        )
    }
}

/// Module for handling raw (packed binary) [PBM](https://en.wikipedia.org/wiki/Netpbm#PBM_example) (black and white) images.
pub mod raw {
    use super::*;
    pub const MAGIC: u8 = 4;
    /// Encode an <code>[Image]<[bool], 1></code> [PBM](https://en.wikipedia.org/wiki/Netpbm#PBM_example) Raw (packed binary) Image.
    pub fn encode<T: AsRef<[bool]>>(x: Image<T, 1>) -> Vec<u8> {
        let mut y = Vec::with_capacity(size(x.as_ref()));
        let n = unsafe { encode_into(x.as_ref(), y.as_mut_ptr()) };
        unsafe { y.set_len(n) };
        y
    }

    crate::decode::dec_fn! {
        "Decode a raw binary [PBM](https://en.wikipedia.org/wiki/Netpbm#PBM_example) image into an <code>[Image]<[Box]<[bool]>, 1></code>"
    }

    #[doc = include_str!("encode_into.md")]
    pub unsafe fn encode_into(x: Input, out: *mut u8) -> usize {
        let mut o = out;
        o.put(b'P'.join(MAGIC + b'0'));
        o.push(b' ');
        encodeu32(x.width(), &mut o);
        o.push(b' ');
        encodeu32(x.height(), &mut o);
        o.push(b'\n');
        x.buffer()
            .chunks_exact(x.width() as _)
            .flat_map(|x| x.chunks(8))
            .map(|chunk| {
                chunk
                    .iter()
                    .copied()
                    .chain(std::iter::repeat(false).take(8 - chunk.len()))
                    .zip(0u8..)
                    .fold(0, |acc, (x, i)| acc | (x as u8) << 7 - i)
            })
            .for_each(|x| o.push(x));

        o.sub_ptr(out)
    }

    #[doc = include_str!("decode_body_into.md")]
    pub fn decode_body_into(x: &[u8], mut into: Uninit) -> Result<Output> {
        let mut out = into.buf().as_mut_ptr() as *mut bool;
        let pixels = into.width() * into.height();
        let padding = into.width() % 8;
        for &x in x
            .iter()
            .copied()
            // expand the bits
            .flat_map(|b| atools::range::<8>().rev().map(|x| b & (1 << x) != 0))
            // TODO skip?
            .collect::<Vec<_>>()
            .chunks_exact((into.width() + padding) as _)
            .map(|x| &x[..into.width() as _])
            .take(pixels as _)
            .flatten()
        {
            // SAFETY: took `pixels` pixels.
            unsafe { out.push(x) };
        }
        if unsafe { out.sub_ptr(into.buf().as_mut_ptr().cast()) < pixels as usize } {
            return Err(Error::MissingData);
        }
        // SAFETY: checked that the pixels have been initialized.
        Ok(unsafe { into.assume_init() })
    }

    #[doc = include_str!("decode_body_into.md")]
    pub fn decode_body_into_u8(
        x: &[u8],
        mut into: fimg::uninit::Image<u8, 1>,
    ) -> Result<Image<Vec<u8>, 1>> {
        let mut out = into.buf().as_mut_ptr() as *mut u8;
        let pixels = into.width() * into.height();
        let padding = into.width() % 8;
        for x in x
            .iter()
            .copied()
            // expand the bits
            .flat_map(|b| atools::range::<8>().rev().map(|x| b & (1 << x) == 0))
            // TODO skip?
            .collect::<Vec<_>>()
            .chunks_exact((into.width() + padding) as _)
            .map(|x| &x[..into.width() as _])
            .take(pixels as _)
            .flatten()
            .map(|&x| x as u8 * 0xff)
        {
            // SAFETY: took `pixels` pixels.
            unsafe { out.push(x) };
        }
        if unsafe { out.sub_ptr(into.buf().as_mut_ptr().cast()) < pixels as usize } {
            return Err(Error::MissingData);
        }
        // SAFETY: checked that the pixels have been initialized.
        Ok(unsafe { into.assume_init() })
    }
    #[doc = include_str!("est.md")]
    pub fn size(x: Input) -> usize {
        2 // magic
            + 23 // w h
            + (x.len() / 8) // packed pixels
            + ((x.width() as usize % 8 != 0) as usize * x.height() as usize) // padding
    }

    #[test]
    fn test_decode() {
        assert_eq!(
            &**decode(include_bytes!("../tdata/fimgR.pbm"))
                .unwrap()
                .buffer(),
            tdata()
        )
    }

    #[test]
    fn test_encode() {
        assert_eq!(
            encode(Image::build(20, 15).buf(tdata())),
            include_bytes!("../tdata/fimgR.pbm")
        );
    }
}