@@ -76,8 +76,20 @@ type output_buffer =
7676 buf : string ;
7777 mutable pos : int ;
7878 mutable avail : int ;
79+ mutable size : int32 ;
80+ mutable crc : int32 ;
81+ mutable add_trailer : bool
7982 }
8083
84+ let write_int32 oz n =
85+ for i = 0 to 3 do
86+ Bytes. set oz.buf (oz.pos + i)
87+ (Char. chr (Int32. to_int (Int32. shift_right_logical n (8 * i)) land 0xff ))
88+ done ;
89+ oz.pos < - oz.pos + 4 ;
90+ oz.avail < - oz.avail - 4 ;
91+ assert (oz.avail > = 0 )
92+
8193(* puts in oz the content of buf, from pos to pos + len ;
8294 * f is the continuation of the current stream *)
8395let rec output oz f buf pos len =
@@ -99,6 +111,8 @@ let rec output oz f buf pos len =
99111 in
100112 oz.pos < - oz.pos + used_out;
101113 oz.avail < - oz.avail - used_out;
114+ oz.size < - Int32. add oz.size (Int32. of_int used_in);
115+ oz.crc < - Zlib. update_crc oz.crc buf pos used_in;
102116 output oz f buf (pos + used_in) (len - used_in)
103117 end
104118
@@ -138,9 +152,19 @@ and next_cont oz stream =
138152 if not finished then
139153 finish ()
140154 else
141- (Lwt_log. ign_info ~section " Zlib.deflate finished, last flush" ;
142- flush oz (fun () -> Ocsigen_stream. empty None ))) in
143-
155+ write_trailer () )
156+ and write_trailer () =
157+ if oz.add_trailer && oz.avail < 8 then
158+ flush oz write_trailer
159+ else begin
160+ if oz.add_trailer then begin
161+ write_int32 oz oz.crc;
162+ write_int32 oz oz.size
163+ end ;
164+ Lwt_log. ign_info ~section " Zlib.deflate finished, last flush" ;
165+ flush oz (fun () -> Ocsigen_stream. empty None )
166+ end
167+ in
144168 finish ()
145169 | Ocsigen_stream. Finished (Some s ) -> next_cont oz s
146170 | Ocsigen_stream. Cont (s ,f ) ->
@@ -161,7 +185,8 @@ let compress deflate stream =
161185 { stream = zstream ;
162186 buf = Bytes. create ! buffer_size;
163187 pos = 0 ;
164- avail = ! buffer_size
188+ avail = ! buffer_size;
189+ size = 0l ; crc = 0l ; add_trailer = not deflate
165190 } in
166191 let new_stream () = next_cont oz (Ocsigen_stream. get stream) in
167192 Lwt_log. ign_info ~section " Zlib stream initialized" ;
0 commit comments