golang/go · error

lzw: litWidth %d out of range

Error message

lzw: litWidth %d out of range

What it means

`lzw.NewWriter` mirrors the reader: `litWidth` must be in [2,8]. Out-of-range values are stored on `w.err` and surface on the first `Write`/`Close`, not from `NewWriter` itself. The writer is the encoding side of the same LZW variant used for GIF.

Source

Thrown at src/compress/lzw/writer.go:278

func newWriter(dst io.Writer, order Order, litWidth int) *Writer {
	w := new(Writer)
	w.init(dst, order, litWidth)
	return w
}

func (w *Writer) init(dst io.Writer, order Order, litWidth int) {
	switch order {
	case LSB:
		w.write = (*Writer).writeLSB
	case MSB:
		w.write = (*Writer).writeMSB
	default:
		w.err = errors.New("lzw: unknown order")
		return
	}
	if litWidth < 2 || 8 < litWidth {
		w.err = fmt.Errorf("lzw: litWidth %d out of range", litWidth)
		return
	}
	bw, ok := dst.(writer)
	if !ok && dst != nil {
		bw = bufio.NewWriter(dst)
	}
	w.w = bw
	lw := uint(litWidth)
	w.order = order
	w.width = 1 + lw
	w.litWidth = lw
	w.hi = 1<<lw + 1
	w.overflow = 1 << (lw + 1)
	w.savedCode = invalidCode
}

View on GitHub (pinned to b6b368adc5)

Solutions

  1. Use litWidth in [2,8] and keep it identical to the decoder's width.
  2. Validate the value at the boundary that supplies it (config load, header parse).
  3. Test the round-trip: write then read back, asserting Close/Flush returns no error.

Example fix

// before
w := lzw.NewWriter(dst, lzw.LSB, 0)
// after
w := lzw.NewWriter(dst, lzw.LSB, 8)
Defensive patterns

Strategy: validation

Validate before calling

if litWidth < 2 || litWidth > 8 {
    return fmt.Errorf("lzw litWidth must be in [2,8], got %d", litWidth)
}

Try / catch

if _, err := w.Write(data); err != nil { /* width/order invalid */ }

Prevention

When it happens

Trigger: Calling `lzw.NewWriter(dst, order, w)` with w<2 or w>8; mismatching the decoder's litWidth (encoder/decoder must agree); defaulting w to 0 from an uninitialized field.

Common situations: Producing GIF-compatible LZW streams with the wrong width; reader/writer pairs configured from different config sources; refactoring that swaps a width constant for a different meaning.

Related errors


AI-assisted analysis of golang/go@b6b368adc5 (2026-08-12). Data as JSON: /api/errors/049d6c031b56f0e4. Report an issue: GitHub.