Files
wuffs/std/gzip/decode_gzip.wuffs
T
Nigel Tao 97aab37462 Rename buf1, reader1, etc to io_buffer, io_reader
Also remove the unused Buf1, Buf2 and Usize tokens.
2018-04-05 20:49:48 +10:00

114 lines
2.8 KiB
Plaintext

// Copyright 2018 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
packageid "gzip"
use "std/crc32"
use "std/deflate"
pub error "bad gzip header"
pub error "checksum mismatch"
pub error "invalid gzip compression method"
pub error "invalid gzip encoding flags"
pub struct decoder?(
flate deflate.decoder,
checksum crc32.ieee,
ignore_checksum bool,
)
pub func decoder.set_ignore_checksum!(ic bool)() {
this.ignore_checksum = in.ic
}
pub func decoder.decode?(dst io_writer, src io_reader)() {
// Read the header.
if in.src.read_u8?() != 0x1F {
return error "bad gzip header"
}
if in.src.read_u8?() != 0x8B {
return error "bad gzip header"
}
if in.src.read_u8?() != 0x08 {
return error "invalid gzip compression method"
}
var flags u8 = in.src.read_u8?()
// TODO: API for returning the header's MTIME field.
in.src.skip32?(n:6)
var c u8
// Handle FEXTRA.
if (flags & 0x04) != 0 {
var xlen u16 = in.src.read_u16le?()
in.src.skip32?(n:xlen as u32)
}
// Handle FNAME.
//
// TODO: API for returning the header's FNAME field. This might require
// converting ISO 8859-1 to UTF-8. We may also want to cap the UTF-8
// filename length to NAME_MAX, which is 255.
if (flags & 0x08) != 0 {
while true {
c = in.src.read_u8?()
if c == 0 {
break
}
}
}
// Handle FCOMMENT.
if (flags & 0x10) != 0 {
while true {
c = in.src.read_u8?()
if c == 0 {
break
}
}
}
// Handle FHCRC.
if (flags & 0x02) != 0 {
in.src.skip32?(n:2)
}
// Reserved flags bits must be zero.
if (flags & 0xE0) != 0 {
return error "invalid gzip encoding flags"
}
// Decode and checksum the DEFLATE-encoded payload.
var checksum_got u32
var decoded_length_got u32
while true {
in.dst.mark()
var z status = try this.flate.decode?(dst:in.dst, src:in.src)
if not this.ignore_checksum {
checksum_got = this.checksum.update(x:in.dst.since_mark())
decoded_length_got = decoded_length_got ~+
((in.dst.since_mark().length() & 0xFFFFFFFF) as u32)
}
if z.is_ok() {
break
}
yield z
}
var checksum_want u32 = in.src.read_u32le?()
var decoded_length_want u32 = in.src.read_u32le?()
if (not this.ignore_checksum) and
((checksum_got != checksum_want) or (decoded_length_got != decoded_length_want)) {
return error "checksum mismatch"
}
}