golang/go · error

lzw: litWidth %d out of range

Error message

lzw: litWidth %d out of range

What it means

`lzw.NewReader` stores the order and `litWidth` (literal-code bit width) on the reader via `init`. `litWidth` must be between 2 and 8 inclusive — values outside that range set `r.err` (note: stored, not returned directly from NewReader) and the reader returns the error on first Read. This width governs the dictionary size; for GIF it is conventionally 8.

Source

Thrown at src/compress/lzw/reader.go:275

func newReader(src io.Reader, order Order, litWidth int) *Reader {
	r := new(Reader)
	r.init(src, order, litWidth)
	return r
}

func (r *Reader) init(src io.Reader, order Order, litWidth int) {
	switch order {
	case LSB:
		r.read = (*Reader).readLSB
	case MSB:
		r.read = (*Reader).readMSB
	default:
		r.err = errors.New("lzw: unknown order")
		return
	}
	if litWidth < 2 || 8 < litWidth {
		r.err = fmt.Errorf("lzw: litWidth %d out of range", litWidth)
		return
	}

	br, ok := src.(io.ByteReader)
	if !ok && src != nil {
		br = bufio.NewReader(src)
	}
	r.r = br
	r.litWidth = litWidth
	r.width = 1 + uint(litWidth)
	r.clear = uint16(1) << uint(litWidth)
	r.eof, r.hi = r.clear+1, r.clear+1
	r.overflow = uint16(1) << r.width
	r.last = decoderInvalidCode
}

View on GitHub (pinned to b6b368adc5)

Solutions

  1. Pass litWidth in [2,8]; for GIF use 8, for many TIFF readers use 8 unless the image header specifies otherwise.
  2. Validate before constructing: `if litWidth < 2 || litWidth > 8 { return fmt.Errorf("bad litWidth %d", litWidth) }`.
  3. Check the error on the first `Read` from the returned reader, not just from `NewReader` — the constructor defers the error.

Example fix

// before
r := lzw.NewReader(src, lzw.LSB, 1)
// after
r := lzw.NewReader(src, 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

// the error is deferred to the first Read
n, err := r.Read(buf)
if err != nil { /* width or order invalid */ }

Prevention

When it happens

Trigger: Calling `lzw.NewReader(src, order, w)` with w<2 or w>8; treating `litWidth` as a byte count instead of bit width; passing 0 by defaulting from an unset struct field; hardcoding a width tuned for a different LZW variant.

Common situations: Decoding GIF/LZW with a misconfigured width pulled from a corrupt header; forking a TIFF reader that supplies a wrong `litWidth`; confusing MSB/LSB AND the width.

Related errors


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