gpool

package
v0.9.2 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2023 License: MIT Imports: 1 Imported by: 1

Documentation

Overview

Package gpool provides "advanced" version of sync.Pool. Supports generics (which is its biggest advantage) and 2 handlers that let you decide what to do if pointer is acquired or returned.

There is also Discard function that gives you control when pointer should be rejected when calling Pool.Put, so it won't be used again. It's useful if you want to remove (for example) buffers that have grown over the limit.

IMPORTANT: By default, Pool will set pointer to zero value of generic provided during initialization. It can be disabled by declaring OnInit handler. It's also important when using pooling for buffers!

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Option

type Option[V any] func(opts *options[V])

func Discard

func Discard[V any](fn func(*V) bool) Option[V]

func OnInit

func OnInit[V any](fn func(*V)) Option[V]

func OnPut

func OnPut[V any](fn func(*V)) Option[V]

type Pool

type Pool[V any] struct {
	// contains filtered or unexported fields
}

func New

func New[V any](opts ...Option[V]) *Pool[V]
Example (Buffers)
// declare pool of bytes.Buffer
pool := New[bytes.Buffer](
	// OnInit function is triggered only if new pointer has been allocated
	OnInit[bytes.Buffer](func(b *bytes.Buffer) {
		// increase buffer size by 1024 bytes to limit future allocations
		b.Grow(1024)
	}),
	OnPut[bytes.Buffer](func(b *bytes.Buffer) {
		// reset buffer for future use, so you don't have to worry about it after calling Pool.Get
		b.Reset()
	}),
)

// simple example of using bytes.Buffer with pooling

buff := pool.Get()
buff.WriteString("Hello World!")
pool.Put(buff)
Example (Simple)
// declare pool of ints
pool := New[int]()
// allocate new pointer or reuse if available
ptr := pool.Get()

/*
	do things with this pointer
*/

// put pointer back to pool
pool.Put(ptr)
// pointer can be reused. Do not use pointer after calling Put method!

func (*Pool[V]) Get

func (p *Pool[V]) Get() *V

func (*Pool[V]) Put

func (p *Pool[V]) Put(x *V)

Jump to

Keyboard shortcuts

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