### 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, "