Standard library / compress/lzw
compress/lzw.NewWriter()
Construct an LZW compression writer using matching order and literal width. Input byte values must fit the literal width; check Write and Close errors. Expected stdout: 'Go\n'.
Formal Syntax & Structure
go syntaxgo
func NewWriter(w io.Writer, order Order, litWidth int) io.WriteCloserParameters & Attributes
| Name | Type | Description |
|---|---|---|
| w | io.Writer | Destination for compressed bytes; closing the compressor does not close this writer. |
| order | Order | Bit packing order, LSB or MSB. Match the encoder and decoder. |
| litWidth | int | Literal code width in bits, from 2 through 8. |
Return Value
io.WriteCloser
Compression writer; close to finalize the stream and check the error.
Working Example
Example Snippetgo
package main
import ( "bytes" "compress/lzw" "fmt" "io")
func must(e error) { if e != nil { panic(e) }}func pack(s string, order lzw.Order) []byte { var b bytes.Buffer w := lzw.NewWriter(&b, order, 8) _, e := w.Write([]byte(s)) must(e) must(w.Close()) return b.Bytes()}func unpack(b []byte, order lzw.Order) string { r := lzw.NewReader(bytes.NewReader(b), order, 8) p, e := io.ReadAll(r) must(e) must(r.Close()) return string(p)}func main() { var b bytes.Buffer w := lzw.NewWriter(&b, lzw.MSB, 8) _, e := w.Write([]byte("Go")) must(e) must(w.Close()) fmt.Println(unpack(b.Bytes(), lzw.MSB))}