compress/lzw Encode Decode Roundtrip

Compress and decompress bytes with compress/lzw, where the byte order and literal width are parameters that both ends must share.

GoData Integrity

Code

gosnippet
44 lines
package main

import (
	"bytes"
	"compress/lzw"
	"fmt"
	"io"
)

func main() {
	payload := []byte("the quick brown fox jumps over the lazy dog; the quick brown fox")

	// TIFF 风格的参数:MSB 字节序 + 8 位字面量宽度
	var buf bytes.Buffer
	writer := lzw.NewWriter(&buf, lzw.MSB, 8)
	if _, err := writer.Write(payload); err != nil {
		fmt.Println("write:", err)
		return
	}
	// NewWriter 返回 WriteCloser:不 Close 就丢掉了尾部编码状态
	if err := writer.Close(); err != nil {
		fmt.Println("close:", err)
		return
	}
	fmt.Println("raw bytes:", len(payload), "encoded bytes:", buf.Len())

	// 解码端必须用同一组 (order, litWidth),否则读出来的不是原字节
	reader := lzw.NewReader(bytes.NewReader(buf.Bytes()), lzw.MSB, 8)
	defer reader.Close()
	decoded, err := io.ReadAll(reader)
	if err != nil {
		fmt.Println("read:", err)
		return
	}
	fmt.Println("roundtrip:", bytes.Equal(decoded, payload))
	fmt.Println("text:", string(decoded))

	// GIF 惯例是 LSB + 8;参数不同得到的码流不通用
	var gif bytes.Buffer
	gw := lzw.NewWriter(&gif, lzw.LSB, 8)
	gw.Write(payload)
	gw.Close()
	fmt.Println("lsb bytes:", gif.Len(), "differs from msb:", gif.Len() != buf.Len())
}

The path through the code

compress/lzw Encode Decode Roundtrip comes down to the function main.

Error handling is inline: 3 places test err != nil and branch immediately. Cleanup is attached with defer, so it runs on every exit path of the function.

What to watch for

  • bytes, compress/lzw, and io are the only imports, all from the standard distribution.

Using it

Signature: func main()

The demo output is labeled (write:, close:, raw bytes:); each label names the call that printed it.

Key statements

if err != nil {
	fmt.Println("read:", err)
	return
}
defer reader.Close()

Interactive Tools for This Topic

FAQ

What does compress/lzw Encode Decode Roundtrip print when run?
Invoke the file as-is — the `write:`, `close:`, `raw bytes:` prefixes identify which step printed each line.