{"record":{"id":"049d6c031b56f0e4","repo":"golang/go","slug":"lzw-litwidth-d-out-of-range-049d6c","errorCode":null,"errorMessage":"lzw: litWidth %d out of range","messagePattern":"lzw: litWidth (.+?) out of range","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"src/compress/lzw/writer.go","lineNumber":278,"sourceCode":"\nfunc newWriter(dst io.Writer, order Order, litWidth int) *Writer {\n\tw := new(Writer)\n\tw.init(dst, order, litWidth)\n\treturn w\n}\n\nfunc (w *Writer) init(dst io.Writer, order Order, litWidth int) {\n\tswitch order {\n\tcase LSB:\n\t\tw.write = (*Writer).writeLSB\n\tcase MSB:\n\t\tw.write = (*Writer).writeMSB\n\tdefault:\n\t\tw.err = errors.New(\"lzw: unknown order\")\n\t\treturn\n\t}\n\tif litWidth < 2 || 8 < litWidth {\n\t\tw.err = fmt.Errorf(\"lzw: litWidth %d out of range\", litWidth)\n\t\treturn\n\t}\n\tbw, ok := dst.(writer)\n\tif !ok && dst != nil {\n\t\tbw = bufio.NewWriter(dst)\n\t}\n\tw.w = bw\n\tlw := uint(litWidth)\n\tw.order = order\n\tw.width = 1 + lw\n\tw.litWidth = lw\n\tw.hi = 1<<lw + 1\n\tw.overflow = 1 << (lw + 1)\n\tw.savedCode = invalidCode\n}\n","sourceCodeStart":260,"sourceCodeEnd":294,"githubUrl":"https://github.com/golang/go/blob/b6b368adc57c96c3151d224d172029f233ead2c3/src/compress/lzw/writer.go#L260-L294","documentation":"`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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Use litWidth in [2,8] and keep it identical to the decoder's width.","Validate the value at the boundary that supplies it (config load, header parse).","Test the round-trip: write then read back, asserting Close/Flush returns no error."],"exampleFix":"// before\nw := lzw.NewWriter(dst, lzw.LSB, 0)\n// after\nw := lzw.NewWriter(dst, lzw.LSB, 8)","handlingStrategy":"validation","validationCode":"if litWidth < 2 || litWidth > 8 {\n    return fmt.Errorf(\"lzw litWidth must be in [2,8], got %d\", litWidth)\n}","typeGuard":null,"tryCatchPattern":"if _, err := w.Write(data); err != nil { /* width/order invalid */ }","preventionTips":["Keep the encoder's litWidth identical to the decoder's.","Round-trip test encode/decode to catch width mismatches."],"tags":["compress","lzw","argument-validation","gif"],"backgroundTag":null,"analyzedSha":"b6b368adc57c96c3151d224d172029f233ead2c3","analyzedAt":"2026-08-12T00:22:02.250Z","schemaVersion":2},"datasetVersion":"2026-08-12T13:17:24.610Z"}