gift 0.12.0

A library for reading and writing GIF images
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
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
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
// block.rs
//
// Copyright (c) 2019-2025  Douglas Lau
//
//! A GIF file consists of a sequence of [Block](enum.Block.html)s in a
//! specific order.
//!
//! With some minor exceptions, the order is thus:
//!
//! * [Header](struct.Header.html)
//! * [LogicalScreenDesc](struct.LogicalScreenDesc.html)
//! * [GlobalColorTable](struct.GlobalColorTable.html) *(optional)*
//! * [Application](struct.Application.html) - animation loop count *(optional)*
//! * [Comment](struct.Comment.html) *(optional)*
//! * Sequence of [Frame](struct.Frame.html)s, which are:
//!   - [GraphicControl](struct.GraphicControl.html) *(optional)*
//!   - [ImageDesc](struct.ImageDesc.html)
//!   - [LocalColorTable](struct.LocalColorTable.html) *(optional)*
//!   - [ImageData](struct.ImageData.html)
//! * [Trailer](struct.Trailer.html)
//!
use pix::{Raster, Region, gray::Gray8};

/// Number of channels in color tables (red, green and blue)
const CHANNELS: usize = 3;

/// Configuration setting indicating the presence or absence of a color table
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ColorTableExistence {
    /// Color table is absent
    Absent,
    /// Color table is present
    Present,
}

/// Configuration setting indicating whether the color table is ordered
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ColorTableOrdering {
    /// Color table not sorted
    NotSorted,
    /// Color table sorted by decreasing importance
    Sorted,
}

/// A color table configuration defines the size and ordering of a color table.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ColorTableConfig {
    /// Does the table exist?
    existence: ColorTableExistence,
    /// Is the table sorted?
    ordering: ColorTableOrdering,
    /// Number of entries; must be between 2..=256
    table_len: usize,
}

impl Default for ColorTableConfig {
    fn default() -> Self {
        let existence = ColorTableExistence::Absent;
        let ordering = ColorTableOrdering::NotSorted;
        let table_len = 2;
        ColorTableConfig {
            existence,
            ordering,
            table_len,
        }
    }
}

impl ColorTableConfig {
    /// Create a new color table configuration
    pub fn new(
        existence: ColorTableExistence,
        ordering: ColorTableOrdering,
        table_len: u16,
    ) -> Self {
        let table_len =
            (table_len as usize).max(2).next_power_of_two().min(256);
        ColorTableConfig {
            existence,
            ordering,
            table_len,
        }
    }

    /// Get the existence of a color table
    pub fn existence(&self) -> ColorTableExistence {
        self.existence
    }

    /// Get the ordering of a color table
    pub fn ordering(&self) -> ColorTableOrdering {
        self.ordering
    }

    /// Get the length of a color table (number of entries)
    pub fn len(&self) -> usize {
        match self.existence {
            ColorTableExistence::Absent => 0,
            ColorTableExistence::Present => self.table_len,
        }
    }

    /// Check if the table is empty
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Get the length code (in flag bits)
    fn len_bits(&self) -> u8 {
        let sz = self.table_len;
        for b in 0..7 {
            if (sz >> (b + 1)) == 1 {
                return b;
            }
        }
        7
    }

    /// Get the size of the color table (in bytes)
    pub fn size_bytes(&self) -> usize {
        self.len() * CHANNELS
    }
}

/// Method to dispose of a frame in an animation
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum DisposalMethod {
    /// No disposal specified
    #[default]
    NoAction,
    /// Do not dispose of frame
    Keep,
    /// Restore to background color
    Background,
    /// Restore to previous frame
    Previous,
    /// Reserved methods
    Reserved(u8),
}

impl From<u8> for DisposalMethod {
    fn from(n: u8) -> Self {
        use self::DisposalMethod::*;
        match n & 0b0111 {
            0 => NoAction,
            1 => Keep,
            2 => Background,
            3 => Previous,
            _ => Reserved(n),
        }
    }
}

impl From<DisposalMethod> for u8 {
    fn from(d: DisposalMethod) -> Self {
        use self::DisposalMethod::*;
        match d {
            NoAction => 0,
            Keep => 1,
            Background => 2,
            Previous => 3,
            Reserved(n) => n & 0b0111,
        }
    }
}

/// Codes for each type of block
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum BlockCode {
    /// Header block code (signature / magic)
    Header_,
    /// Logical screen descriptor block code
    LogicalScreenDesc_,
    /// Global color table block code
    GlobalColorTable_,
    /// Extension block code
    Extension_,
    /// Image descriptor block code
    ImageDesc_,
    /// Local color table block code
    LocalColorTable_,
    /// Image data block code
    ImageData_,
    /// Image trailer block code
    Trailer_,
}

impl BlockCode {
    /// Get block code from a separator / introducer byte.
    pub fn from_u8(t: u8) -> Option<Self> {
        use self::BlockCode::*;
        match t {
            b',' => Some(ImageDesc_), // (0x2C) Image separator
            b'!' => Some(Extension_), // (0x21) Extension introducer
            b';' => Some(Trailer_),   // (0x3B) GIF trailer
            _ => None,
        }
    }

    /// Get the block signature (if any).
    pub fn signature(self) -> &'static [u8] {
        use self::BlockCode::*;
        match self {
            ImageDesc_ => b",", // (0x2C) Image separator
            Extension_ => b"!", // (0x21) Extension introducer
            Trailer_ => b";",   // (0x3B) GIF trailer
            _ => &[],
        }
    }

    /// Get the block size in bytes
    pub fn size(self) -> usize {
        use self::BlockCode::*;
        match self {
            Header_ => 6,
            LogicalScreenDesc_ => 7,
            ImageDesc_ => 10,
            Trailer_ => 1,
            Extension_ => 2, // +sub-blocks
            ImageData_ => 1, // +sub-blocks
            _ => 0,
        }
    }
}

/// Extension block codes
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum ExtensionCode {
    /// Plain text extension code
    PlainText_,
    /// Graphic control extension code
    GraphicControl_,
    /// Comment extension code
    Comment_,
    /// Application extension code
    Application_,
    /// Unknown extension code
    Unknown_(u8),
}

impl From<u8> for ExtensionCode {
    fn from(n: u8) -> Self {
        use self::ExtensionCode::*;
        match n {
            0x01 => PlainText_,
            0xF9 => GraphicControl_,
            0xFE => Comment_,
            0xFF => Application_,
            _ => Unknown_(n),
        }
    }
}

impl From<ExtensionCode> for u8 {
    fn from(t: ExtensionCode) -> Self {
        use self::ExtensionCode::*;
        match t {
            PlainText_ => 0x01,
            GraphicControl_ => 0xF9,
            Comment_ => 0xFE,
            Application_ => 0xFF,
            Unknown_(n) => n,
        }
    }
}

/// The header contains the
/// [magic](https://en.wikipedia.org/wiki/File_format#Magic_number)
/// string "GIF", followed by a version number.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Header {
    version: [u8; 3],
}

impl Default for Header {
    fn default() -> Self {
        let version = *b"89a";
        Header { version }
    }
}

impl Header {
    /// Create a header block with a specific GIF version
    pub fn with_version(version: [u8; 3]) -> Self {
        Header { version }
    }

    /// Get the GIF version
    pub fn version(self) -> [u8; 3] {
        self.version
    }
}

/// The logical screen descriptor contains properties which apply to all frames
/// in the file.
///
/// ```
/// use gift::block::{
///     ColorTableConfig, ColorTableExistence, ColorTableOrdering,
///     LogicalScreenDesc
/// };
///
/// let desc = LogicalScreenDesc::default()
///     .with_screen_width(64)
///     .with_screen_height(64)
///     .with_color_table_config(ColorTableConfig::new(
///         ColorTableExistence::Present,
///         ColorTableOrdering::NotSorted,
///         16,
///     ))
///     .with_background_color_idx(1);
/// ```
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct LogicalScreenDesc {
    /// Pixel width of logical screen
    screen_width: u16,
    /// Pixel height of logical screen
    screen_height: u16,
    /// Bit flags for color table
    flags: u8,
    /// Index into global color table for background color
    background_color_idx: u8,
    /// Pixel aspect ratio is an obsolete GIF feature
    pixel_aspect_ratio: u8,
}

impl LogicalScreenDesc {
    const COLOR_TABLE_PRESENT: u8 = 0b1000_0000;
    const COLOR_RESOLUTION: u8 = 0b0111_0000;
    const COLOR_TABLE_ORDERING: u8 = 0b0000_1000;
    const COLOR_TABLE_SIZE: u8 = 0b0000_0111;

    /// Set the screen width
    pub fn with_screen_width(mut self, screen_width: u16) -> Self {
        self.screen_width = screen_width;
        self
    }

    /// Get the screen width
    pub fn screen_width(self) -> u16 {
        self.screen_width
    }

    /// Set the screen height
    pub fn with_screen_height(mut self, screen_height: u16) -> Self {
        self.screen_height = screen_height;
        self
    }

    /// Get the screen height
    pub fn screen_height(self) -> u16 {
        self.screen_height
    }

    /// Check if screen sizes are equal
    pub fn equal_size(self, rhs: Self) -> bool {
        self.screen_width == rhs.screen_width
            && self.screen_height == rhs.screen_height
    }

    /// Set the flags which control the global color table configuration.
    ///
    /// It is recommended to use [with_color_table_config] instead.
    ///
    /// [with_color_table_config]: struct.LogicalScreenDesc.html#method.with_color_table_config
    pub fn with_flags(mut self, flags: u8) -> Self {
        self.flags = flags;
        self
    }

    /// Get the flags which control the global color table configuration
    pub fn flags(self) -> u8 {
        self.flags
    }

    /// Check the descriptor for global color table existence
    fn color_table_existence(self) -> ColorTableExistence {
        if self.flags & Self::COLOR_TABLE_PRESENT != 0 {
            ColorTableExistence::Present
        } else {
            ColorTableExistence::Absent
        }
    }

    /// Get the color resolution (obsolete GIF feature)
    pub fn color_resolution(self) -> u16 {
        2 << ((self.flags & Self::COLOR_RESOLUTION) >> 4_u16)
    }

    /// Check the descriptor for global color table ordering
    fn color_table_ordering(self) -> ColorTableOrdering {
        if self.flags & Self::COLOR_TABLE_ORDERING != 0 {
            ColorTableOrdering::Sorted
        } else {
            ColorTableOrdering::NotSorted
        }
    }

    /// Check the descriptor for global color table length
    fn color_table_len(self) -> usize {
        2 << ((self.flags & Self::COLOR_TABLE_SIZE) as usize)
    }

    /// Get the global color table configuration
    pub fn color_table_config(self) -> ColorTableConfig {
        let existence = self.color_table_existence();
        let ordering = self.color_table_ordering();
        let table_len = self.color_table_len();
        ColorTableConfig {
            existence,
            ordering,
            table_len,
        }
    }

    /// Set the global color table configuration
    pub fn with_color_table_config(mut self, tbl: ColorTableConfig) -> Self {
        let mut flags = tbl.len_bits() & Self::COLOR_TABLE_SIZE;
        flags |= (flags << 4) & Self::COLOR_RESOLUTION;
        if tbl.existence == ColorTableExistence::Present {
            flags |= Self::COLOR_TABLE_PRESENT;
        }
        if tbl.ordering == ColorTableOrdering::Sorted {
            flags |= Self::COLOR_TABLE_ORDERING;
        }
        self.flags = flags;
        self
    }

    /// Set the background color index
    pub fn with_background_color_idx(
        mut self,
        background_color_idx: u8,
    ) -> Self {
        self.background_color_idx = background_color_idx;
        self
    }

    /// Get the background color index
    pub fn background_color_idx(self) -> u8 {
        self.background_color_idx
    }

    /// Set the pixel aspect ratio (obsolete GIF feature)
    pub fn with_pixel_aspect_ratio(mut self, pixel_aspect_ratio: u8) -> Self {
        self.pixel_aspect_ratio = pixel_aspect_ratio;
        self
    }

    /// Get the pixel aspect ratio (obsolete GIF feature)
    pub fn pixel_aspect_ratio(self) -> u8 {
        self.pixel_aspect_ratio
    }
}

/// The global color table, if present, is used for all frames which do not
/// define a [LocalColorTable](struct.LocalColorTable.html).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GlobalColorTable {
    colors: Vec<u8>,
}

impl GlobalColorTable {
    /// Create a global color table with specified colors
    ///
    /// # Panics
    ///
    /// Panics if the length of `colors` is not divisible by 3, the number of
    /// color channels.
    pub fn with_colors(colors: &[u8]) -> Self {
        assert_eq!(colors.len() / CHANNELS * CHANNELS, colors.len());
        let colors = colors.to_vec();
        GlobalColorTable { colors }
    }

    /// Get the global color table length (number of entries)
    pub fn len(&self) -> usize {
        self.colors.len() / CHANNELS
    }

    /// Check if the table is empty
    pub fn is_empty(&self) -> bool {
        self.colors.is_empty()
    }

    /// Get the color table data
    pub fn colors(&self) -> &[u8] {
        &self.colors
    }
}

/// The plain text extension block is an obsolete GIF feature.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct PlainText {
    /// Sequence of sub-blocks
    sub_blocks: Vec<Vec<u8>>,
}

impl PlainText {
    /// Add a sub block
    ///
    /// # Panics
    ///
    /// Panics if `b` is empty or longer than 255 bytes.
    pub fn add_sub_block(&mut self, b: &[u8]) {
        assert!(!b.is_empty() && b.len() < 256);
        self.sub_blocks.push(b.to_vec());
    }

    /// Get the sub blocks
    pub fn sub_blocks(&self) -> &Vec<Vec<u8>> {
        &self.sub_blocks
    }
}

/// The graphic control extension block contains animation parameters for one
/// frame.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct GraphicControl {
    /// Bit flags
    flags: u8,
    /// Delay in centiseconds (hundredths of a second)
    delay_time_cs: u16,
    /// Index into global color table for transparent color
    transparent_color_idx: u8,
}

impl GraphicControl {
    #[allow(dead_code)]
    const RESERVED: u8 = 0b1110_0000;
    const DISPOSAL_METHOD: u8 = 0b0001_1100;
    const USER_INPUT: u8 = 0b0000_0010;
    const TRANSPARENT_COLOR: u8 = 0b0000_0001;

    /// Set the graphic control flags
    pub fn set_flags(&mut self, flags: u8) {
        self.flags = flags;
    }

    /// Get the graphic control flags
    pub fn flags(self) -> u8 {
        self.flags
    }

    /// Get the frame disposal method
    pub fn disposal_method(self) -> DisposalMethod {
        ((self.flags & Self::DISPOSAL_METHOD) >> 2).into()
    }

    /// Set the frame disposal method
    pub fn set_disposal_method(&mut self, disposal_method: DisposalMethod) {
        let d: u8 = disposal_method.into();
        self.flags = (self.flags & !Self::DISPOSAL_METHOD) | (d << 2);
    }

    /// Get the user input flag
    pub fn user_input(self) -> bool {
        (self.flags & Self::USER_INPUT) != 0
    }

    /// Set the user input flag
    pub fn set_user_input(&mut self, user_input: bool) {
        let u = (user_input as u8) << 1;
        self.flags = (self.flags & !Self::USER_INPUT) | u;
    }

    /// Get the frame delay time (centiseconds)
    pub fn delay_time_cs(self) -> u16 {
        self.delay_time_cs
    }

    /// Set the frame delay time (centiseconds)
    pub fn set_delay_time_cs(&mut self, delay_time_cs: u16) {
        self.delay_time_cs = delay_time_cs;
    }

    /// Get the transparent color, if any
    pub fn transparent_color(self) -> Option<u8> {
        let t = (self.flags & Self::TRANSPARENT_COLOR) != 0;
        if t {
            Some(self.transparent_color_idx)
        } else {
            None
        }
    }

    /// Get the transparent color index
    pub fn transparent_color_idx(self) -> u8 {
        self.transparent_color_idx
    }

    /// Set the transparent color index
    pub fn set_transparent_color_idx(&mut self, transparent_color_idx: u8) {
        self.transparent_color_idx = transparent_color_idx;
    }

    /// Set the transparent color
    pub fn set_transparent_color(&mut self, transparent_color: Option<u8>) {
        match transparent_color {
            Some(t) => {
                self.flags |= Self::TRANSPARENT_COLOR;
                self.transparent_color_idx = t;
            }
            None => {
                self.flags &= !Self::TRANSPARENT_COLOR;
                self.transparent_color_idx = 0;
            }
        }
    }
}

/// A comment extension block contains unstructured file metadata.
///
/// The specification recommends using the ASCII encoding.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Comment {
    /// Vec of comments
    comments: Vec<Vec<u8>>,
}

impl Comment {
    /// Add a comment
    ///
    /// # Panics
    ///
    /// Panics if `b` is empty or longer than 255 bytes.
    pub fn add_comment(&mut self, b: &[u8]) {
        assert!(!b.is_empty() && b.len() < 256);
        self.comments.push(b.to_vec());
    }

    /// Get the comments
    pub fn comments(&self) -> &Vec<Vec<u8>> {
        &self.comments
    }
}

/// The application extension block is typically only used to enable looping
/// animation.  Other uses are ignored by most GIF readers.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Application {
    /// Sequence of sub-blocks
    app_data: Vec<Vec<u8>>,
}

impl Application {
    /// Check if the block indicates animation looping
    fn is_looping(app_id: &[u8]) -> bool {
        app_id == b"NETSCAPE2.0" || app_id == b"ANIMEXTS1.0"
    }

    /// Create a new application block with specified loop count.
    ///
    /// Use zero to loop forever.
    pub fn with_loop_count(loop_count: u16) -> Self {
        let param0 = b"NETSCAPE2.0".to_vec();
        let param1 = vec![1, (loop_count >> 8) as u8, loop_count as u8];
        let app_data = vec![param0, param1];
        Application { app_data }
    }

    /// Add application data
    ///
    /// # Panics
    ///
    /// Panics if `b` is empty or longer than 255 bytes.
    pub fn add_app_data(&mut self, b: &[u8]) {
        assert!(!b.is_empty() && b.len() < 256);
        self.app_data.push(b.to_vec());
    }

    /// Get the application data
    pub fn app_data(&self) -> &Vec<Vec<u8>> {
        &self.app_data
    }

    /// Get the loop count, if applicable.
    ///
    /// Loop count is the number of times to repeat animation.  Some(0) means
    /// to loop forever.
    pub fn loop_count(&self) -> Option<u16> {
        // NOTE: this block must follow immediately after GlobalColorTable
        //       (or LogicalScreenDesc if there is no GlobalColorTable).
        let d = &self.app_data;
        let exists = d.len() == 2 &&            // 2 sub-blocks
                     Self::is_looping(&d[0]) && // app ID / auth code
                     d[1].len() == 3 &&         // app data sub-block length
                     d[1][0] == 1; // sub-block ID
        if exists {
            Some((u16::from(d[1][1]) << 8) | u16::from(d[1][2]))
        } else {
            None
        }
    }
}

/// Unknown extension blocks should not exist, but might be generated
/// by non-standard encoders.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Unknown {
    /// Sequence of sub-blocks (first has ext_id)
    sub_blocks: Vec<Vec<u8>>,
}

impl Unknown {
    /// Get the extension ID
    pub fn ext_id(&self) -> &[u8] {
        if self.sub_blocks.is_empty() {
            &[]
        } else {
            &self.sub_blocks[0]
        }
    }

    /// Add a sub-block
    ///
    /// # Panics
    ///
    /// Panics if `b` is empty or longer than 255 bytes.
    pub fn add_sub_block(&mut self, b: &[u8]) {
        assert!(!b.is_empty() && b.len() < 256);
        self.sub_blocks.push(b.to_vec());
    }

    /// Get the sub-blocks
    pub fn sub_blocks(&self) -> &[Vec<u8>] {
        if self.sub_blocks.is_empty() {
            &[]
        } else {
            &self.sub_blocks[1..]
        }
    }
}

/// The image descriptor block contains properties which apply to one frame.
///
/// ```
/// use gift::block::{
///     ColorTableConfig, ColorTableExistence, ColorTableOrdering, ImageDesc,
/// };
///
/// let desc = ImageDesc::default()
///     .with_width(64)
///     .with_height(64)
///     .with_color_table_config(ColorTableConfig::new(
///         ColorTableExistence::Present,
///         ColorTableOrdering::NotSorted,
///         16,
///     ));
/// ```
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct ImageDesc {
    /// Left position relative to logical screen
    left: u16,
    /// Top position relative to logical screen
    top: u16,
    /// Pixel width
    width: u16,
    /// Pixel height
    height: u16,
    /// Bit flags
    flags: u8,
}

impl ImageDesc {
    const COLOR_TABLE_PRESENT: u8 = 0b1000_0000;
    const INTERLACED: u8 = 0b0100_0000;
    const COLOR_TABLE_ORDERING: u8 = 0b0010_0000;
    #[allow(dead_code)]
    const RESERVED: u8 = 0b0001_1000;
    const COLOR_TABLE_SIZE: u8 = 0b0000_0111;

    /// Set the left position
    pub fn with_left(mut self, left: u16) -> Self {
        self.left = left;
        self
    }

    /// Get the left position
    pub fn left(&self) -> u16 {
        self.left
    }

    /// Set the top position
    pub fn with_top(mut self, top: u16) -> Self {
        self.top = top;
        self
    }

    /// Get the top position
    pub fn top(&self) -> u16 {
        self.top
    }

    /// Set the width
    pub fn with_width(mut self, width: u16) -> Self {
        self.width = width;
        self
    }

    /// Get the width
    pub fn width(&self) -> u16 {
        self.width
    }

    /// Set the height
    pub fn with_height(mut self, height: u16) -> Self {
        self.height = height;
        self
    }

    /// Get the height
    pub fn height(&self) -> u16 {
        self.height
    }

    /// Set the flags which control the interlace value and the local color
    /// table configuration.
    ///
    /// It is recommended to use [with_interlaced] or [with_color_table_config]
    /// instead.
    ///
    /// [with_color_table_config]: struct.ImageDesc.html#method.with_color_table_config
    /// [with_interlaced]: struct.ImageDesc.html#method.with_interlaced
    pub fn with_flags(mut self, flags: u8) -> Self {
        self.flags = flags;
        self
    }

    /// Get the flags which control the interlace value and the local color
    /// table configuration.
    pub fn flags(&self) -> u8 {
        self.flags
    }

    /// Set the interlaced flag
    pub fn with_interlaced(mut self, interlaced: bool) -> Self {
        self.flags = if interlaced {
            self.flags | Self::INTERLACED
        } else {
            self.flags & !Self::INTERLACED
        };
        self
    }

    /// Get the interlaced flag
    pub fn interlaced(&self) -> bool {
        (self.flags & Self::INTERLACED) != 0
    }

    /// Check the descriptor for local color table existence
    fn color_table_existence(&self) -> ColorTableExistence {
        if self.flags & Self::COLOR_TABLE_PRESENT != 0 {
            ColorTableExistence::Present
        } else {
            ColorTableExistence::Absent
        }
    }

    /// Check the descriptor for local color table ordering
    fn color_table_ordering(&self) -> ColorTableOrdering {
        if self.flags & Self::COLOR_TABLE_ORDERING != 0 {
            ColorTableOrdering::Sorted
        } else {
            ColorTableOrdering::NotSorted
        }
    }

    /// Check the descriptor for local color table length
    fn color_table_len(&self) -> usize {
        2 << u16::from(self.flags & Self::COLOR_TABLE_SIZE)
    }

    /// Get the local color table configuration
    pub fn color_table_config(&self) -> ColorTableConfig {
        let existence = self.color_table_existence();
        let ordering = self.color_table_ordering();
        let table_len = self.color_table_len();
        ColorTableConfig {
            existence,
            ordering,
            table_len,
        }
    }

    /// Set the local color table configuration
    pub fn with_color_table_config(mut self, tbl: ColorTableConfig) -> Self {
        let mut flags = self.flags & (Self::INTERLACED | Self::RESERVED);
        flags |= tbl.len_bits() & Self::COLOR_TABLE_SIZE;
        if tbl.existence == ColorTableExistence::Present {
            flags |= Self::COLOR_TABLE_PRESENT;
        }
        if tbl.ordering == ColorTableOrdering::Sorted {
            flags |= Self::COLOR_TABLE_ORDERING;
        }
        self.flags = flags;
        self
    }

    /// Get the image size (bytes)
    pub fn image_sz(&self) -> usize {
        self.width as usize * self.height as usize
    }
}

/// The local color table, if present, must immediately
/// follow an image descriptor block.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LocalColorTable {
    /// Colors in table
    colors: Vec<u8>,
}

impl LocalColorTable {
    /// Create a local color table with specified colors
    ///
    /// # Panics
    ///
    /// Panics if the length of `colors` is not divisible by 3, the number of
    /// color channels.
    pub fn with_colors(colors: &[u8]) -> Self {
        assert_eq!(colors.len() / CHANNELS * CHANNELS, colors.len());
        let colors = colors.to_vec();
        LocalColorTable { colors }
    }

    /// Get the local color table length (number of entries)
    pub fn len(&self) -> usize {
        self.colors.len() / CHANNELS
    }

    /// Check if the table is empty
    pub fn is_empty(&self) -> bool {
        self.colors.is_empty()
    }

    /// Get the color table data
    pub fn colors(&self) -> &[u8] {
        &self.colors
    }
}

/// An image data block contains image data for one frame.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ImageData {
    /// Image data in uncompressed form.
    data: Vec<u8>,
}

impl From<&Raster<Gray8>> for ImageData {
    fn from(raster: &Raster<Gray8>) -> Self {
        let buf = raster.as_u8_slice();
        let mut image_data = ImageData::new(buf.len());
        image_data.data_mut().extend_from_slice(buf);
        image_data
    }
}

impl ImageData {
    /// Create a new image data block
    pub fn new(image_sz: usize) -> Self {
        let data = Vec::with_capacity(image_sz);
        ImageData { data }
    }

    /// Get the image data
    pub fn data(&self) -> &[u8] {
        &self.data
    }

    /// Get a mutable reference to the image data
    pub fn data_mut(&mut self) -> &mut Vec<u8> {
        &mut self.data
    }
}

/// The trailer block indicates the end of a GIF file.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct Trailer {}

/// A block within a GIF file.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Block {
    /// Header block
    Header(Header),
    /// Logical screen descriptor block
    LogicalScreenDesc(LogicalScreenDesc),
    /// Global color table block
    GlobalColorTable(GlobalColorTable),
    /// Plain text extension block
    PlainText(PlainText),
    /// Graphics control extension block
    GraphicControl(GraphicControl),
    /// Comment extension block
    Comment(Comment),
    /// Application extension block
    Application(Application),
    /// Unknown extension block
    Unknown(Unknown),
    /// Image descriptor block
    ImageDesc(ImageDesc),
    /// Local color table block
    LocalColorTable(LocalColorTable),
    /// Image data block
    ImageData(ImageData),
    /// Trailer block
    Trailer(Trailer),
}

impl Block {
    /// Check if a block can contain sub-blocks
    pub fn has_sub_blocks(&self) -> bool {
        use self::Block::*;
        matches!(
            self,
            PlainText(_)
                | GraphicControl(_)
                | Comment(_)
                | Application(_)
                | Unknown(_)
                | ImageData(_)
        )
    }
}

impl From<Header> for Block {
    fn from(b: Header) -> Self {
        Block::Header(b)
    }
}

impl From<LogicalScreenDesc> for Block {
    fn from(b: LogicalScreenDesc) -> Self {
        Block::LogicalScreenDesc(b)
    }
}

impl From<GlobalColorTable> for Block {
    fn from(b: GlobalColorTable) -> Self {
        Block::GlobalColorTable(b)
    }
}

impl From<PlainText> for Block {
    fn from(b: PlainText) -> Self {
        Block::PlainText(b)
    }
}

impl From<GraphicControl> for Block {
    fn from(b: GraphicControl) -> Self {
        Block::GraphicControl(b)
    }
}

impl From<Comment> for Block {
    fn from(b: Comment) -> Self {
        Block::Comment(b)
    }
}

impl From<Application> for Block {
    fn from(b: Application) -> Self {
        Block::Application(b)
    }
}

impl From<Unknown> for Block {
    fn from(b: Unknown) -> Self {
        Block::Unknown(b)
    }
}

impl From<ImageDesc> for Block {
    fn from(b: ImageDesc) -> Self {
        Block::ImageDesc(b)
    }
}

impl From<LocalColorTable> for Block {
    fn from(b: LocalColorTable) -> Self {
        Block::LocalColorTable(b)
    }
}

impl From<ImageData> for Block {
    fn from(b: ImageData) -> Self {
        Block::ImageData(b)
    }
}

impl From<Trailer> for Block {
    fn from(b: Trailer) -> Self {
        Block::Trailer(b)
    }
}

/// The preamble blocks are the first few
/// blocks in a GIF file, before any frames.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Preamble {
    /// Header block
    pub header: Header,
    /// Logical screen descriptor block
    pub logical_screen_desc: LogicalScreenDesc,
    /// Global color table block
    pub global_color_table: Option<GlobalColorTable>,
    /// Loop count (application) extension block
    pub loop_count_ext: Option<Application>,
    /// Comment blocks
    pub comments: Vec<Comment>,
}

impl Preamble {
    /// Get the screen width
    pub fn screen_width(&self) -> u16 {
        self.logical_screen_desc.screen_width()
    }

    /// Get the screen height
    pub fn screen_height(&self) -> u16 {
        self.logical_screen_desc.screen_height()
    }
}

/// A single frame of a GIF animation.
///
/// Frames can be partial image which might depend on previous frames
/// to have a complete image to render.
#[derive(Debug)]
pub struct Frame {
    /// Graphic control for the frame
    pub graphic_control_ext: Option<GraphicControl>,
    /// Image descriptor for the frame
    pub image_desc: ImageDesc,
    /// Local color table for the frame
    pub local_color_table: Option<LocalColorTable>,
    /// Image data for the frame
    pub image_data: ImageData,
}

impl Frame {
    /// Create a new frame
    pub fn new(
        graphic_control_ext: Option<GraphicControl>,
        image_desc: ImageDesc,
        local_color_table: Option<LocalColorTable>,
        image_data: ImageData,
    ) -> Self {
        Frame {
            graphic_control_ext,
            image_desc,
            local_color_table,
            image_data,
        }
    }

    /// Get the frame disposal method
    pub fn disposal_method(&self) -> DisposalMethod {
        match &self.graphic_control_ext {
            Some(gc) => gc.disposal_method(),
            None => DisposalMethod::NoAction,
        }
    }

    /// Get the frame transparent color
    pub fn transparent_color(&self) -> Option<u8> {
        match &self.graphic_control_ext {
            Some(gc) => gc.transparent_color(),
            None => None,
        }
    }

    /// Get the left position
    pub fn left(&self) -> u16 {
        self.image_desc.left()
    }

    /// Get the top position
    pub fn top(&self) -> u16 {
        self.image_desc.top()
    }

    /// Get the width
    pub fn width(&self) -> u16 {
        self.image_desc.width()
    }

    /// Get the height
    pub fn height(&self) -> u16 {
        self.image_desc.height()
    }

    /// Get frame region
    pub fn region(&self) -> Region {
        let x = self.left().into();
        let y = self.top().into();
        let w = self.width().into();
        let h = self.height().into();
        Region::new(x, y, w, h)
    }
}

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

    #[test]
    fn block_size() {
        dbg!(std::mem::size_of::<Block>());
        assert!(std::mem::size_of::<Block>() <= 32);
    }

    #[test]
    fn color_table_len() {
        let t = ColorTableConfig::new(
            ColorTableExistence::Present,
            ColorTableOrdering::NotSorted,
            0,
        ); // 0-2
        assert_eq!(t.len_bits(), 0);
        let t = ColorTableConfig::new(
            ColorTableExistence::Present,
            ColorTableOrdering::NotSorted,
            4,
        ); // 3-4
        assert_eq!(t.len_bits(), 1);
        let t = ColorTableConfig::new(
            ColorTableExistence::Present,
            ColorTableOrdering::NotSorted,
            7,
        ); // 5-8
        assert_eq!(t.len_bits(), 2);
        let t = ColorTableConfig::new(
            ColorTableExistence::Present,
            ColorTableOrdering::NotSorted,
            16,
        ); // 9-16
        assert_eq!(t.len_bits(), 3);
        let t = ColorTableConfig::new(
            ColorTableExistence::Present,
            ColorTableOrdering::NotSorted,
            17,
        ); // 17-32
        assert_eq!(t.len_bits(), 4);
        let t = ColorTableConfig::new(
            ColorTableExistence::Present,
            ColorTableOrdering::NotSorted,
            64,
        ); // 33-64
        assert_eq!(t.len_bits(), 5);
        let t = ColorTableConfig::new(
            ColorTableExistence::Present,
            ColorTableOrdering::NotSorted,
            65,
        ); // 65-128
        assert_eq!(t.len_bits(), 6);
        let t = ColorTableConfig::new(
            ColorTableExistence::Present,
            ColorTableOrdering::NotSorted,
            130,
        ); // 129-256
        assert_eq!(t.len_bits(), 7);
        let t = ColorTableConfig::default();
        assert_eq!(t.len_bits(), 0);
    }

    #[test]
    fn graphic_control() {
        let mut g = GraphicControl::default();
        assert_eq!(g.disposal_method(), DisposalMethod::NoAction);
        assert_eq!(g.transparent_color(), None);
        assert_eq!(g.user_input(), false);
        g.set_disposal_method(DisposalMethod::Keep);
        assert_eq!(g.disposal_method(), DisposalMethod::Keep);
        assert_eq!(g.transparent_color(), None);
        assert_eq!(g.user_input(), false);
        g.set_transparent_color(Some(0));
        assert_eq!(g.disposal_method(), DisposalMethod::Keep);
        assert_eq!(g.transparent_color(), Some(0));
        assert_eq!(g.user_input(), false);
        g.set_transparent_color(None);
        assert_eq!(g.disposal_method(), DisposalMethod::Keep);
        assert_eq!(g.transparent_color(), None);
        assert_eq!(g.user_input(), false);
        g.set_user_input(true);
        assert_eq!(g.disposal_method(), DisposalMethod::Keep);
        assert_eq!(g.transparent_color(), None);
        assert_eq!(g.user_input(), true);
    }

    #[test]
    fn loop_count() {
        let b = Application::default();
        assert_eq!(b.loop_count(), None);
        let b = Application::with_loop_count(0);
        assert_eq!(b.loop_count(), Some(0));
        let b = Application::with_loop_count(4);
        assert_eq!(b.loop_count(), Some(4));
    }
}