Source File
reader.go
Belonging Package
golang.org/x/image/tiff/lzw
// Copyright 2011 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.// Package lzw implements the Lempel-Ziv-Welch compressed data format,// described in T. A. Welch, “A Technique for High-Performance Data// Compression”, Computer, 17(6) (June 1984), pp 8-19.//// In particular, it implements LZW as used by the TIFF file format, including// an "off by one" algorithmic difference when compared to standard LZW.package lzw // import "golang.org/x/image/tiff/lzw"/*This file was branched from src/pkg/compress/lzw/reader.go in thestandard library. Differences from the original are marked with "NOTE".The tif_lzw.c file in the libtiff C library has this comment:----The 5.0 spec describes a different algorithm than Aldusimplements. Specifically, Aldus does code length transitionsone code earlier than should be done (for real LZW).Earlier versions of this library implemented the correctLZW algorithm, but emitted codes in a bit order oppositeto the TIFF spec. Thus, to maintain compatibility w/ Alduswe interpret MSB-LSB ordered codes to be images written w/old versions of this library, but otherwise adhere to theAldus "off by one" algorithm.----The Go code doesn't read (invalid) TIFF files written by old versions oflibtiff, but the LZW algorithm in this package still differs from the one inGo's standard package library to accommodate this "off by one" in valid TIFFs.*/import ()// Order specifies the bit ordering in an LZW data stream.type Order intconst (// LSB means Least Significant Bits first, as used in the GIF file format.LSB Order = iota// MSB means Most Significant Bits first, as used in the TIFF and PDF// file formats.MSB)const (maxWidth = 12decoderInvalidCode = 0xffffflushBuffer = 1 << maxWidth)// decoder is the state from which the readXxx method converts a byte// stream into a code stream.type decoder struct {r io.ByteReaderbits uint32nBits uintwidth uintread func(*decoder) (uint16, error) // readLSB or readMSBlitWidth int // width in bits of literal codeserr error// The first 1<<litWidth codes are literal codes.// The next two codes mean clear and EOF.// Other valid codes are in the range [lo, hi] where lo := clear + 2,// with the upper bound incrementing on each code seen.// overflow is the code at which hi overflows the code width. NOTE: TIFF's LZW is "off by one".// last is the most recently seen code, or decoderInvalidCode.clear, eof, hi, overflow, last uint16// Each code c in [lo, hi] expands to two or more bytes. For c != hi:// suffix[c] is the last of these bytes.// prefix[c] is the code for all but the last byte.// This code can either be a literal code or another code in [lo, c).// The c == hi case is a special case.suffix [1 << maxWidth]uint8prefix [1 << maxWidth]uint16// output is the temporary output buffer.// Literal codes are accumulated from the start of the buffer.// Non-literal codes decode to a sequence of suffixes that are first// written right-to-left from the end of the buffer before being copied// to the start of the buffer.// It is flushed when it contains >= 1<<maxWidth bytes,// so that there is always room to decode an entire code.output [2 * 1 << maxWidth]byteo int // write index into outputtoRead []byte // bytes to return from Read}// readLSB returns the next code for "Least Significant Bits first" data.func ( *decoder) () (uint16, error) {for .nBits < .width {, := .r.ReadByte()if != nil {return 0,}.bits |= uint32() << .nBits.nBits += 8}:= uint16(.bits & (1<<.width - 1)).bits >>= .width.nBits -= .widthreturn , nil}// readMSB returns the next code for "Most Significant Bits first" data.func ( *decoder) () (uint16, error) {for .nBits < .width {, := .r.ReadByte()if != nil {return 0,}.bits |= uint32() << (24 - .nBits).nBits += 8}:= uint16(.bits >> (32 - .width)).bits <<= .width.nBits -= .widthreturn , nil}func ( *decoder) ( []byte) (int, error) {for {if len(.toRead) > 0 {:= copy(, .toRead).toRead = .toRead[:]return , nil}if .err != nil {return 0, .err}.decode()}}// decode decompresses bytes from r and leaves them in d.toRead.// read specifies how to decode bytes into codes.// litWidth is the width in bits of literal codes.func ( *decoder) () {// Loop over the code stream, converting codes into decompressed bytes.:for {, := .read()if != nil {if == io.EOF {= io.ErrUnexpectedEOF}.err =break}switch {case < .clear:// We have a literal code..output[.o] = uint8().o++if .last != decoderInvalidCode {// Save what the hi code expands to..suffix[.hi] = uint8().prefix[.hi] = .last}case == .clear:.width = 1 + uint(.litWidth).hi = .eof.overflow = 1 << .width.last = decoderInvalidCodecontinuecase == .eof:.err = io.EOFbreakcase <= .hi:, := , len(.output)-1if == .hi && .last != decoderInvalidCode {// code == hi is a special case which expands to the last expansion// followed by the head of the last expansion. To find the head, we walk// the prefix chain until we find a literal code.= .lastfor >= .clear {= .prefix[]}.output[] = uint8()--= .last}// Copy the suffix chain into output and then write that to w.for >= .clear {.output[] = .suffix[]--= .prefix[]}.output[] = uint8().o += copy(.output[.o:], .output[:])if .last != decoderInvalidCode {// Save what the hi code expands to..suffix[.hi] = uint8().prefix[.hi] = .last}default:.err = errors.New("lzw: invalid code")break}.last, .hi = , .hi+1if .hi+1 >= .overflow { // NOTE: the "+1" is where TIFF's LZW differs from the standard algorithm.if .width == maxWidth {.last = decoderInvalidCode} else {.width++.overflow <<= 1}}if .o >= flushBuffer {break}}// Flush pending output..toRead = .output[:.o].o = 0}var errClosed = errors.New("lzw: reader/writer is closed")func ( *decoder) () error {.err = errClosed // in case any Reads come alongreturn nil}// NewReader creates a new io.ReadCloser.// Reads from the returned io.ReadCloser read and decompress data from r.// If r does not also implement io.ByteReader,// the decompressor may read more data than necessary from r.// It is the caller's responsibility to call Close on the ReadCloser when// finished reading.// The number of bits to use for literal codes, litWidth, must be in the// range [2,8] and is typically 8. It must equal the litWidth// used during compression.func ( io.Reader, Order, int) io.ReadCloser {:= new(decoder)switch {case LSB:.read = (*decoder).readLSBcase MSB:.read = (*decoder).readMSBdefault:.err = errors.New("lzw: unknown order")return}if < 2 || 8 < {.err = fmt.Errorf("lzw: litWidth %d out of range", )return}if , := .(io.ByteReader); {.r =} else {.r = bufio.NewReader()}.litWidth =.width = 1 + uint().clear = uint16(1) << uint().eof, .hi = .clear+1, .clear+1.overflow = uint16(1) << .width.last = decoderInvalidCodereturn}
![]() |
The pages are generated with Golds v0.8.7. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds. |