bufpool

package
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 6 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package bufpool recycles off-heap byte buffers of power-of-two sizes, for I/O and decoding that would otherwise churn []byte through the Go heap.

Sizes start at 4 KiB, and every buffer is aligned to its size up to the operating system's page, which direct I/O and registered ring buffers need. Contents of a buffer are undefined when handed out, because the point is not paying to clear what a read is about to overwrite.

Example
package main

import (
	"fmt"

	memory "github.com/stubbedev/memory-go"
	"github.com/stubbedev/memory-go/bufpool"
)

func main() {
	var a memory.Local
	defer a.Close()

	p, err := bufpool.New(&a, 1<<20)
	if err != nil {
		panic(err)
	}
	b, err := p.Get(5000)
	if err != nil {
		panic(err)
	}
	fmt.Println(len(b.Bytes()), b.Cap())
	if err := p.Put(b); err != nil {
		panic(err)
	}
}
Output:
5000 8192

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrForeign = errors.New("buffer is not checked out of this pool")

ErrForeign reports a Buf that did not come from this pool or was put back already.

Functions

This section is empty.

Types

type Buf

type Buf struct {
	// contains filtered or unexported fields
}

Buf is a buffer checked out of a Pool. It may be stored off-heap.

func (Buf) Bytes

func (b Buf) Bytes() []byte

Bytes returns the buffer with the length asked for and room up to Cap, valid until Put.

func (Buf) Cap

func (b Buf) Cap() int

Cap returns the size of the buffer.

type Pool

type Pool struct {
	// contains filtered or unexported fields
}

Pool hands out buffers and keeps returned ones for reuse, up to a limit. It is safe for concurrent use if its allocator is a Shared.

func New

func New(a memory.Allocator, maxRetained int) (*Pool, error)

New returns a Pool keeping at most maxRetained bytes of returned buffers.

func (*Pool) Get

func (p *Pool) Get(n int) (Buf, error)

Get returns a buffer of length n with undefined contents. Requests too large to pool are allocated and freed directly.

func (*Pool) Put

func (p *Pool) Put(b Buf) error

Put returns b to p, invalidating it. Putting a Buf back twice, or one with a size p never hands out, returns ErrForeign.

func (*Pool) Trim

func (p *Pool) Trim() error

Trim frees every retained buffer.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL