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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
//!# PWG Raster
//!
//!Decoding of Printer Working Group Candidate Standard 5102.4-2012 raster images.
//!
//!# Decoding multiple pages
//!
//! [next_page()](struct.PWGReader.html#method.next_page) will call a closure with a page structure that allows access to
//! the header and page data. It will return Ok(None) when there are no more
//! pages.
//!
//!```no_run
//!use std::fs::File;
//!use std::io::BufReader;
//!use pwgraster::PWGReader;
//!let infile = File::open("./color.jpg-4x6-srgb-8-600dpi.pwg")
//!                 .expect("Failed to open input");
//!let mut pwg = PWGReader::new(BufReader::new(infile), true).unwrap();
//!while pwg.next_page(|page| {
//!        let width = page.header().Width().unwrap();
//!        let height = page.header().Height().unwrap();
//!        println!("Page dimensions {}x{}", width, height);
//!        let mut buf = Vec::with_capacity(page.header().image_size_bytes().unwrap());
//!        println!("Reading page");
//!        page.unpack(&mut buf).unwrap();
//!        println!("Page read");
//!        // Do something with image data
//!        Ok(())
//!    }).unwrap().is_some() {}
//!```
extern crate byteorder;
#[macro_use]
extern crate enum_primitive;
extern crate memchr;

use std::io::{self, Read, Write};
use byteorder::ReadBytesExt;

#[derive(Debug, PartialEq, Eq)]
pub enum ErrorKind {
    UnterminatedString,
    InvalidUTF8,
    BadPwgRasterString,
    BadEnumValue(u32),
    /// A reserved field contained a non-zero byte
    NonZeroReserved,
    /// The unused high byte was set in SrgbColor
    InvalidColor,
}

#[derive(Debug)]
pub struct Error {
    field: &'static str,
    offset: usize,
    err: ErrorKind,
}

#[derive(Debug)]
pub enum StreamError {
    /// Decoding a header field failed
    HeaderError(Error),
    /// Error from Read or Write
    IO(io::Error),
    /// Initial sync word != PWG_SYNC_WORD
    BadSyncWord,
    /// Pixel repeat exceeded line length
    LineOverflow,
    /// Line repeat exceeded image height
    HeightOverflow,
    /// bpp is not 1 or a multiple of 8
    UnsupportedBpp,
}

impl From<Error> for StreamError {
    fn from(e: Error) -> Self {
        StreamError::HeaderError(e)
    }
}

impl From<io::Error> for StreamError {
    fn from(e: io::Error) -> Self {
        StreamError::IO(e)
    }
}

/// Data types used in the PWG header
pub mod types {
    use std::str;
    use byteorder::{ByteOrder, BigEndian};
    use enum_primitive::FromPrimitive;
    use memchr::memchr;
    use ErrorKind;

    pub trait PWGType<'a>: Sized {
        fn deserialize(buf: &'a [u8]) -> Result<Self, ErrorKind>;
    }

    // Marker for enums that should be represented as u32.
    // This is currently all of them.
    pub trait EnumU32: FromPrimitive {}

    impl<'a, T: EnumU32> PWGType<'a> for T {
        fn deserialize(buf: &'a [u8]) -> Result<Self, ErrorKind> {
            let val = BigEndian::read_u32(buf);
            Self::from_u32(val).ok_or(ErrorKind::BadEnumValue(val))
        }
    }

    // 4.3.1.1
    pub type Boolean = bool;

    impl<'a> PWGType<'a> for Boolean {
        fn deserialize(buf: &'a [u8]) -> Result<Self, ErrorKind> {
            let val = BigEndian::read_u32(buf);
            Ok(val != 0)
        }
    }

    // 4.3.1.2
    #[derive(Debug, PartialEq, Eq)]
    pub struct CString<'a>(pub &'a str);

    impl<'a> PWGType<'a> for CString<'a> {
        fn deserialize(buf: &'a [u8]) -> Result<Self, ErrorKind> {
            if let Some(end) = memchr(0, buf) {
                str::from_utf8(&buf[0..end])
                    .map(|s| CString(s))
                    .map_err(|_| ErrorKind::InvalidUTF8)
            } else {
                Err(ErrorKind::UnterminatedString)
            }
        }
    }

    #[test]
    fn test_cstring() {
        assert_eq!(CString::deserialize(b"abcd\0abcd").unwrap().0, "abcd")
    }

    // 4.3.1.3
    enum_from_primitive! {
    pub enum ColorOrder {
        // Chunky pixels, e.g. CMYK CMYK CMYK ...
        Chunky = 0,
    }
    }

    impl EnumU32 for ColorOrder {}

    // 4.3.1.4
    enum_from_primitive! {
    pub enum ColorSpace {
        // Device RGB (red green blue)
        Rgb = 1,
        // Device black
        Black = 3,
        // Device CMYK (cyan magenta yellow black)
        Cmyk = 6,
        // sRGB grayscale
        Sgray = 18,
        // sRGB color
        Srgb = 19,
        // Adobe RGB color
        AdobeRgb = 20,
        // Device color, 1 colorant
        Device1 = 48,
        // Device color, 2 colorants
        Device2 = 49,
        // Device color, 3 colorants
        Device3 = 50,
        // Device color, 4 colorants
        Device4 = 51,
        // Device color, 5 colorants
        Device5 = 52,
        // Device color, 6 colorants
        Device6 = 53,
        // Device color, 7 colorants
        Device7 = 54,
        // Device color, 8 colorants
        Device8 = 55,
        // Device color, 9 colorants
        Device9 = 56,
        // Device color, 10 colorants
        Device10 = 57,
        // Device color, 11 colorants
        Device11 = 58,
        // Device color, 12 colorants
        Device12 = 59,
        // Device color, 13 colorants
        Device13 = 60,
        // Device color, 14 colorants
        Device14 = 61,
        // Device color, 15 colorants
        Device15 = 62,
    }
    }

    impl EnumU32 for ColorSpace {}

    // 4.3.1.5
    enum_from_primitive! {
    pub enum Edge {
        // The short edge of the media is first.
        ShortEdgeFirst = 0,
        // The long edge of the media is first.
        LongEdgeFirst = 1,
    }
    }

    impl EnumU32 for Edge {}

    // 4.3.1.6
    pub type Integer = i32;

    impl<'a> PWGType<'a> for Integer {
        fn deserialize(buf: &'a [u8]) -> Result<Self, ErrorKind> {
            Ok(BigEndian::read_i32(buf))
        }
    }

    // 4.3.1.7
    enum_from_primitive! {
    pub enum MediaPosition {
        // Default or automatically selected source.
        Auto = 0,
        // The primary or main source.
        Main = 1,
        // The secondary or alternate source.
        Alternate = 2,
        // The large capacity source.
        LargeCapacity = 3,
        // The manual feed source.
        Manual = 4,
        // The envelope feed source.
        Envelope = 5,
        // The CD/DVD/Bluray disc source.
        Disc = 6,
        // The photo media source.
        Photo = 7,
        // The Hagaki media source.
        Hagaki = 8,
        // The primary or main roll.
        MainRoll = 9,
        // The secondary or alternate roll.
        AlternateRoll = 10,
        // The topmost source.
        Top = 11,
        // The middle source.
        Middle = 12,
        // The bottommost source.
        Bottom = 13,
        // The side source.
        Side = 14,
        // The leftmost source.
        Left = 15,
        // The rightmost source.
        Right = 16,
        // The center source.
        Center = 17,
        // The rear source.
        Rear = 18,
        // The by-pass or multi-purpose source.
        ByPassTray = 19,
        // Tray 1.
        Tray1 = 20,
        // Tray 2.
        Tray2 = 21,
        // Tray 3.
        Tray3 = 22,
        // Tray 4.
        Tray4 = 23,
        // Tray 5.
        Tray5 = 24,
        // Tray 6.
        Tray6 = 25,
        // Tray 7.
        Tray7 = 26,
        // Tray 8.
        Tray8 = 27,
        // Tray 9.
        Tray9 = 28,
        // Tray 10.
        Tray10 = 29,
        // Tray 11.
        Tray11 = 30,
        // Tray 12.
        Tray12 = 31,
        // Tray 13.
        Tray13 = 32,
        // Tray 14.
        Tray14 = 33,
        // Tray 15.
        Tray15 = 34,
        // Tray 16.
        Tray16 = 35,
        // Tray 17.
        Tray17 = 36,
        // Tray 18.
        Tray18 = 37,
        // Tray 19.
        Tray19 = 38,
        // Tray 20.
        Tray20 = 39,
        // Roll 1.
        Roll1 = 40,
        // Roll 2.
        Roll2 = 41,
        // Roll 3.
        Roll3 = 42,
        // Roll 4.
        Roll4 = 43,
        // Roll 5.
        Roll5 = 44,
        // Roll 6.
        Roll6 = 45,
        // Roll 7.
        Roll7 = 46,
        // Roll 8.
        Roll8 = 47,
        // Roll 9.
        Roll9 = 48,
        // Roll 10.
        Roll10 = 49,
    }
    }

    impl EnumU32 for MediaPosition {}

    // 4.3.1.8
    enum_from_primitive! {
    pub enum Orientation {
        //Not rotated
        Portrait = 0,
        // Rotated 90 degrees counter-clockwise
        Landscape = 1,
        // Rotated 180 degrees
        ReversePortrait = 2,
        // Rotated 90 degrees clockwise
        ReverseLandscape = 3,
    }
    }

    impl EnumU32 for Orientation {}

    // 4.3.1.9
    enum_from_primitive! {
    pub enum PrintQuality {
        // The default print quality.
        Default = 0,
        // Draft/fast print quality.
        Draft = 3,
        // Normal print quality.
        Normal = 4,
        // High/best/photo print quality.
        High = 5,
    }
    }

    impl EnumU32 for PrintQuality {}

    // 4.3.1.10
    pub struct Reserved;

    impl<'a> PWGType<'a> for Reserved {
        fn deserialize(buf: &'a [u8]) -> Result<Self, ErrorKind> {
            for byte in buf {
                if *byte != 0 {
                    return Err(ErrorKind::NonZeroReserved);
                }
            }
            Ok(Reserved)
        }
    }

    // 4.3.1.11
    pub struct SrgbColor(u32);

    impl SrgbColor {
        pub fn red(&self) -> u8 {
            (self.0 >> 16) as u8
        }

        pub fn green(&self) -> u8 {
            (self.0 >> 8) as u8
        }

        pub fn blue(&self) -> u8 {
            self.0 as u8
        }
    }

    impl<'a> PWGType<'a> for SrgbColor {
        fn deserialize(buf: &'a [u8]) -> Result<Self, ErrorKind> {
            let val = BigEndian::read_u32(buf);
            if (val & 0xff000000) != 0 {
                Err(ErrorKind::InvalidColor)
            } else {
                Ok(SrgbColor(val))
            }
        }
    }

    // 4.3.1.12
    pub type UnsignedInteger = u32;

    impl<'a> PWGType<'a> for UnsignedInteger {
        fn deserialize(buf: &'a [u8]) -> Result<Self, ErrorKind> {
            Ok(BigEndian::read_u32(buf))
        }
    }

    // 4.3.1.13
    pub struct VendorData<'a>(&'a [u8]);

    impl<'a> PWGType<'a> for VendorData<'a> {
        fn deserialize(buf: &'a [u8]) -> Result<Self, ErrorKind> {
            Ok(VendorData(buf))
        }
    }

    // 4.3.1.14
    enum_from_primitive! {
    pub enum When {
        // Never apply feature.
        Never = 0,
        // Apply feature after current document/file.
        AfterDocument = 1,
        // Apply feature after current job.
        AfterJob = 2,
        // Apply feature after current set/copy.
        AfterSet = 3,
        // Apply feature after current page.
        AfterPage = 4,
    }
    }

    impl EnumU32 for When {}

    // 4.3.2.1
    pub struct PwgRaster<'a>(pub CString<'a>);

    impl<'a> PWGType<'a> for PwgRaster<'a> {
        fn deserialize(buf: &'a [u8]) -> Result<Self, ErrorKind> {
            let s = CString::deserialize(buf)?;
            if s.0 == "PwgRaster" {
                Ok(PwgRaster(s))
            } else {
                Err(ErrorKind::BadPwgRasterString)
            }
        }
    }

    // 4.3.2.2
    pub struct HwResolution {
        pub feed_res_dpi: UnsignedInteger,
        pub cross_feed_res_dpi: UnsignedInteger,
    }

    impl<'a> PWGType<'a> for HwResolution {
        fn deserialize(buf: &'a [u8]) -> Result<Self, ErrorKind> {
            Ok(HwResolution {
                   feed_res_dpi: UnsignedInteger::deserialize(&buf[..4])?,
                   cross_feed_res_dpi: UnsignedInteger::deserialize(&buf[4..])?,
               })
        }
    }

    // 4.3.3.11
    pub struct PageSize {
        pub width: UnsignedInteger,
        pub height: UnsignedInteger,
    }

    impl<'a> PWGType<'a> for PageSize {
        fn deserialize(buf: &'a [u8]) -> Result<Self, ErrorKind> {
            Ok(PageSize {
                   width: UnsignedInteger::deserialize(&buf[..4])?,
                   height: UnsignedInteger::deserialize(&buf[4..])?,
               })
        }
    }
}

use types::*;

macro_rules! make_struct {
    ($(#[$attr:meta])* pub struct $name:ident {
            $(
                $start:expr, $end:expr, $fname:ident: $ftype:ident
            ),*
    } ) => {
        $(#[$attr])*
        pub struct $name<'a>(&'a [u8]);
        impl<'a> $name<'a> {
                #[inline]
                // Do the full length check to help optimize out subsequent checks
                // for fields within the struct
                fn checked_buf(&self) -> &[u8] {
                    &self.0[..PWG_HEADER_SIZE]
                }
            $(
                #[allow(non_snake_case)]
                #[inline]
                pub fn $fname(&self) -> Result<$ftype, Error> {
                    <$ftype as PWGType>::deserialize(&self.checked_buf()[$start..$end + 1])
                        .map_err(|e| {
                            Error {
                                field: stringify!($fname),
                                offset: $start,
                                err: e,
                            }
                        })
                }
             )*
                /// Attempt to unpack all values, calling a function to
                /// handle any errors as they are encountered.
                ///
                /// An error handler may choose to map the errors to a custom
                /// type or discard some types of errors.
                pub fn validate_filter<E, F: Fn(Error) -> Result<(), E>>(&self, err_handler: F) -> Result<(), E> {
                    $(
                        if let Err(e) = self.$fname() {
                            if let Err(e) = err_handler(e) {
                                return Err(e);
                            }
                        }
                     )*
                    Ok(())
                }
        }
    }
}

/// 4 bytes found at the beginning of PWG data
pub const PWG_SYNC_WORD: &'static [u8; 4] = b"RaS2";
/// Size of the fixed-length PWG header for each page
pub const PWG_HEADER_SIZE: usize = 1796;

make_struct! {
    /// Accessors into a slice containing a PWG page header
    pub struct PageHeader {
        0, 63, PwgRaster: PwgRaster,
        64, 127, MediaColor: CString,
        128, 191, MediaType: CString,
        192, 255, PrintContentOptimize: CString,
        256, 267, Reserved1: Reserved,
        268, 271, CutMedia: When,
        272, 275, Duplex: Boolean,
        276, 283, HWResolution: HwResolution,
        284, 299, Reserved2: Reserved,
        300, 303, InsertSheet: Boolean,
        304, 307, Jog: When,
        308, 311, LeadingEdge: Edge,
        312, 323, Reserved3: Reserved,
        324, 327, MediaPosition: MediaPosition,
        328, 331, MediaWeight: UnsignedInteger,
        332, 339, Reserved4: Reserved,
        340, 343, NumCopies: UnsignedInteger,
        344, 347, Orientation: Orientation,
        348, 351, Reserved5: Reserved,
        352, 359, PageSize: PageSize,
        360, 367, Reserved6: Reserved,
        368, 371, Tumble: Boolean,
        372, 375, Width: UnsignedInteger,
        376, 379, Height: UnsignedInteger,
        380, 383, Reserved7: Reserved,
        384, 387, BitsPerColor: UnsignedInteger,
        388, 391, BitsPerPixel: UnsignedInteger,
        392, 395, BytesPerLine: UnsignedInteger,
        396, 399, ColorOrder: ColorOrder,
        400, 403, ColorSpace: ColorSpace,
        404, 419, Reserved8: Reserved,
        420, 423, NumColors: UnsignedInteger,
        424, 451, Reserved9: Reserved,
        452, 455, TotalPageCount: UnsignedInteger,
        456, 459, CrossFeedTransform: Integer,
        460, 463, FeedTransform: Integer,
        464, 467, ImageBoxLeft: UnsignedInteger,
        468, 471, ImageBoxTop: UnsignedInteger,
        472, 475, ImageBoxRight: UnsignedInteger,
        476, 479, ImageBoxBottom: UnsignedInteger,
        480, 483, AlternatePrimary: SrgbColor,
        484, 487, PrintQuality: PrintQuality,
        488, 507, Reserved10: Reserved,
        508, 511, VendorIdentifier: UnsignedInteger,
        512, 515, VendorLength: UnsignedInteger,
        516, 1603, VendorData: VendorData,
        1604, 1667, Reserved11: Reserved,
        1668, 1731, RenderingIntent: CString,
        1732, 1795, PageSizeName: CString
    }
}

impl<'a> PageHeader<'a> {
    /// Construct over a borrowed buffer that starts at the beginning of the
    /// PWG header (after the sync word or a previous page).
    ///
    /// Does not copy the input or allocate.
    ///
    /// Returns None if the buffer is not at least PWG_HEADER_SIZE bytes. No
    /// input validation is performed at this step.
    #[inline]
    pub fn from_buf(buf: &'a [u8]) -> Option<Self> {
        if buf.len() >= PWG_HEADER_SIZE {
            Some(PageHeader(buf))
        } else {
            None
        }
    }

    /// Attempt to unpack all values, calling a function to
    /// handle any errors as they are encountered.
    ///
    /// This ignores reserved fields but returns the first error encountered in
    /// other fields.
    pub fn validate(&self) -> Result<(), Error> {
        self.validate_filter(|e| match e {
                                 Error { err: ErrorKind::NonZeroReserved, .. } => Ok(()),
                                 _ => Err(e),
                             })
    }

    /// Attempt to unpack all values, calling a function to
    /// handle any errors as they are encountered.
    ///
    /// Warning! This validates that reserved fields are set to 0 so code using
    /// this may not be future-proof.
    pub fn validate_withreserved(&self) -> Result<(), Error> {
        self.validate_filter(|e| Err(e))
    }

    /// Return the image's smallest unit of pixel values in bytes. This is the
    /// bpp of the image or 1 in the case of packed 1-bit pixels.
    fn chunk_bytes(&self) -> Result<usize, StreamError> {
        match self.BitsPerPixel()? {
            // 1bpp is packed into bytes
            1 => Ok(1),
            // Else divide bpp by 8
            bpp if bpp % 8 == 0 => Ok(bpp as usize / 8),
            _ => Err(StreamError::UnsupportedBpp),
        }
    }

    /// The size of an unpacked line.
    ///
    /// 1 bpp data will remain packed 8 pixel in a byte. Pixels are packed into
    /// a stream of bytes, i.e. 2 24bpp pixels are represented as 6 contiguous
    /// bytes.
    pub fn bytes_per_line(&self) -> Result<usize, Error> {
        Ok((self.Width()? as usize * self.BitsPerPixel()? as usize + 7) / 8)
    }

    /// The size of the unpacked image data in bytes. bytes_per_line * height.
    ///
    /// 1 bpp data will remain packed 8 pixel in a byte. Pixels are packed into
    /// a stream of bytes, i.e. 2 24bpp pixels are represented as 6 contiguous
    /// bytes.
    pub fn image_size_bytes(&self) -> Result<usize, Error> {
        Ok(self.bytes_per_line()? * self.Height()? as usize)
    }

    pub fn unpack_page<R: Read, W: Write>(&self,
                                          reader: &mut R,
                                          writer: &mut W)
                                          -> Result<(), StreamError> {
        let chunk_bytes = self.chunk_bytes()?;
        let bytes_per_line = self.bytes_per_line()?;
        let height = self.Height()? as usize;

        unpack_page(reader, writer, chunk_bytes, bytes_per_line, height)
    }
}

/// Stream PWG image data from a reader to a writer
///
/// The reader must point to the image data found immediately after the header.
pub fn unpack_page<R: Read, W: Write>(reader: &mut R,
                                      writer: &mut W,
                                      chunk_bytes: usize,
                                      bytes_per_line: usize,
                                      height: usize)
                                      -> Result<(), StreamError> {
    let mut pixel_buf = Vec::with_capacity(chunk_bytes);
    pixel_buf.resize(chunk_bytes, 0);
    let mut line_buf = Vec::with_capacity(bytes_per_line);
    line_buf.resize(bytes_per_line, 0);

    let mut lines_complete = 0;
    while lines_complete < height {
        let line_repeat = reader.read_u8()? as usize + 1;
        let mut line_bytes = 0;

        if (lines_complete + line_repeat) > height {
            return Err(StreamError::HeightOverflow);
        }

        while line_bytes < bytes_per_line {
            let count = reader.read_u8()?;
            if count < 128 {
                let repeat_count = count + 1;
                reader.read_exact(&mut pixel_buf[..])?;

                let repeat_length = pixel_buf.len() * repeat_count as usize;
                if (bytes_per_line - line_bytes) < repeat_length {
                    return Err(StreamError::LineOverflow);
                }

                for _ in 0..repeat_count {
                    line_buf[line_bytes..line_bytes + pixel_buf.len()]
                        .clone_from_slice(&pixel_buf[..]);
                    line_bytes += pixel_buf.len();
                }
            } else {
                let count = 257 - count as usize;
                let byte_count = count * pixel_buf.len();

                if (bytes_per_line - line_bytes) < byte_count {
                    return Err(StreamError::LineOverflow);
                }
                reader
                    .read_exact(&mut line_buf[line_bytes..line_bytes + byte_count])?;
                line_bytes += byte_count;
            }
        }

        for _ in 0..line_repeat {
            writer.write_all(&line_buf[..])?;
            lines_complete += 1;
        }
    }
    Ok(())
}

#[test]
fn test_unpack() {
    use std::io::Cursor;
    let mut buf = [0, 0xfd, 1, 2, 3, 0];
    let mut outbuf = [0; 4];

    unpack_page(&mut Cursor::new(&buf[..]),
                &mut Cursor::new(&mut outbuf[..]),
                1,
                4,
                1)
            .unwrap();
    assert_eq!(outbuf, [1, 2, 3, 0]);
    let e = unpack_page(&mut Cursor::new(&buf[..]),
                        &mut Cursor::new(&mut outbuf[..3]),
                        1,
                        4,
                        1);
    if let Err(StreamError::IO(e)) = e {
        assert_eq!(e.kind(), io::ErrorKind::WriteZero);
    } else {
        panic!("{:?}", e);
    }
    let e = unpack_page(&mut Cursor::new(&buf[..4]),
                        &mut Cursor::new(&mut outbuf[..]),
                        1,
                        4,
                        1);
    if let Err(StreamError::IO(e)) = e {
        assert_eq!(e.kind(), io::ErrorKind::UnexpectedEof);
    } else {
        panic!("{:?}", e);
    }

    match unpack_page(&mut Cursor::new(&buf[..]),
                      &mut Cursor::new(&mut outbuf[..]),
                      1,
                      3,
                      1) {
        Err(StreamError::LineOverflow) => (),
        e => panic!("{:?}", e),
    }

    // Set line repeat
    buf[0] = 1;
    match unpack_page(&mut Cursor::new(&buf[..]),
                      &mut Cursor::new(&mut outbuf[..]),
                      1,
                      4,
                      1) {
        Err(StreamError::HeightOverflow) => (),
        e => panic!("{:?}", e),
    }
}

/// Top-level structure over a reader that returns decoded pages
pub struct PWGReader<R: Read> {
    reader: R,
    header_buf: [u8; PWG_HEADER_SIZE],
    page_read: bool,
}

impl<R: Read> PWGReader<R> {
    /// Construct a PWGReader over a byte reader
    ///
    /// If syncword is true, read and validate the initial sync word that comes
    /// before the first page header. If false, the reader should point to a
    /// page header.
    pub fn new(mut reader: R, syncword: bool) -> Result<Self, StreamError> {
        if syncword {
            let mut sync = [0; 4];
            reader.read_exact(&mut sync[..])?;
            if &sync != PWG_SYNC_WORD {
                return Err(StreamError::BadSyncWord);
            }
        }

        Ok(PWGReader {
               reader: reader,
               header_buf: [0; PWG_HEADER_SIZE],
               page_read: false,
           })
    }

    /// Return the reader
    pub fn into_inner(self) -> R {
        self.reader
    }

    /// Invoke a closure on the next page. The closure is passed a page
    /// structure which can return the header and unpack the page data.
    pub fn next_page<T, F: Fn(PWGPage<R>) -> Result<T, StreamError>>
        (&mut self,
         f: F)
         -> Result<Option<T>, StreamError> {
        struct NullWriter;

        impl Write for NullWriter {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                Ok(buf.len())
            }

            fn flush(&mut self) -> io::Result<()> {
                Ok(())
            }
        }

        // This is like read_exact() but returns Ok(None) if we read exactly 0.
        let mut header_bytes = 0;
        while header_bytes < self.header_buf.len() {
            match self.reader.read(&mut self.header_buf[header_bytes..]) {
                Ok(len) if len == 0 => {
                    if header_bytes == 0 {
                        // Reached the end at the start of the next header, so
                        // there aren't any more pages.
                        return Ok(None);
                    } else {
                        // It might be a problem if we get EOF in the middle of
                        // a header.
                        return Err(io::Error::from(io::ErrorKind::UnexpectedEof).into());
                    }
                }
                Ok(len) => header_bytes += len,
                Err(e) => {
                    if e.kind() == io::ErrorKind::Interrupted {
                        continue;
                    } else {
                        // EOF during a header or any other error. Raise the error.
                        return Err(e.into());
                    }
                }
            }
        }

        self.page_read = false;
        let ret = f(PWGPage(self))?;
        if !self.page_read {
            // Need to flush the page data if the client didn't read it so the
            // reader is pointing at the next header.
            PWGPage(self).unpack(&mut NullWriter)?;
        }
        Ok(Some(ret))
    }
}

/// Returned by PWGReader::next_page(). Allows access to the page header and image data.
pub struct PWGPage<'a, R: Read + 'a>(&'a mut PWGReader<R>);

impl<'a, R: Read + 'a> PWGPage<'a, R> {
    /// Get the page's header
    pub fn header(&'a self) -> PageHeader<'a> {
        // Unwrap is safe because we know the size of our buffer
        PageHeader::from_buf(&self.0.header_buf).unwrap()
    }

    /// Unpack PWG image data to a writer. This consumes the page.
    pub fn unpack<W: Write>(self, writer: &mut W) -> Result<(), StreamError> {
        self.0.page_read = true;
        // Unwrap is safe because we know the size of our buffer
        let header = PageHeader::from_buf(&self.0.header_buf).unwrap();
        header.unpack_page(&mut self.0.reader, writer)
    }
}