//go:build generate // +build generate //go:generate go run $GOFILE //go:generate go fmt ../inflate_gen.go package main import ( "os" "strings" ) func main() { f, err := os.Create("../inflate_gen.go") if err != nil { panic(err) } defer f.Close() types := []string{"*bytes.Buffer", "*bytes.Reader", "*bufio.Reader", "*strings.Reader", "Reader"} names := []string{"BytesBuffer", "BytesReader", "BufioReader", "StringsReader", "GenericReader"} imports := []string{"bytes", "bufio", "fmt", "strings", "math/bits", "", "github.com/klauspost/compress/internal/regmask"} f.WriteString(`// Code generated by go generate gen_inflate.go. DO NOT EDIT. package flate import ( `) for _, imp := range imports { if imp == "" { f.WriteString("\n") continue } f.WriteString("\t\"" + imp + "\"\n") } f.WriteString(")\n\n") template := ` // Decode a single Huffman block from f. // hl and hd are the Huffman states for the lit/length values // and the distance values, respectively. If hd == nil, using the // fixed distance encoding associated with fixed Huffman blocks. func (f *decompressor) $FUNCNAME$() { const ( stateInit = iota // Zero value must be stateInit stateDict ) fr := f.r.($TYPE$) // Optimization. Compiler isn't smart enough to keep f.b,f.nb in registers, // but is smart enough to keep local variables in registers, so use nb and b, // inline call to moreBits and reassign b,nb back to f on return. fnb, fb, dict := f.nb, f.b, &f.dict $PEEKTOP$ switch f.stepState { case stateInit: goto readLiteral case stateDict: goto copyHistory } readLiteral: // Read literal and/or (length, distance) according to RFC section 3.2.3. { var v int { // Inlined v, err := f.huffSym(f.hl) // Since a huffmanDecoder can be empty or be composed of a degenerate tree // with single element, huffSym must error on these two edge cases. In both // cases, the chunks slice will be 0 for the invalid sequence, leading it // satisfy the n == 0 check below. n := uint(f.hl.maxRead) for { for fnb < n { $GETBYTE_S$ f.err = noEOF(err) $GETBYTE_E$ f.roffset++ fb |= uint32(c) << (fnb & regmask.Shift32ByUint) fnb += 8 } chunk := f.hl.chunks[fb&(huffmanNumChunks-1)] n = uint(chunk & huffmanCountMask) if n > huffmanChunkBits { chunk = f.hl.links[chunk>>huffmanValueShift][(fb>>huffmanChunkBits)&f.hl.linkMask] n = uint(chunk & huffmanCountMask) } if n <= fnb { if n == 0 { $DISCARD$ f.b, f.nb = fb, fnb if debugDecode { fmt.Println("huffsym: n==0") } f.err = CorruptInputError(f.roffset) return } fb = fb >> (n & regmask.Shift32ByUint) fnb = fnb - n v = int(chunk >> huffmanValueShift) break } } } var length int switch { case v < 256: dict.writeByte(byte(v)) if dict.availWrite() == 0 { $DISCARD$ f.toRead = dict.readFlush() f.step = $FUNCNAME$ f.stepState = stateInit f.b, f.nb = fb, fnb return } goto readLiteral case v == 256: $DISCARD$ f.b, f.nb = fb, fnb f.finishBlock() return // otherwise, reference to older data case v < 265: length = v - (257 - 3) case v < maxNumLit: val := decCodeToLen[(v - 257)] length = int(val.length) + 3 n := uint(val.extra) for fnb < n { $GETBYTE_S$ if debugDecode { fmt.Println("morebits n>0:", err) } f.err = err $GETBYTE_E$ f.roffset++ fb |= uint32(c) << (fnb®mask.Shift32ByUint) fnb += 8 } length += int(fb & bitMask32[n]) fb >>= n & regmask.Shift32ByUint fnb -= n default: $DISCARD$ if debugDecode { fmt.Println(v, ">= maxNumLit") } f.err = CorruptInputError(f.roffset) f.b, f.nb = fb, fnb return } var dist uint32 if f.hd == nil { for fnb < 5 { $GETBYTE_S$ if debugDecode { fmt.Println("morebits f.nb<5:", err) } f.err = err $GETBYTE_E$ f.roffset++ fb |= uint32(c) << (fnb®mask.Shift32ByUint) fnb += 8 } dist = uint32(bits.Reverse8(uint8(fb & 0x1F << 3))) fb >>= 5 fnb -= 5 } else { // Since a huffmanDecoder can be empty or be composed of a degenerate tree // with single element, huffSym must error on these two edge cases. In both // cases, the chunks slice will be 0 for the invalid sequence, leading it // satisfy the n == 0 check below. n := uint(f.hd.maxRead) // Optimization. Compiler isn't smart enough to keep f.b,f.nb in registers, // but is smart enough to keep local variables in registers, so use nb and b, // inline call to moreBits and reassign b,nb back to f on return. for { for fnb < n { $GETBYTE_S$ f.err = noEOF(err) $GETBYTE_E$ f.roffset++ fb |= uint32(c) << (fnb & regmask.Shift32ByUint) fnb += 8 } chunk := f.hd.chunks[fb&(huffmanNumChunks-1)] n = uint(chunk & huffmanCountMask) if n > huffmanChunkBits { chunk = f.hd.links[chunk>>huffmanValueShift][(fb>>huffmanChunkBits)&f.hd.linkMask] n = uint(chunk & huffmanCountMask) } if n <= fnb { if n == 0 { $DISCARD$ f.b, f.nb = fb, fnb if debugDecode { fmt.Println("huffsym: n==0") } f.err = CorruptInputError(f.roffset) return } fb = fb >> (n & regmask.Shift32ByUint) fnb = fnb - n dist = uint32(chunk >> huffmanValueShift) break } } } switch { case dist < 4: dist++ case dist < maxNumDist: nb := uint(dist-2) >> 1 // have 1 bit in bottom of dist, need nb more. extra := (dist & 1) << (nb & regmask.Shift32ByUint) for fnb < nb { $GETBYTE_S$ if debugDecode { fmt.Println("morebits f.nb>= nb & regmask.Shift32ByUint fnb -= nb dist = 1<<((nb+1)®mask.Shift32ByUint) + 1 + extra // slower: dist = bitMask32[nb+1] + 2 + extra default: $DISCARD$ f.b, f.nb = fb, fnb if debugDecode { fmt.Println("dist too big:", dist, maxNumDist) } f.err = CorruptInputError(f.roffset) return } // No check on length; encoding can be prescient. if dist > uint32(dict.histSize()) { $DISCARD$ f.b, f.nb = fb, fnb if debugDecode { fmt.Println("dist > dict.histSize():", dist, dict.histSize()) } f.err = CorruptInputError(f.roffset) return } f.copyLen, f.copyDist = length, int(dist) goto copyHistory } copyHistory: // Perform a backwards copy according to RFC section 3.2.3. { cnt := dict.tryWriteCopy(f.copyDist, f.copyLen) if cnt == 0 { cnt = dict.writeCopy(f.copyDist, f.copyLen) } f.copyLen -= cnt if dict.availWrite() == 0 || f.copyLen > 0 { $DISCARD$ f.toRead = dict.readFlush() f.step = $FUNCNAME$ // We need to continue this work f.stepState = stateDict f.b, f.nb = fb, fnb return } goto readLiteral } // Not reached } ` f.WriteString(` func peekBufio(fr *bufio.Reader) ([]byte, error) { if fr.Buffered() == 0 { if _, err := fr.Peek(1); err != nil && fr.Buffered() == 0 { return nil, err } } return fr.Peek(fr.Buffered()) } `) // Each variant pulls the next input byte differently. The default reads via // fr.ReadByte(). The *bufio.Reader variant reads from a Peek window so the // per-byte fill inlines as a slice index; since Peek only views the buffer and // Discard advances it, it must Discard consumed bytes before every return. // getS/getE wrap each read site around that site's own EOF handling: // // (output indentation is normalized by the go fmt step, so these need not be // pre-indented). type readImpl struct{ top, getS, getE, discard string } readByte := readImpl{ getS: `c, err := fr.ReadByte() if err != nil { f.b, f.nb = fb, fnb`, getE: `return }`, } peek := readImpl{ top: "pbuf, _ := fr.Peek(fr.Buffered())\npos := 0\n", getS: `if pos >= len(pbuf) { fr.Discard(pos) var err error pbuf, err = peekBufio(fr) pos = 0 if len(pbuf) == 0 { f.b, f.nb = fb, fnb`, getE: `return } } c := pbuf[pos] pos++`, discard: "fr.Discard(pos)\n", } for i, t := range types { r := readByte if t == "*bufio.Reader" { r = peek } f.WriteString(strings.NewReplacer( "$FUNCNAME$", "huffman"+names[i], "$TYPE$", t, "$PEEKTOP$", r.top, "$GETBYTE_S$", r.getS, "$GETBYTE_E$", r.getE, "$DISCARD$", r.discard, ).Replace(template)) } f.WriteString("func (f *decompressor) huffmanBlockDecoder() {\n") f.WriteString("\tswitch f.r.(type) {\n") for i, t := range types { f.WriteString("\t\tcase " + t + ":\n") f.WriteString("\t\t\tf.huffman" + names[i] + "()\n") } f.WriteString("\t\tdefault:\n") f.WriteString("\t\t\tf.huffmanGenericReader()\n") f.WriteString("\t}\n}\n") }