@@ -5,6 +5,8 @@ const beginBlock = @import("block_writer.zig").beginBlock;
5
5
const endBlock = @import ("block_writer.zig" ).endBlock ;
6
6
const bmp = @import ("bmp.zig" );
7
7
const io = @import ("io.zig" );
8
+ const report = @import ("report.zig" );
9
+ const BMCOMP_NMAJMIN_H7 = @import ("rmim.zig" ).BMCOMP_NMAJMIN_H7 ;
8
10
const BMCOMP_NMAJMIN_H8 = @import ("rmim.zig" ).BMCOMP_NMAJMIN_H8 ;
9
11
const BMCOMP_NMAJMIN_HT8 = @import ("rmim.zig" ).BMCOMP_NMAJMIN_HT8 ;
10
12
@@ -24,18 +26,22 @@ pub fn encode(
24
26
25
27
const bmap_fixup = try beginBlock (out , "BMAP" );
26
28
27
- // only these are implemented
28
- if (compression != BMCOMP_NMAJMIN_H8 and compression != BMCOMP_NMAJMIN_HT8 )
29
- return error .BadData ;
30
29
try out .writer ().writeByte (compression );
31
- try compressBmap (header , out .writer ());
30
+ try compressBmap (header , compression , out .writer ());
32
31
33
32
try endBlock (out , fixups , bmap_fixup );
34
33
35
34
try endBlock (out , fixups , im00_fixup );
36
35
}
37
36
38
- fn compressBmap (header : bmp.Bmp , writer : anytype ) ! void {
37
+ fn compressBmap (header : bmp.Bmp , compression : u8 , writer : anytype ) ! void {
38
+ const color_bits : u8 = switch (compression ) {
39
+ BMCOMP_NMAJMIN_H7 = > 7 ,
40
+ BMCOMP_NMAJMIN_H8 , BMCOMP_NMAJMIN_HT8 = > 8 ,
41
+ else = > return error .BadData ,
42
+ };
43
+ const max_pixel : u8 = @intCast ((@as (u9 , 1 ) << @intCast (color_bits )) - 1 );
44
+
39
45
var out = std .io .bitWriter (.little , writer );
40
46
41
47
var pixit = try header .iterPixels ();
@@ -44,6 +50,11 @@ fn compressBmap(header: bmp.Bmp, writer: anytype) !void {
44
50
try out .writeBits (current , 8 );
45
51
46
52
while (pixit .next ()) | pixel | {
53
+ if (pixel > max_pixel ) {
54
+ report .fatal ("color index {} too large for encoding" , .{pixel });
55
+ return error .Reported ;
56
+ }
57
+
47
58
const diff = @as (i16 , pixel ) - current ;
48
59
if (diff == 0 ) {
49
60
try out .writeBits (@as (u1 , 0 ), 1 );
@@ -55,7 +66,7 @@ fn compressBmap(header: bmp.Bmp, writer: anytype) !void {
55
66
try out .writeBits (@as (u3 , @intCast (diff + 3 )), 3 );
56
67
} else {
57
68
try out .writeBits (@as (u2 , 1 ), 2 );
58
- try out .writeBits (pixel , 8 );
69
+ try out .writeBits (pixel , color_bits );
59
70
}
60
71
61
72
current = pixel ;
0 commit comments