### NewWriterLevel usage example Source: https://github.com/andybalholm/brotli Shows how to create a writer with brotli.BestCompression, write a string, and close the writer. The example uses log.Fatal on write or close errors. ```go var buf bytes.Buffer w := brotli.NewWriterLevel(&buf, brotli.BestCompression) if _, err := io.WriteString(w, "compress me"); err != nil { log.Fatal(err) } if err := w.Close(); err != nil { log.Fatal(err) } ``` -------------------------------- ### Manual two-stage pipeline example Source: https://github.com/andybalholm/brotli Shows how to use Encoder directly with a matchfinder to compress a byte slice. The example creates an Encoder, finds matches with ZFast, encodes with lastBlock true, and prints the compressed size. ```go var dst []byte enc := &brotli.Encoder{} mf := &matchfinder.ZFast{MaxDistance: 1 << 20} src := []byte("the quick brown fox jumps over the lazy dog. " + "the quick brown fox jumps over the lazy dog.") matches := mf.FindMatches(nil, src) dst = enc.Encode(dst, src, matches, true) // dst now contains a complete, decodable brotli stream. fmt.Println(len(dst), "compressed bytes") ``` -------------------------------- ### Flush example Source: https://github.com/andybalholm/brotli Example of using Flush to make partial data available before closing the stream. Returns nil on success; errors include errEncode and errWriterClosed. ```go w := brotli.NewWriter(dst) io.WriteString(w, "partial") if err := w.Flush(); err != nil { // make bytes available without finishing the stream log.Fatal(err) } io.WriteString(w, "more") w.Close() ``` -------------------------------- ### FastEncoder usage example with match finder Source: https://github.com/andybalholm/brotli Example showing how to use FastEncoder with a match finder that produces only matches of at least 4 bytes. Bargain1's MinLength defaults to 4. ```go enc := &brotli.FastEncoder{} mf := &matchfinder.Bargain1{MaxDistance: 1 << 20} // MinLength defaults to 4 var dst []byte src := []byte("abcabcabcabcabcabcabcabcabc") matches := mf.FindMatches(nil, src) dst = enc.Encode(dst, src, matches, true) ``` -------------------------------- ### HTTPCompressorWithLevel usage example Source: https://github.com/andybalholm/brotli Example handler using brotli.HTTPCompressorWithLevel with brotli.BestCompression. The returned WriteCloser must be closed before the handler returns. ```go func handler(w http.ResponseWriter, r *http.Request) { cw := brotli.HTTPCompressorWithLevel(w, r, brotli.BestCompression) defer cw.Close() io.WriteString(cw, payload) } ``` -------------------------------- ### HTTPCompressor usage example Source: https://github.com/andybalholm/brotli Example handler using brotli.HTTPCompressor. The returned WriteCloser must be closed before the handler returns; the deferred Close ensures that. ```go func handler(w http.ResponseWriter, r *http.Request) { cw := brotli.HTTPCompressor(w, r) defer cw.Close() // must close before the handler returns io.WriteString(cw, "compressed response") } ``` -------------------------------- ### Write example Source: https://github.com/andybalholm/brotli Example of using Write to compress data. Returns the number of bytes consumed and an error. Errors include errWriterClosed after Close and errEncode on encoder failure. ```go w := brotli.NewWriter(dst) n, err := w.Write([]byte("data")) if err != nil { log.Fatal(err) } fmt.Println("wrote", n, "bytes") ``` -------------------------------- ### Writer usage example Source: https://github.com/andybalholm/brotli Shows how to create a Writer with a ZFast MatchFinder and brotli.Encoder, write a string, and close. Uses BlockSize 1<<16. ```go var buf bytes.Buffer w := &matchfinder.Writer{ Dest: &buf, MatchFinder: &matchfinder.ZFast{MaxDistance: 1 << 20}, Encoder: &brotli.Encoder{}, BlockSize: 1 << 16, } io.WriteString(w, "hello hello hello") if err := w.Close(); err != nil { log.Fatal(err) } ``` -------------------------------- ### NewWriterV2 usage example Source: https://github.com/andybalholm/brotli Shows how to create a writer with level 9, write a byte slice, and close the writer. The example uses log.Fatal on write or close errors. ```go var buf bytes.Buffer w := brotli.NewWriterV2(&buf, 9) if _, err := w.Write([]byte("hello world hello world")); err != nil { log.Fatal(err) } if err := w.Close(); err != nil { log.Fatal(err) } ``` -------------------------------- ### Write error example Source: https://github.com/andybalholm/brotli Example showing that writing after Close returns errWriterClosed. The error can be checked with errors.Is. ```go w := brotli.NewWriter(dst) w.Close() // stream is now finished _, err := w.Write([]byte("late")) if err != nil && errors.Is(err, errWriterClosed) { log.Println("write after close rejected:", err) } ``` -------------------------------- ### NewReaderOptions example: large-window streams (RFC 9841) Source: https://github.com/andybalholm/brotli Creates a Reader with LargeWindow enabled for RFC 9841 large-window streams, then copies decompressed output to out. Errors are fatal. ```go r := brotli.NewReaderOptions(file, brotli.ReaderOptions{LargeWindow: true}) if _, err := io.Copy(out, r); err != nil { log.Fatal(err) } ``` -------------------------------- ### NewReader example: decompress file to stdout Source: https://github.com/andybalholm/brotli Opens a compressed Brotli file and uses NewReader with io.Copy to decompress to stdout. Handles errors with log.Fatal. ```go compressed, _ := os.Open("data.br") defer compressed.Close() r := brotli.NewReader(compressed) if _, err := io.Copy(os.Stdout, r); err != nil { log.Fatal(err) } ``` -------------------------------- ### Writer usage example with NoMatchFinder (HuffmanOnly) Source: https://github.com/andybalholm/brotli Shows a Writer with NoMatchFinder so no matches are found; every byte becomes a literal. Close is called without error checking. ```go var buf bytes.Buffer w := &matchfinder.Writer{ Dest: &buf, MatchFinder: matchfinder.NoMatchFinder{}, Encoder: &brotli.Encoder{}, } io.WriteString(w, "no matches are found here") w.Close() // every byte becomes a literal ``` -------------------------------- ### Reset example: reuse Reader across files Source: https://github.com/andybalholm/brotli Creates a Reader once and reuses it for multiple files via Reset. The LargeWindow option is retained. This is the reuse pattern from example_test.go. ```go br := brotli.NewReader(nil) // create once for _, f := range files { f, _ := os.Open(f) if err := br.Reset(f); err != nil { log.Fatal(err) } io.Copy(os.Stdout, br) f.Close() } ``` -------------------------------- ### Reset usage example Source: https://github.com/andybalholm/brotli Demonstrates the canonical reuse pattern from ExampleWriter_Reset: create the writer once with NewWriter(nil), then Reset before each stream. The writer is reused for a fresh stream by resetting it with a new destination buffer. ```go var b bytes.Buffer bw := brotli.NewWriter(nil) bw.Reset(&b) // reuse the writer for a fresh stream io.WriteString(bw, "first message") bw.Close() ``` -------------------------------- ### Read example: manual read loop with error handling Source: https://github.com/andybalholm/brotli Reads decompressed data in 4096-byte chunks, writing to stdout. Detects truncated streams via io.ErrUnexpectedEOF and stops when n == 0. ```go r := brotli.NewReader(compressed) p := make([]byte, 4096) for { n, err := r.Read(p) os.Stdout.Write(p[:n]) if err != nil { if errors.Is(err, io.ErrUnexpectedEOF) { log.Fatal("truncated brotli stream") } log.Fatal(err) } if n == 0 { break } } ``` -------------------------------- ### Close usage example Source: https://github.com/andybalholm/brotli Shows how to use Close after writing data. Creates a writer with NewWriterLevel, writes a payload, then calls Close to finalize the stream. The error from Close is checked with log.Fatal. ```go w := brotli.NewWriterLevel(&buf, 5) io.WriteString(w, "payload") if err := w.Close(); err != nil { log.Fatal(err) } ``` -------------------------------- ### NewGZIPWriter: compress data with gzip encoding Source: https://github.com/andybalholm/brotli Creates a matchfinder.Writer that compresses data at the given level (1–9) in gzip encoding, producing a complete gzip file (header + deflate body + CRC32/ISIZE trailer). The example creates a file, writes to it via gzip, and closes both. ```go f, _ := os.Create("out.gz") gw := flate.NewGZIPWriter(f, 9) io.Copy(gw, r) // stream an io.Reader into gzip gw.Close() f.Close() ``` -------------------------------- ### NewGZIPEncoder: gzip encoder with match finder Source: https://github.com/andybalholm/brotli Returns a matchfinder.Encoder that wraps NewEncoder() and writes a gzip header on first Encode, and appends CRC-32 and ISIZE on lastBlock. The example shows using it with a match finder to write gzip output to stdout. ```go w := &matchfinder.Writer{ Dest: os.Stdout, MatchFinder: &matchfinder.ZFast{MaxDistance: 1 << 15}, Encoder: flate.NewGZIPEncoder(), } io.WriteString(w, "gzip output") w.Close() ``` -------------------------------- ### NewEncoder: combine with any match finder Source: https://github.com/andybalholm/brotli Returns a matchfinder.Encoder that writes raw DEFLATE format (RFC 1951) with dynamic Huffman coding, stored blocks, and fixed blocks as appropriate. The example shows combining it with a custom match finder in a matchfinder.Writer. ```go var buf bytes.Buffer w := &matchfinder.Writer{ Dest: &buf, MatchFinder: &matchfinder.Bargain2{MaxDistance: 1 << 15}, Encoder: flate.NewEncoder(), // deflate, not brotli } io.WriteString(w, "data") w.Close() ``` -------------------------------- ### NewWriter: compress data with flate encoding Source: https://github.com/andybalholm/brotli Creates a matchfinder.Writer that compresses data at the given level (1–9) in flate encoding. Levels outside the range are replaced with the closest available. The writer uses BlockSize 1<<16 and the default flate encoder. The example writes a string to a buffer and closes the writer. ```go var buf bytes.Buffer fw := flate.NewWriter(&buf, 6) if _, err := io.WriteString(fw, "deflate me"); err != nil { log.Fatal(err) } if err := fw.Close(); err != nil { log.Fatal(err) } ``` -------------------------------- ### NewWriter constructor signature Source: https://github.com/andybalholm/brotli Creates a *Writer compressing at DefaultCompression (level 6). Equivalent to NewWriterLevel(dst, DefaultCompression). The caller must call Close when done; writes are buffered and may not be flushed until Close. ```go func NewWriter(dst io.Writer) *Writer ``` -------------------------------- ### matchfinder.Writer options Source: https://github.com/andybalholm/brotli Configuration options for the matchfinder.Writer. Configured via exported struct fields. ```APIDOC ## matchfinder.Writer options ### Description Configuration options for the matchfinder.Writer. Configured via exported struct fields. ### Fields - **Dest** (io.Writer) - Required - Destination for compressed output - **MatchFinder** (MatchFinder) - Required - LZ77 match-finding stage - **Encoder** (Encoder) - Required - Format-encoding stage - **BlockSize** (int) - Optional - Number of bytes to compress at a time. If zero, each `Write` operation is treated as one block. ``` -------------------------------- ### NewReaderOptions function signature Source: https://github.com/andybalholm/brotli Constructor that creates a Reader with supplied decoding options. Takes an io.Reader source and ReaderOptions, returns a *Reader. ```go func NewReaderOptions(src io.Reader, options ReaderOptions) *Reader ``` -------------------------------- ### NewWriterV2 function signature Source: https://github.com/andybalholm/brotli Declares the experimental NewWriterV2 constructor that uses the matchfinder-based implementation. Levels are clamped to 0–9, and the returned writer uses BlockSize 1<<16. ```go func NewWriterV2(dst io.Writer, level int) *matchfinder.Writer ``` -------------------------------- ### MatchFinder interface definition Source: https://github.com/andybalholm/brotli Defines the interface for the LZ77 stage of compression. Implemented by M0, M4, ZFast, ZDFast, ZM, Trio, Bargain1, Bargain2, Bargain3, Pathfinder, and NoMatchFinder. FindMatches appends matches to dst and returns it; Reset clears internal state for a new stream. ```go // A MatchFinder performs the LZ77 stage of compression, looking for matches. type MatchFinder interface { // FindMatches looks for matches in src, appends them to dst, and returns dst. FindMatches(dst []Match, src []byte) []Match // Reset clears any internal state, preparing the MatchFinder to be used with // a new stream. Reset() } ``` -------------------------------- ### NewWriterLevel function signature Source: https://github.com/andybalholm/brotli Declares the NewWriterLevel constructor that creates a brotli writer with a specified compression level. The level must be DefaultCompression or an integer between BestSpeed (0) and BestCompression (11) inclusive. ```go func NewWriterLevel(dst io.Writer, level int) *Writer ``` -------------------------------- ### Read method signature Source: https://github.com/andybalholm/brotli Implements io.Reader. Decompresses into p, pulling more input from src as needed. Returns bytes read and error; terminal errors include io.EOF, io.ErrUnexpectedEOF, io.ErrShortBuffer, errExcessiveInput, errInvalidState, and decodeError. ```go func (r *Reader) Read(p []byte) (n int, err error) ``` -------------------------------- ### brotli.WriterOptions struct Source: https://github.com/andybalholm/brotli Defines the WriterOptions struct with Quality and LGWin fields. Passed to NewWriterOptions and applied by (*Writer).Reset. Quality ranges 0-11, LGWin ranges 10-24 with 0 meaning automatic. ```go type WriterOptions struct { Quality int LGWin int } ``` -------------------------------- ### NewWriterOptions function signature Source: https://github.com/andybalholm/brotli Declares the NewWriterOptions constructor that creates a brotli writer from a full WriterOptions value, which configures quality and window size. ```go func NewWriterOptions(dst io.Writer, options WriterOptions) *Writer ``` -------------------------------- ### NewReader function signature Source: https://github.com/andybalholm/brotli Constructor that creates a Reader with default options (LargeWindow disabled). Takes an io.Reader source of compressed Brotli data and returns a *Reader. ```go func NewReader(src io.Reader) *Reader ``` -------------------------------- ### (*Writer).Flush Source: https://github.com/andybalholm/brotli Flushes any buffered compressed data to the underlying writer. This ensures that all data written so far is output. ```APIDOC ## (*Writer).Flush ### Description Flushes any buffered compressed data to the underlying writer. This ensures that all data written so far is output. ### Method Method ### Signature `func (w *Writer) Flush() error` ### Returns - **error** - An error if flushing fails. ``` -------------------------------- ### Reset method signature Source: https://github.com/andybalholm/brotli Discards Reader state and makes it equivalent to NewReader but reading from src. Retains LargeWindow option across Reset. Error return is always nil. ```go func (r *Reader) Reset(src io.Reader) error ``` -------------------------------- ### Reset method signature Source: https://github.com/andybalholm/brotli Declares the Reset method on the brotli Writer. It discards the Writer's state and makes it equivalent to the result of NewWriter or NewWriterLevel, but writing to dst instead. Preserves configured Quality and (if nonzero) LGWin options. ```go func (w *Writer) Reset(dst io.Writer) ``` -------------------------------- ### HTTPCompressor Source: https://github.com/andybalholm/brotli Chooses a compression method (brotli, gzip, or none) based on the Accept-Encoding header, sets the Content-Encoding header, and returns a WriteCloser that implements that compression. The Close method must be called before the current HTTP handler returns. ```APIDOC ## HTTPCompressor ### Description Chooses a compression method (brotli, gzip, or none) based on the Accept-Encoding header, sets the Content-Encoding header, and returns a WriteCloser that implements that compression. The Close method must be called before the current HTTP handler returns. ### Method Function ### Endpoint func HTTPCompressor(w http.ResponseWriter, r *http.Request) io.WriteCloser ### Parameters #### Function Parameters - **w** (http.ResponseWriter) - Required - Response writer to receive the compressed body - **r** (http.Request pointer) - Required - The request whose Accept-Encoding header is negotiated ### Response #### Return Value - **io.WriteCloser** - A WriteCloser that implements the negotiated compression: *brotli.Writer (level 4) when br wins, *gzip.Writer when gzip wins, or nopCloser (uncompressed passthrough) when neither is acceptable. ### Request Example ```go func handler(w http.ResponseWriter, r *http.Request) { cw := brotli.HTTPCompressor(w, r) defer cw.Close() // must close before the handler returns io.WriteString(cw, "compressed response") } ``` ``` -------------------------------- ### FastEncoder.Encode method signature Source: https://github.com/andybalholm/brotli Method signature for encoding a block. Same contract as Encoder.Encode. Panics with "match too short (minimum 4 bytes)" if a match length is between 1 and 3. ```go func (e *FastEncoder) Encode(dst []byte, src []byte, matches []matchfinder.Match, lastBlock bool) []byte ``` -------------------------------- ### NewWriterOptions Source: https://github.com/andybalholm/brotli Creates a new Brotli writer with a full WriterOptions value, allowing configuration of quality and window size. This function is similar to NewWriter but provides more control over the compression settings. ```APIDOC ## NewWriterOptions ### Description Creates a new Brotli writer with a full WriterOptions value, allowing configuration of quality and window size. This function is similar to NewWriter but provides more control over the compression settings. ### Method Function ### Signature `func NewWriterOptions(dst io.Writer, options WriterOptions) *Writer` ### Parameters - **dst** (io.Writer) - Required - Destination that receives the compressed bytes - **options** (WriterOptions) - Required - Quality and window-size configuration ### Returns - **\*Writer** - A writer initialized from options ``` -------------------------------- ### WriterOptions struct definition Source: https://github.com/andybalholm/brotli Configures Writer with Quality (0-11) and LGWin (10-24, 0 for automatic). Defaults are overridden by constructor. Consumed by NewWriterOptions and applied by (*Writer).Reset. ```go // WriterOptions configures Writer. type WriterOptions struct { // Quality controls the compression-speed vs compression-density trade-offs. // The higher the quality, the slower the compression. Range is 0 to 11. Quality int // LGWin is the base 2 logarithm of the sliding window size. // Range is 10 to 24. 0 indicates automatic configuration based on Quality. LGWin int } ``` -------------------------------- ### brotli.ReaderOptions Source: https://github.com/andybalholm/brotli Configuration options for the Brotli reader. Passed to NewReaderOptions and retained across Reset. ```APIDOC ## brotli.ReaderOptions ### Description Configuration options for the Brotli reader. Passed to NewReaderOptions and retained across Reset. ### Fields - **LargeWindow** (bool) - Optional - Accept the large-window extension defined by RFC 9841 (window bits up to 30, header prefix `0x11`). Disabled by default. Applications such as PDF readers may require it. Without it, large-window streams fail with a `WINDOW_BITS` decode error. ``` -------------------------------- ### NewGZIPWriter Source: https://github.com/andybalholm/brotli Creates a new matchfinder.Writer that compresses data at the given level in gzip encoding. Levels 1–9 are available; levels outside this range will be replaced by the closest level available. ```APIDOC ## NewGZIPWriter ### Description Returns a new matchfinder.Writer that compresses data at the given level, in gzip encoding. Levels 1–9 are available; levels outside this range will be replaced by the closest level available. Identical to NewWriter but uses the gzip encoder, producing a complete gzip file (header + deflate body + CRC32/ISIZE trailer). ### Parameters - **w** (io.Writer) - Required - Destination for the gzip stream - **level** (int) - Required - Compression level 1–9 ### Returns - **matchfinder.Writer** - Pre-configured with the gzip encoder. ### Request Example ```go f, _ := os.Create("out.gz") gw := flate.NewGZIPWriter(f, 9) io.Copy(gw, r) // stream an io.Reader into gzip gw.Close() f.Close() ``` ``` -------------------------------- ### MatchFinder interface Source: https://github.com/andybalholm/brotli The MatchFinder interface defines the LZ77 stage of compression, with methods to find matches and reset state. ```APIDOC ## MatchFinder interface ### Description The MatchFinder interface performs the LZ77 stage of compression, looking for matches. Implemented by: M0, M4, ZFast, ZDFast, ZM, Trio, Bargain1, Bargain2, Bargain3, Pathfinder, NoMatchFinder. ### Methods - **FindMatches** `FindMatches(dst []Match, src []byte) []Match` - Looks for matches in src, appends them to dst, returns dst - **Reset** `Reset()` - Clears internal state for a new stream ### Source `matchfinder/matchfinder.go:23` ``` -------------------------------- ### Read Source: https://github.com/andybalholm/brotli Implements io.Reader. Decompresses into p, pulling more input from the underlying src as needed. ```APIDOC ## Read ### Description Implements `io.Reader`. Decompresses into `p`, pulling more input from the underlying `src` as needed. The state machine is `decoderDecompressStream` (`decode.go:2097`). ### Method Read ### Endpoint `func (r *Reader) Read(p []byte) (n int, err error)` ### Parameters #### Parameters - **p** ([]byte) - Required - Destination buffer for decompressed bytes ### Response Returns the number of bytes read and an error. Terminal states and errors: | Returned error | Condition | |----------------|-----------| | `io.EOF` | underlying `src` returned EOF while the decoder state is `stateDone` (the stream was fully decoded with the final input chunk); n == 0 | | `io.ErrUnexpectedEOF` | `src` returned `io.EOF` before the stream reached `stateDone` (truncated stream) | | `io.ErrShortBuffer` | decoder produced no output but needs a larger buffer (`decoderResultNeedsMoreOutput` and n == 0) | | `errExcessiveInput` ("brotli: excessive input") | stream decoded successfully but input bytes remained unconsumed | | `errInvalidState` ("brotli: invalid state") | input remained unread after a non-terminal decode step | | `decodeError` ("brotli: ") | corrupt or unsupported stream; see [errors.md](../errors.md) | Note: if the underlying `src.Read` returns `(0, nil)`, that behavior is proxied directly. ### Request Example ```go r := brotli.NewReader(compressed) p := make([]byte, 4096) for { n, err := r.Read(p) os.Stdout.Write(p[:n]) if err != nil { if errors.Is(err, io.ErrUnexpectedEOF) { log.Fatal("truncated brotli stream") } log.Fatal(err) } if n == 0 { break } } ``` ``` -------------------------------- ### NewWriter Source: https://github.com/andybalholm/brotli Creates a new Writer that compresses data at the default compression level (6). The caller must call Close when done, as writes are buffered and may not be flushed until Close. ```APIDOC ## NewWriter ### Description Creates a new Writer that compresses data at the default compression level (6). The caller must call Close when done, as writes are buffered and may not be flushed until Close. ### Method NewWriter ### Parameters #### Parameters - **dst** (io.Writer) - Required - Destination that receives the compressed bytes ### Returns - **writer** (*Writer) - The new Writer instance ``` -------------------------------- ### NewReaderOptions Source: https://github.com/andybalholm/brotli Creates a Reader with the supplied decoding options. ```APIDOC ## NewReaderOptions ### Description Creates a `Reader` with the supplied decoding options. ### Method NewReaderOptions ### Endpoint `func NewReaderOptions(src io.Reader, options ReaderOptions) *Reader` ### Parameters #### Parameters - **src** (io.Reader) - Required - Source of compressed Brotli data - **options** (ReaderOptions) - Required - Decoding options (see [configuration.md](../configuration.md)) ### Response Returns a `*Reader`. ### Request Example — large-window streams (RFC 9841) ```go r := brotli.NewReaderOptions(file, brotli.ReaderOptions{LargeWindow: true}) if _, err := io.Copy(out, r); err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Encoder and FastEncoder Source: https://github.com/andybalholm/brotli Encoder and FastEncoder are structs that implement the matchfinder.Encoder interface. They are used internally by the brotli writer for compression. ```APIDOC ## Encoder and FastEncoder ### Description Encoder and FastEncoder are structs that implement the matchfinder.Encoder interface. They are used internally by the brotli writer for compression. ### Type Struct ### Implements - **matchfinder.Encoder** - Interface for LZ77 encoders. ``` -------------------------------- ### Reset Source: https://github.com/andybalholm/brotli Discards the Writer's state and makes it equivalent to the result of its original state from NewWriter or NewWriterLevel, but writing to dst instead. This permits reusing a Writer rather than allocating a new one. ```APIDOC ## Reset ### Description Discards the `Writer`'s state and makes it equivalent to the result of its original state from `NewWriter` or `NewWriterLevel`, but writing to `dst` instead. This permits reusing a `Writer` rather than allocating a new one. The configured `Quality` and (if nonzero) `LGWin` options are preserved. ### Method Reset ### Signature `func (w *Writer) Reset(dst io.Writer)` ### Parameters #### Parameters - **dst** (io.Writer) - Required - New destination for compressed output ### Response No return value. ### Request Example ```go var b bytes.Buffer bw := brotli.NewWriter(nil) bw.Reset(&b) // reuse the writer for a fresh stream io.WriteString(bw, "first message") bw.Close() ``` ``` -------------------------------- ### Write method signature Source: https://github.com/andybalholm/brotli Signature of the Write method on the brotli Writer. It implements io.Writer and compresses p into the stream. Flush or Close must be called to ensure encoded bytes are flushed to the underlying writer. ```go func (w *Writer) Write(p []byte) (n int, err error) ``` -------------------------------- ### M4 methods: FindMatches and Reset Source: https://github.com/andybalholm/brotli Declares the two methods of the M4 type. FindMatches finds matches in the source, and Reset clears state. History is trimmed to MaxDistance when it grows past MaxDistance*2. ```go func (q *M4) FindMatches(dst []Match, src []byte) []Match func (q *M4) Reset() ``` -------------------------------- ### Writer.Reset Source: https://github.com/andybalholm/brotli Clears internal buffers and errors, resets both MatchFinder and Encoder, and repoints Dest at newDest. ```APIDOC ## Writer.Reset ### Description Clears internal buffers and errors, resets both MatchFinder and Encoder, and repoints Dest at newDest. ### Method Reset ### Signature ```go func (w *Writer) Reset(newDest io.Writer) ``` ### Parameters - **newDest** (io.Writer) - Required - New destination for compressed output ``` -------------------------------- ### (*Reader).Reset Source: https://github.com/andybalholm/brotli Resets the Brotli reader to read from a new source, reusing internal buffers. This allows efficient reuse of the reader. ```APIDOC ## (*Reader).Reset ### Description Resets the Brotli reader to read from a new source, reusing internal buffers. This allows efficient reuse of the reader. ### Method Method ### Signature `func (r *Reader) Reset(src io.Reader) error` ### Parameters - **src** (io.Reader) - Required - The new source of compressed data. ### Returns - **error** - An error if resetting fails. ``` -------------------------------- ### FastEncoder.Reset method signature Source: https://github.com/andybalholm/brotli Method signature for resetting encoder state, preparing it for a new stream. ```go func (e *FastEncoder) Reset() ``` -------------------------------- ### Writer struct definition (encode.go) Source: https://github.com/andybalholm/brotli The Writer struct holds the destination writer, options, and unexported encoder state. All fields are unexported; configuration is done via WriterOptions. A zero-value Writer is not usable; always construct with NewWriter, NewWriterLevel, or NewWriterOptions. ```go type Writer struct { dst io.Writer options WriterOptions err error params encoderParams hasher_ hasherHandle input_pos_ uint64 ringbuffer_ ringBuffer commands []command num_literals_ uint last_insert_len_ uint last_flush_pos_ uint64 last_processed_pos_ uint64 dist_cache_ [numDistanceShortCodes]int saved_dist_cache_ [4]int // ... additional unexported encoder state (see encode.go:74) } ``` -------------------------------- ### WriterOptions Source: https://github.com/andybalholm/brotli Configuration options for the Brotli Writer. It controls compression quality and sliding window size. ```APIDOC ## WriterOptions ### Description Configuration options for the Brotli Writer. It controls compression quality and sliding window size. ### Fields - **Quality** (int) - Optional - Compression quality 0–11. Higher values mean slower compression but better density. - **LGWin** (int) - Optional - Base-2 logarithm of the sliding window size, range 10–24. 0 indicates automatic configuration based on Quality. ### Defaults - Quality: 0 (overridden by constructor) - LGWin: 0 (automatic) ### Usage Consumed by `NewWriterOptions` and applied by `(*Writer).Reset`. ``` -------------------------------- ### Match struct definition Source: https://github.com/andybalholm/brotli Defines the basic unit of LZ77 compression. A sequence of Match values describes the input: before each match there are Unmatched literal bytes, then Length bytes copied from Distance bytes back. A final match with Length == 0 and Unmatched covering the tail terminates the stream. ```go // A Match is the basic unit of LZ77 compression. type Match struct { Unmatched int // the number of unmatched bytes since the previous match Length int // the number of bytes in the matched string; it may be 0 at the end of the input Distance int // how far back in the stream to copy from } ``` -------------------------------- ### NewWriterV2 Source: https://github.com/andybalholm/brotli Creates a new Brotli writer using the new implementation based on the matchfinder package. Supports levels 0-9; higher levels are clamped to 9, negative levels to 0. This function is experimental and not covered by SemVer compatibility guarantees. ```APIDOC ## NewWriterV2 ### Description Creates a new Brotli writer using the new implementation based on the matchfinder package. Supports levels 0-9; higher levels are clamped to 9, negative levels to 0. This function is experimental and not covered by SemVer compatibility guarantees. ### Method Function ### Signature `func NewWriterV2(dst io.Writer, level int) *matchfinder.Writer` ### Parameters - **dst** (io.Writer) - Required - Destination that receives the compressed bytes - **level** (int) - Required - Compression level 0-9 (clamped) ### Returns - **\*matchfinder.Writer** - A writer using the matchfinder package ### Level Configuration | level | MatchFinder | Encoder | |-------|-------------|---------| | 0 | `matchfinder.ZFast{MaxDistance: 1 << 20}` | `&FastEncoder{}` | | 1 | `matchfinder.ZFast{MaxDistance: 1 << 20}` | `&Encoder{}` | | 2 | `matchfinder.ZDFast{MaxDistance: 1 << 20}` | `&Encoder{}` | | 3 | `matchfinder.ZM{MaxDistance: 1 << 20}` | `&Encoder{}` | | 4 | `matchfinder.Trio{MaxDistance: 1 << 20}` | `&Encoder{}` | | 5, 6 | `matchfinder.Bargain1{MaxDistance: 1 << 20}` | `&Encoder{}` | | 7 | `matchfinder.Bargain2{MaxDistance: 1 << 20, Skip: true}` | `&Encoder{}` | | 8 | `matchfinder.Bargain2{MaxDistance: 1 << 20}` | `&Encoder{}` | | 9 | `matchfinder.Bargain3{MaxDistance: 1 << 20}` | `&Encoder{}` | ### Request Example ```go var buf bytes.Buffer w := brotli.NewWriterV2(&buf, 9) if _, err := w.Write([]byte("hello world hello world")); err != nil { log.Fatal(err) } if err := w.Close(); err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### NewWriter Source: https://github.com/andybalholm/brotli Creates a new matchfinder.Writer that compresses data at the given level in flate encoding. Levels 1–9 are available; levels outside this range will be replaced with the closest level available. ```APIDOC ## NewWriter ### Description Returns a new matchfinder.Writer that compresses data at the given level, in flate encoding. Levels 1–9 are available; levels outside this range will be replaced with the closest level available. ### Parameters - **w** (io.Writer) - Required - Destination for the deflate stream - **level** (int) - Required - Compression level 1–9 (out-of-range values use the closest available) ### Returns - **matchfinder.Writer** - Pre-configured with BlockSize: 1 << 16 and the default flate encoder. Match finder selected per level. ### Request Example ```go var buf bytes.Buffer fw := flate.NewWriter(&buf, 6) if _, err := io.WriteString(fw, "deflate me"); err != nil { log.Fatal(err) } if err := fw.Close(); err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Encode Source: https://github.com/andybalholm/brotli Encodes the source data using the FastEncoder, writing Brotli format. It uses static histograms and panics if a match is shorter than 4 bytes. ```APIDOC ## Encode ### Description Encodes the source data using the FastEncoder, writing Brotli format. It uses static histograms and panics if a match is shorter than 4 bytes. ### Method Encode ### Signature `func (e *FastEncoder) Encode(dst []byte, src []byte, matches []matchfinder.Match, lastBlock bool) []byte` ### Parameters - **dst** ([]byte) - Required - Destination buffer for encoded output. - **src** ([]byte) - Required - Source data to encode. - **matches** ([]matchfinder.Match) - Required - Matches found by a match finder; must be at least 4 bytes long. - **lastBlock** (bool) - Required - Indicates if this is the final block. ### Returns - **[]byte** - The encoded Brotli data. ### Errors - Panics with `"match too short (minimum 4 bytes)"` if a match length is between 1 and 3. ### Example ```go enc := &brotli.FastEncoder{} mf := &matchfinder.Bargain1{MaxDistance: 1 << 20} // MinLength defaults to 4 var dst []byte src := []byte("abcabcabcabcabcabcabcabcabc") matches := mf.FindMatches(nil, src) dst = enc.Encode(dst, src, matches, true) ``` ``` -------------------------------- ### Bargain3 Source: https://github.com/andybalholm/brotli Bargain3 is a MatchFinder that attempts to find the encoding with the lowest 'bit cost', using 3 hash lengths (5, 8, and 12). It exposes MaxDistance and Skip fields and implements FindMatches and Reset methods. ```APIDOC ## Bargain3 ### Description Bargain3 is a MatchFinder that attempts to find the encoding with the lowest "bit cost", using 3 hash lengths (5, 8, and 12). ### Fields - **MaxDistance** (int) - Maximum look-back distance in bytes - **Skip** (bool) - Look for matches at every other byte instead of every byte (faster, worse compression) ### Methods - `func (z *Bargain3) FindMatches(dst []Match, src []byte) []Match` - `func (z *Bargain3) Reset()` ``` -------------------------------- ### (*Writer).Reset Source: https://github.com/andybalholm/brotli Resets the Brotli writer to write to a new underlying writer, reusing internal buffers. This allows efficient reuse of the writer. ```APIDOC ## (*Writer).Reset ### Description Resets the Brotli writer to write to a new underlying writer, reusing internal buffers. This allows efficient reuse of the writer. ### Method Method ### Signature `func (w *Writer) Reset(dst io.Writer)` ### Parameters - **dst** (io.Writer) - Required - The new underlying writer. ``` -------------------------------- ### NewReader Source: https://github.com/andybalholm/brotli Creates a new Reader reading the given reader, with default options (LargeWindow disabled). ```APIDOC ## NewReader ### Description Creates a new `Reader` reading the given reader, with default options (`LargeWindow` disabled). ### Method NewReader ### Endpoint `func NewReader(src io.Reader) *Reader` ### Parameters #### Parameters - **src** (io.Reader) - Required - Source of compressed Brotli data ### Response Returns a `*Reader`. ### Request Example ```go compressed, _ := os.Open("data.br") defer compressed.Close() r := brotli.NewReader(compressed) if _, err := io.Copy(os.Stdout, r); err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### HTTPCompressorWithLevel Source: https://github.com/andybalholm/brotli Same as HTTPCompressor, but specifies the brotli compression level used when br is negotiated. The level is also used for gzip, clamped to ≤ 9. ```APIDOC ## HTTPCompressorWithLevel ### Description Same as HTTPCompressor, but specifies the brotli compression level used when br is negotiated. The level is also used for gzip, clamped to ≤ 9. ### Method Function ### Endpoint func HTTPCompressorWithLevel(w http.ResponseWriter, r *http.Request, level int) io.WriteCloser ### Parameters #### Function Parameters - **w** (http.ResponseWriter) - Required - Response writer to receive the compressed body - **r** (http.Request pointer) - Required - The request whose Accept-Encoding header is negotiated - **level** (int) - Required - Brotli level passed to NewWriterLevel; also used for gzip (clamped to ≤ 9) ### Response #### Return Value - **io.WriteCloser** - A WriteCloser that implements the negotiated compression, using the specified brotli level when br wins. ### Request Example ```go func handler(w http.ResponseWriter, r *http.Request) { cw := brotli.HTTPCompressorWithLevel(w, r, brotli.BestCompression) defer cw.Close() io.WriteString(cw, payload) } ``` ``` -------------------------------- ### Close method signature Source: https://github.com/andybalholm/brotli Declares the Close method on the brotli Writer. It flushes remaining data, writes the final 'islast' metablock, and sets w.dst to nil. After Close, further Write/Flush calls return errWriterClosed. Returns errEncode if finalization fails. ```go func (w *Writer) Close() error ``` -------------------------------- ### Writer.Reset method signature Source: https://github.com/andybalholm/brotli Signature for the Reset method. Clears internal buffers and errors, resets both MatchFinder and Encoder, and repoints Dest at newDest. ```go func (w *Writer) Reset(newDest io.Writer) ``` -------------------------------- ### (*Writer).Close Source: https://github.com/andybalholm/brotli Closes the Brotli writer, flushing any remaining data and releasing resources. The underlying writer is not closed. ```APIDOC ## (*Writer).Close ### Description Closes the Brotli writer, flushing any remaining data and releasing resources. The underlying writer is not closed. ### Method Method ### Signature `func (w *Writer) Close() error` ### Returns - **error** - An error if closing fails. ``` -------------------------------- ### NewGZIPEncoder Source: https://github.com/andybalholm/brotli Returns a matchfinder.Encoder wrapping NewEncoder() that writes gzip format. On the first Encode it writes the gzip header and when lastBlock is true appends the CRC-32 and total input length. ```APIDOC ## NewGZIPEncoder ### Description Returns a matchfinder.Encoder (*gzipEncoder) wrapping NewEncoder(). On the first Encode it writes the gzip header (0x1f 0x8b, CM=8 flate, FLG=0, mtime = time.Now().Unix(), XFL=0, OS=255) and when lastBlock is true appends the CRC-32 (IEEE table) of all input and the total input length (ISIZE), little-endian. ### Returns - **matchfinder.Encoder** - The gzip encoder. ### Request Example ```go w := &matchfinder.Writer{ Dest: os.Stdout, MatchFinder: &matchfinder.ZFast{MaxDistance: 1 << 15}, Encoder: flate.NewGZIPEncoder(), } io.WriteString(w, "gzip output") w.Close() ``` ``` -------------------------------- ### Bargain1 Source: https://github.com/andybalholm/brotli Bargain1 is a MatchFinder that attempts to find the encoding with the lowest 'bit cost', using 1 hash length (6). It exposes MaxDistance and Skip fields and implements FindMatches and Reset methods. ```APIDOC ## Bargain1 ### Description Bargain1 is a MatchFinder that attempts to find the encoding with the lowest "bit cost", using 1 hash length (6). ### Fields - **MaxDistance** (int) - Maximum look-back distance in bytes - **Skip** (bool) - Look for matches at every other byte instead of every byte (faster, worse compression) ### Methods - `func (z *Bargain1) FindMatches(dst []Match, src []byte) []Match` - `func (z *Bargain1) Reset()` ``` -------------------------------- ### Match struct Source: https://github.com/andybalholm/brotli The Match struct represents the basic unit of LZ77 compression, describing unmatched bytes, match length, and distance. ```APIDOC ## Match struct ### Description The Match struct is the intermediate representation between MatchFinder and Encoder. A sequence of matches describes the input: before each match there are Unmatched literal bytes, then Length bytes copied from Distance bytes back. A final match with Length == 0 and Unmatched covering the tail of input terminates the stream. ### Fields - **Unmatched** (int) - Number of unmatched (literal) bytes since the previous match - **Length** (int) - Number of bytes in the matched string; may be 0 at the end of the input - **Distance** (int) - How far back in the stream to copy from ### Source `matchfinder/matchfinder.go:16` ``` -------------------------------- ### Flush Source: https://github.com/andybalholm/brotli Outputs encoded data for all input provided to Write. The resulting output can be decoded to match all input before Flush, but the stream is not yet complete until after Close. Flushing has a negative impact on compression. ```APIDOC ## Flush ### Description Outputs encoded data for all input provided to Write. The resulting output can be decoded to match all input before Flush, but the stream is not yet complete until after Close. Flushing has a negative impact on compression. ### Method Flush ### Endpoint func (w *Writer) Flush() error ### Response #### Success Response Returns `nil` on success. #### Error Response - **errEncode** - if the stream encoder fails - **errWriterClosed** - if already closed ### Request Example ```go w := brotli.NewWriter(dst) io.WriteString(w, "partial") if err := w.Flush(); err != nil { // make bytes available without finishing the stream log.Fatal(err) } io.WriteString(w, "more") w.Close() ``` ``` -------------------------------- ### FastEncoder struct definition Source: https://github.com/andybalholm/brotli Defines the FastEncoder type implementing the matchfinder.Encoder interface. Uses a simplified encoding (like level 0) and does not support matches shorter than four bytes. ```go // A FastEncoder implements the matchfinder.Encoder interface, writing in Brotli // format. It uses a simplified encoding (like level 0 in the reference // implementation) to save time. It does not support matches shorter than four // bytes. type FastEncoder struct { wroteHeader bool bw bitWriter commandHisto [704]uint32 distanceHisto [64]uint32 } ```