### Get and Put ByteBuffers from Default Pool Source: https://context7.com/valyala/bytebufferpool/llms.txt Acquire a byte buffer from the default pool using `Get` and return it using `Put`. Always pair `Get` with `Put` to ensure proper resource management. Do not use the buffer after calling `Put`. ```go package main import ( "fmt" "github.com/valyala/bytebufferpool" ) func main() { // Acquire a buffer from the pool bb := bytebufferpool.Get() // Write data using multiple methods bb.WriteString("Hello, ") bb.Write([]byte("world")) bb.WriteByte('!') fmt.Println(bb.String()) // Output: Hello, world! // Return the buffer to the pool — do NOT use bb after this bytebufferpool.Put(bb) } ``` -------------------------------- ### Get() *ByteBuffer Source: https://context7.com/valyala/bytebufferpool/llms.txt Obtains an empty *ByteBuffer from the package-level default pool. Always pair with Put() after use. The buffer has a zero-length byte slice with pre-allocated capacity. ```APIDOC ## Get() *ByteBuffer ### Description Obtains an empty `*ByteBuffer` from the package-level default pool. The returned buffer's `B` field is a zero-length byte slice with pre-allocated capacity. Always pair `Get` with a corresponding `Put` after use. ### Method `Get()` ### Parameters None ### Request Example ```go package main import ( "fmt" "github.com/valyala/bytebufferpool" ) func main() { bb := bytebufferpool.Get() // ... use bb ... bytebufferpool.Put(bb) } ``` ### Response #### Success Response (ByteBuffer) - **B** ([]byte) - The byte slice buffer. ### Response Example ```go // Example of a returned ByteBuffer (internal structure not fully exposed in docs) { "B": []byte{} } ``` ``` -------------------------------- ### Get current ByteBuffer length Source: https://context7.com/valyala/bytebufferpool/llms.txt Returns the number of bytes in the buffer. Useful for size checks and content-length headers without string conversion. ```go package main import ( "fmt" "github.com/valyala/bytebufferpool" ) func main() { bb := bytebufferpool.Get() defer bytebufferpool.Put(bb) fmt.Println(bb.Len()) // 0 bb.WriteString("hello") fmt.Println(bb.Len()) // 5 bb.Write([]byte(" world")) fmt.Println(bb.Len()) // 11 if bb.Len() > 10 { fmt.Println("Buffer exceeds 10 bytes:", bb.String()) } // Output: Buffer exceeds 10 bytes: hello world } ``` -------------------------------- ### Create and Use Custom BytebufferPool Instances Source: https://context7.com/valyala/bytebufferpool/llms.txt Illustrates creating separate `bytebufferpool.Pool` instances for different purposes (e.g., JSON serialization, HTTP responses). This allows for independent calibration and potentially better memory efficiency for distinct buffer usage patterns. ```go package main import ( "fmt" "github.com/valyala/bytebufferpool" ) // Dedicated pool for JSON serialization buffers var jsonPool bytebufferpool.Pool // Dedicated pool for HTTP response body buffers var responsePool bytebufferpool.Pool func buildJSON(key, value string) string { bb := jsonPool.Get() defer jsonPool.Put(bb) bb.WriteString(`{"`) bb.WriteString(key) bb.WriteString(`":"`) bb.WriteString(value) bb.WriteString(`"}`) return bb.String() } func buildResponse(status int, body string) string { bb := responsePool.Get() defer responsePool.Put(bb) fmt.Fprintf(bb, "HTTP/1.1 %d OK\r\nContent-Length: %d\r\n\r\n%s", status, len(body), body) return bb.String() } func main() { fmt.Println(buildJSON("name", "gopher")) // Output: {"name":"gopher"} fmt.Println(buildResponse(200, "Hello")) // Output: HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello } ``` -------------------------------- ### (*ByteBuffer).ReadFrom Source: https://context7.com/valyala/bytebufferpool/llms.txt Implements io.ReaderFrom, reading all available data from an io.Reader and appending it to the buffer. The buffer's capacity is doubled as needed, and existing content is preserved. ```APIDOC ## (*ByteBuffer).ReadFrom(r io.Reader) (int64, error) ### Description Implements `io.ReaderFrom`, reading all available data from `r` and appending it to the buffer. Doubles the internal buffer capacity as needed. Existing content in the buffer is preserved; data is appended, not replaced. ### Method `ReadFrom` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **r** (io.Reader) - The io.Reader to read data from. ``` -------------------------------- ### Process Request with Deferred Put Source: https://context7.com/valyala/bytebufferpool/llms.txt Demonstrates using `defer bytebufferpool.Put(bb)` to ensure a buffer is returned to the pool even if the function exits early. The buffer's content is copied to a string before `Put` is called. ```go package main import ( "fmt" "github.com/valyala/bytebufferpool" ) func processRequest(data []byte) string { bb := bytebufferpool.Get() defer bytebufferpool.Put(bb) // safe: defer ensures return even on early exit bb.Write(data) bb.WriteString(" [processed]") result := bb.String() // copy to string before Put fmt.Printf("Buffer length: %d\n", bb.Len()) return result // bb is returned to the pool when the function exits } func main() { out := processRequest([]byte("request payload")) fmt.Println(out) // Output: request payload [processed] } ``` -------------------------------- ### Read from io.Reader into ByteBuffer Source: https://context7.com/valyala/bytebufferpool/llms.txt Implements io.ReaderFrom to read all data from an io.Reader and append it to the buffer. Doubles capacity as needed and preserves existing content. ```go package main import ( "fmt" "net/http" "github.com/valyala/bytebufferpool" ) func fetchURL(url string) (string, error) { resp, err := http.Get(url) if err != nil { return "", err } defer resp.Body.Close() bb := bytebufferpool.Get() defer bytebufferpool.Put(bb) if _, err := bb.ReadFrom(resp.Body); err != nil { return "", err } return bb.String(), nil } func main() { body, err := fetchURL("https://example.com") if err != nil { fmt.Printf("Error: %v\n", err) return } fmt.Printf("Read %d bytes\n", len(body)) } ``` -------------------------------- ### (*ByteBuffer).Write Source: https://context7.com/valyala/bytebufferpool/llms.txt Implements the io.Writer interface, appending a byte slice to the buffer. This allows the ByteBuffer to be used with functions expecting an io.Writer. ```APIDOC ## (*ByteBuffer).Write(p []byte) (int, error) ### Description Implements the `io.Writer` interface, appending `p` to the buffer. This makes `*ByteBuffer` compatible with any function that accepts an `io.Writer`, such as `fmt.Fprintf`, `json.NewEncoder`, and `template.Execute`. ### Method `Write` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **p** ([]byte) - The byte slice to append. ``` -------------------------------- ### Write to ByteBuffer using io.Writer Source: https://context7.com/valyala/bytebufferpool/llms.txt Implements the io.Writer interface to append data. Compatible with functions accepting io.Writer like fmt.Fprintf and json.NewEncoder. ```go package main import ( "encoding/json" "fmt" "github.com/valyala/bytebufferpool" ) type User struct { Name string `json:"name"` Email string `json:"email"` } func main() { bb := bytebufferpool.Get() defer bytebufferpool.Put(bb) user := User{Name: "Alice", Email: "alice@example.com"} enc := json.NewEncoder(bb) // ByteBuffer satisfies io.Writer if err := enc.Encode(user); err != nil { panic(err) } fmt.Printf("JSON: %s", bb.String()) // Output: JSON: {"name":"Alice","email":"alice@example.com"} fmt.Fprintf(bb, "Extra: %d bytes total\n", bb.Len()) fmt.Print(bb.String()) } ``` -------------------------------- ### Replace ByteBuffer contents with Set/SetString Source: https://context7.com/valyala/bytebufferpool/llms.txt Replaces the entire buffer content with new data, reusing allocated capacity. Equivalent to Reset followed by append. ```go package main import ( "fmt" "github.com/valyala/bytebufferpool" ) func main() { bb := bytebufferpool.Get() defer bytebufferpool.Put(bb) bb.SetString("initial content") fmt.Println(bb.String()) // initial content fmt.Println(bb.Len()) // 15 // Replace with new content — no new allocation if capacity is sufficient bb.SetString("replaced") fmt.Println(bb.String()) // replaced fmt.Println(bb.Len()) // 8 bb.Set([]byte{0x47, 0x6f}) // "Go" fmt.Println(bb.String()) // Go } ``` -------------------------------- ### Write ByteBuffer contents to io.Writer Source: https://context7.com/valyala/bytebufferpool/llms.txt Implements io.WriterTo to write the entire buffer contents to a given io.Writer. Returns the number of bytes written and any error. ```go package main import ( "fmt" "net/http" "github.com/valyala/bytebufferpool" ) func writeResponse(w http.ResponseWriter, r *http.Request) { bb := bytebufferpool.Get() defer bytebufferpool.Put(bb) // Build response into the buffer first bb.WriteString("") fmt.Fprintf(bb, "

Path: %s

", r.URL.Path) bb.WriteString("") w.Header().Set("Content-Type", "text/html") // Write the entire buffer to the response writer in one call bb.WriteTo(w) } ``` -------------------------------- ### Append String to ByteBuffer Source: https://context7.com/valyala/bytebufferpool/llms.txt Appends a string to a `ByteBuffer` using the `WriteString` method. The method returns the number of bytes written and a nil error, compatible with `io.Writer`. ```go package main import ( "fmt" "github.com/valyala/bytebufferpool" ) func main() { bb := bytebufferpool.Get() defer bytebufferpool.Put(bb) n, _ := bb.WriteString("line one\n") fmt.Printf("Wrote %d bytes\n", n) // Wrote 9 bytes bb.WriteString("line two\n") bb.WriteString("line three\n") fmt.Print(bb.String()) // Output: // line one // line two // line three } ``` -------------------------------- ### Put(b *ByteBuffer) Source: https://context7.com/valyala/bytebufferpool/llms.txt Releases a *ByteBuffer back to the package-level default pool. The buffer is reset before being stored. Buffers exceeding the pool's maximum size are discarded. Never access the buffer after calling Put. ```APIDOC ## Put(b *ByteBuffer) ### Description Releases a `*ByteBuffer` back to the package-level default pool. The buffer is reset (its `B` slice is set to zero length) before being stored. If the buffer's capacity exceeds the pool's calibrated maximum size, it is discarded rather than pooled to prevent memory waste. **Never access the buffer after calling `Put`.** ### Method `Put(b *ByteBuffer)` ### Parameters - **b** (*ByteBuffer) - Required - The byte buffer to release. ### Request Example ```go package main import ( "github.com/valyala/bytebufferpool" ) func main() { bb := bytebufferpool.Get() // ... use bb ... bytebufferpool.Put(bb) } ``` ### Response None (This is a procedure to return a buffer to the pool). ``` -------------------------------- ### (*ByteBuffer).Set / (*ByteBuffer).SetString Source: https://context7.com/valyala/bytebufferpool/llms.txt Replaces the buffer's entire contents with the provided byte slice or string. This operation reuses the underlying allocated capacity, behaving like a Reset followed by an append. ```APIDOC ## (*ByteBuffer).Set(p []byte) / (*ByteBuffer).SetString(s string) ### Description Replaces the buffer's entire contents with `p` or `s`, reusing the underlying allocated capacity rather than allocating a new slice. Equivalent to a `Reset` followed by an `append`. ### Method `Set` or `SetString` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **p** ([]byte) - The byte slice to set as the buffer's content. - **s** (string) - The string to set as the buffer's content. ``` -------------------------------- ### (*ByteBuffer).WriteTo Source: https://context7.com/valyala/bytebufferpool/llms.txt Implements io.WriterTo, writing the full contents of the buffer to a given io.Writer. Returns the number of bytes written and any write error encountered. ```APIDOC ## (*ByteBuffer).WriteTo(w io.Writer) (int64, error) ### Description Implements `io.WriterTo`, writing the full contents of the buffer to the given writer. Returns the number of bytes written and any write error. ### Method `WriteTo` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **w** (io.Writer) - The io.Writer to write the buffer's contents to. ``` -------------------------------- ### (*ByteBuffer).Reset Source: https://context7.com/valyala/bytebufferpool/llms.txt Clears the buffer by setting its length to zero without releasing the underlying memory, making the buffer ready for immediate reuse. ```APIDOC ## (*ByteBuffer).Reset() ### Description Sets the buffer length to zero without releasing the underlying memory, making the buffer ready for reuse. This is automatically called by `Put` before the buffer is stored back in the pool. ### Method `Reset` ### Parameters None ``` -------------------------------- ### Reset ByteBuffer to zero length Source: https://context7.com/valyala/bytebufferpool/llms.txt Sets the buffer length to zero without releasing memory, preparing it for reuse. Automatically called by Put. ```go package main import ( "fmt" "github.com/valyala/bytebufferpool" ) func main() { bb := bytebufferpool.Get() defer bytebufferpool.Put(bb) bb.WriteString("temporary data") fmt.Println(bb.Len()) // 14 bb.Reset() fmt.Println(bb.Len()) // 0 fmt.Println(bb.String()) // "" // Capacity is retained — the next write won't allocate bb.WriteString("reused buffer") fmt.Println(bb.String()) // reused buffer } ``` -------------------------------- ### (*ByteBuffer).WriteString(s string) (int, error) Source: https://context7.com/valyala/bytebufferpool/llms.txt Appends a string to the buffer by extending the underlying B slice. Returns the number of bytes written and a nil error. ```APIDOC ## (*ByteBuffer).WriteString(s string) (int, error) ### Description Appends a string to the buffer by extending the underlying `B` slice. Returns the number of bytes written and a nil error (error is always nil, provided for `io.Writer` compatibility). ### Method `WriteString(s string)` ### Parameters - **s** (string) - Required - The string to append to the buffer. ### Request Example ```go package main import ( "fmt" "github.com/valyala/bytebufferpool" ) func main() { bb := bytebufferpool.Get() defer bytebufferpool.Put(bb) n, _ := bb.WriteString("Hello ") fmt.Printf("Wrote %d bytes\n", n) // Wrote 6 bytes bb.WriteString("world!") fmt.Println(bb.String()) } ``` ### Response #### Success Response (Tuple) - **int** - The number of bytes written. - **error** - Always nil for this method. ### Response Example ```go // Example return values (6, nil) ``` ``` -------------------------------- ### Pool Source: https://context7.com/valyala/bytebufferpool/llms.txt Represents an independent byte buffer pool that can be created and tuned separately from the default pool. Use distinct Pool instances for different buffer types. ```APIDOC ## Pool ### Description A `Pool` is an independent byte buffer pool that can be created and tuned separately from the default pool. Use distinct `Pool` instances for logically different buffer types (e.g., small vs. large buffers) to improve calibration accuracy and reduce memory waste. ### Methods - **Get() *ByteBuffer**: Obtains a buffer from this specific pool instance. - **Put(b *ByteBuffer)**: Releases a buffer back to this specific pool instance. ### Request Example ```go package main import ( "fmt" "github.com/valyala/bytebufferpool" ) var jsonPool bytebufferpool.Pool func buildJSON(key, value string) string { bb := jsonPool.Get() defer jsonPool.Put(bb) bb.WriteString(`{"`) // Example usage of Get and Put on a custom pool bb.WriteString(key) bb.WriteString(`":"`) bb.WriteString(value) bb.WriteString(`"}`) return bb.String() } ``` ``` -------------------------------- ### (*ByteBuffer).Len Source: https://context7.com/valyala/bytebufferpool/llms.txt Returns the current number of bytes held in the buffer. This is useful for size checks or setting content-length headers without converting the buffer to a string. ```APIDOC ## (*ByteBuffer).Len() int ### Description Returns the number of bytes currently held in the buffer. Useful for size checks and content-length headers without converting to a string. ### Method `Len` ### Parameters None ### Returns - **int** - The current length of the buffer in bytes. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.