fastalloc

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2025 License: Apache-2.0, MIT Imports: 8 Imported by: 0

Documentation

Overview

purpose: fastalloc is a high-performance memory pool library that helps you reuse objects

instead of creating new ones every time, which reduces garbage collection and speeds up your program.

this library gives you several types of pools to choose from:

- generic pool: a flexible pool that works with any type using Go generics - fixed pool: a pool with a set size that never grows or shrinks - growing pool: a pool that gets bigger when you need more items and smaller when idle - sync pool: wraps Go's sync.Pool with extra features like metrics - sharded pool: splits items across multiple pools to reduce contention

basic usage:

type Request struct {
    ID   string
    Data []byte
}

pool := fastalloc.NewPool[*Request](fastalloc.Config{
    InitialCapacity: 100,
    New: func() *Request {
        return &Request{Data: make([]byte, 0, 4096)}
    },
    Reset: func(r *Request) {
        r.ID = ""
        r.Data = r.Data[:0]
    },
})

// get an item from the pool
req := pool.Get()
req.ID = "123"

// use the request...

// return it to the pool
pool.Put(req)

builder pattern:

pool := fastalloc.NewPoolBuilder[*Buffer]().
    WithInitialCapacity(100).
    WithMaxCapacity(1000).
    WithConstructor(NewBuffer).
    WithReset(ResetBuffer).
    WithMetrics(true).
    Build()

functional options:

pool := fastalloc.NewPoolWithOptions(
    NewBuffer,
    fastalloc.WithInitialCapacity[*Buffer](100),
    fastalloc.WithMaxCapacity[*Buffer](1000),
    fastalloc.WithMetrics[*Buffer](true),
)

performance:

fastalloc is designed to be faster than creating new objects and can reduce garbage collection pressure significantly. it uses lock-free algorithms where possible and supports sharding to minimize contention in highly concurrent scenarios.

the library has zero external dependencies in its core and works with Go 1.18+.

Index

Constants

This section is empty.

Variables

View Source
var ErrCapacityExceeded = errors.New("capacity exceeded maximum limit")

purpose: tells us when we ask for more capacity than the pool's maximum limit params: none (this is an error constant) args: n/a returns: n/a raises: n/a

View Source
var ErrClosed = errors.New("pool is closed")

purpose: tells us when we try to use a pool that has been closed and shut down params: none (this is an error constant) args: n/a returns: n/a raises: n/a

View Source
var ErrInvalidCapacity = errors.New("capacity must be positive")

purpose: tells us when we try to create a pool with a negative or zero capacity params: none (this is an error constant) args: n/a returns: n/a raises: n/a

View Source
var ErrInvalidConfiguration = errors.New("invalid pool configuration")

purpose: tells us when we try to create a pool with bad settings that don't make sense params: none (this is an error constant) args: n/a returns: n/a raises: n/a

View Source
var ErrMissingConstructor = errors.New("constructor function is required")

purpose: tells us when we forget to provide a constructor function (New) for creating items params: none (this is an error constant) args: n/a returns: n/a raises: n/a

View Source
var ErrPoolExhausted = errors.New("pool exhausted: no items available")

purpose: tells us when the pool is completely full or exhausted and can't give us any items params: none (this is an error constant) args: n/a returns: n/a raises: n/a

View Source
var ErrTimeout = errors.New("timeout waiting for item")

purpose: tells us when a timeout expires while waiting for an item to become available params: none (this is an error constant) args: n/a returns: n/a raises: n/a

View Source
var ErrValidationFailed = errors.New("item validation failed")

purpose: tells us when an item failed our health check and was rejected from the pool params: none (this is an error constant) args: n/a returns: n/a raises: n/a

Functions

This section is empty.

Types

type Config

type Config[T any] struct {
	// purpose: how many items to create when the pool starts
	InitialCapacity int

	// purpose: the maximum number of items the pool can ever hold (0 means unlimited)
	MaxCapacity int

	// purpose: function that creates a brand new item from scratch
	New func() T

	// purpose: function that cleans up an item when it comes back to the pool
	Reset func(T)

	// purpose: function that checks if an item is still good to use
	Validate func(T) bool

	// purpose: function that destroys an item when we don't need it anymore
	Destructor func(T)

	// purpose: function to check if an item is healthy and working properly
	HealthCheck func(T) bool

	// purpose: how long items can sit unused before we shrink the pool
	IdleTimeout time.Duration

	// purpose: which growth strategy to use when pool needs more capacity
	GrowthStrategy GrowthStrategy

	// purpose: for linear growth, how many items to add each time
	LinearGrowthStep int

	// purpose: custom growth function if using GrowthCustom strategy
	CustomGrowthFunc func(currentCapacity int) int

	// purpose: should we create all items at startup or wait until needed
	EagerWarmup bool

	// purpose: should we collect detailed metrics about pool performance
	Metrics bool

	// purpose: for sharded pools, how many shards to create
	ShardCount int
}

purpose: all the settings we can configure for our pool - like a recipe for how to build it params: none (this is a type definition) args: n/a returns: n/a raises: n/a

func DefaultConfig

func DefaultConfig[T any](constructor func() T) Config[T]

purpose: creates a default configuration with sensible settings to get you started quickly params: constructor func() T - the function to create new items args: sets up a config with reasonable defaults and the provided constructor returns: Config[T] - a ready-to-use configuration raises: none

func (*Config[T]) ValidateConfig

func (c *Config[T]) ValidateConfig() error

purpose: checks if the configuration has valid settings that make sense params: none args: examines each setting to ensure it's reasonable returns: error - describes what's wrong, or nil if everything is good raises: ErrInvalidCapacity, ErrMissingConstructor, ErrInvalidConfiguration

type FixedPool

type FixedPool[T any] struct {
	// contains filtered or unexported fields
}

purpose: a pool with a fixed size that never grows or shrinks - like a parking lot with

exactly N spots, no more and no less

params: none (this is a type definition) args: n/a returns: n/a raises: n/a

func NewFixedPool

func NewFixedPool[T any](cfg Config[T]) (*FixedPool[T], error)

purpose: creates a new fixed-size pool with exact capacity params: cfg Config[T] - configuration settings args: validates config, creates fixed storage, optionally pre-fills with items returns: (*FixedPool[T], error) - the pool or an error raises: ErrInvalidConfiguration, ErrInvalidCapacity, ErrMissingConstructor

func (*FixedPool[T]) Close

func (p *FixedPool[T]) Close() error

purpose: closes the pool params: none args: marks closed, cleans up items returns: error raises: ErrClosed

func (*FixedPool[T]) Get

func (p *FixedPool[T]) Get() T

purpose: gets an item, implementing the Pool interface (panics if exhausted) params: none args: calls GetWithError and panics on error returns: item T raises: panics if pool exhausted

func (*FixedPool[T]) GetBlocking

func (p *FixedPool[T]) GetBlocking(ctx context.Context) (T, error)

purpose: gets an item from the pool, blocking until one is available params: ctx context.Context - allows cancellation and timeout args: waits for an item to be returned to pool if empty returns: (item T, error) - the item or context error raises: ErrClosed, ErrTimeout, context errors

func (*FixedPool[T]) GetWithError

func (p *FixedPool[T]) GetWithError() (T, error)

purpose: gets an item from the pool, returns error if pool is empty params: none args: tries to get from pool, creates new if empty (which means exceeded capacity) returns: (item T, error) - the item or ErrPoolExhausted raises: ErrPoolExhausted, ErrClosed

func (*FixedPool[T]) Put

func (p *FixedPool[T]) Put(item T)

purpose: returns an item to the pool params: item T - what we're returning args: resets, validates, stores back returns: none raises: none

func (*FixedPool[T]) Stats

func (p *FixedPool[T]) Stats() PoolStats

purpose: gets current statistics params: none args: collects all metrics returns: PoolStats raises: none

type GenericPool

type GenericPool[T any] struct {
	// contains filtered or unexported fields
}

purpose: a type-safe pool that uses Go generics to store and reuse items of any type

without the performance cost of interface casting

params: none (this is a type definition) args: n/a returns: n/a raises: n/a

func NewPool

func NewPool[T any](cfg Config[T]) (*GenericPool[T], error)

purpose: creates a brand new generic pool with the settings you provide params: cfg Config[T] - all the settings for how the pool should work args: validates the config, sets up storage, optionally warms up with initial items returns: (*GenericPool[T], error) - the new pool or an error if config is bad raises: ErrInvalidConfiguration, ErrInvalidCapacity, ErrMissingConstructor

func (*GenericPool[T]) Close

func (p *GenericPool[T]) Close() error

purpose: shuts down the pool and cleans up all resources params: none args: marks as closed, drains items, runs destructors on each returns: error - nil on success, ErrClosed if already closed raises: ErrClosed

func (*GenericPool[T]) Get

func (p *GenericPool[T]) Get() T

purpose: borrows an item from the pool or creates a new one if pool is empty params: none args: tries to get from pool first, if empty creates new, tracks metrics returns: item T - the item you can use raises: none (always returns an item)

func (*GenericPool[T]) Put

func (p *GenericPool[T]) Put(item T)

purpose: returns an item back to the pool after you're done with it params: item T - the item you're giving back args: resets the item, validates it if needed, stores it back in the pool returns: none raises: none

func (*GenericPool[T]) Stats

func (p *GenericPool[T]) Stats() PoolStats

purpose: gets a snapshot of how the pool is performing right now params: none args: gathers all counters and calculates derived metrics returns: PoolStats - current pool statistics raises: none

type GrowingPool

type GrowingPool[T any] struct {
	// contains filtered or unexported fields
}

purpose: a pool that can grow bigger when needed and shrink when idle - like a balloon

that expands when you need more space and deflates when you don't

params: none (this is a type definition) args: n/a returns: n/a raises: n/a

func NewGrowingPool

func NewGrowingPool[T any](cfg Config[T]) (*GrowingPool[T], error)

purpose: creates a new growing pool that can expand and contract params: cfg Config[T] - configuration settings args: validates config, sets up initial storage, starts shrink monitor if idle timeout set returns: (*GrowingPool[T], error) - the pool or an error raises: ErrInvalidConfiguration, ErrInvalidCapacity, ErrMissingConstructor

func (*GrowingPool[T]) Close

func (p *GrowingPool[T]) Close() error

purpose: closes the pool params: none args: stops shrink monitor, cleans up items returns: error raises: ErrClosed

func (*GrowingPool[T]) Get

func (p *GrowingPool[T]) Get() T

purpose: gets an item from pool, growing if necessary params: none args: tries to get existing item, creates new if empty, may grow capacity returns: item T raises: none

func (*GrowingPool[T]) Put

func (p *GrowingPool[T]) Put(item T)

purpose: returns item to pool params: item T - what we're returning args: resets, validates, stores back or grows if needed returns: none raises: none

func (*GrowingPool[T]) Stats

func (p *GrowingPool[T]) Stats() PoolStats

purpose: gets current statistics params: none args: collects all metrics returns: PoolStats raises: none

type GrowthStrategy

type GrowthStrategy int

purpose: defines how we want our pool to grow when it needs more items - like choosing

between adding one at a time, doubling the size, or using a custom formula

params: none (this is a type definition) args: n/a returns: n/a raises: n/a

const (
	// purpose: pool never grows beyond initial capacity
	GrowthNone GrowthStrategy = iota

	// purpose: pool grows by adding a fixed number of items each time
	GrowthLinear

	// purpose: pool doubles in size each time it grows
	GrowthDouble

	// purpose: pool uses a custom function to decide growth
	GrowthCustom
)

type Option

type Option[T any] func(*Config[T])

purpose: a function that modifies pool configuration - this is the functional options pattern

where each option is a function that tweaks the settings

params: none (this is a type definition) args: n/a returns: n/a raises: n/a

func WithDestructor

func WithDestructor[T any](destructor func(T)) Option[T]

purpose: creates an option that sets the destructor function params: destructor func(T) - function to destroy items args: returns a function that sets this value returns: Option[T] - an option function raises: none

func WithEagerWarmup

func WithEagerWarmup[T any]() Option[T]

purpose: creates an option that enables eager warmup params: none args: returns a function that enables warmup returns: Option[T] - an option function raises: none

func WithGrowthStrategy

func WithGrowthStrategy[T any](strategy GrowthStrategy) Option[T]

purpose: creates an option that sets growth strategy params: strategy GrowthStrategy - how to grow the pool args: returns a function that sets this value returns: Option[T] - an option function raises: none

func WithHealthCheck

func WithHealthCheck[T any](healthCheck func(T) bool) Option[T]

purpose: creates an option that sets the health check function params: healthCheck func(T) bool - function to check health args: returns a function that sets this value returns: Option[T] - an option function raises: none

func WithIdleTimeout

func WithIdleTimeout[T any](timeout time.Duration) Option[T]

purpose: creates an option that sets idle timeout params: timeout time.Duration - how long to wait before shrinking args: returns a function that sets this value returns: Option[T] - an option function raises: none

func WithInitialCapacity

func WithInitialCapacity[T any](capacity int) Option[T]

purpose: creates an option that sets initial capacity params: capacity int - how many items to start with args: returns a function that sets this value returns: Option[T] - an option function raises: none

func WithMaxCapacity

func WithMaxCapacity[T any](capacity int) Option[T]

purpose: creates an option that sets maximum capacity params: capacity int - max items allowed args: returns a function that sets this value returns: Option[T] - an option function raises: none

func WithMetrics

func WithMetrics[T any](enabled bool) Option[T]

purpose: creates an option that enables or disables metrics params: enabled bool - whether to collect metrics args: returns a function that sets this value returns: Option[T] - an option function raises: none

func WithReset

func WithReset[T any](reset func(T)) Option[T]

purpose: creates an option that sets the reset function params: reset func(T) - function to clean items args: returns a function that sets this value returns: Option[T] - an option function raises: none

func WithValidate

func WithValidate[T any](validate func(T) bool) Option[T]

purpose: creates an option that sets the validation function params: validate func(T) bool - function to check items args: returns a function that sets this value returns: Option[T] - an option function raises: none

type Pool

type Pool[T any] interface {
	// purpose: borrows an item from the pool so you can use it
	// params: none
	// args: n/a
	// returns: item T - the item you can use
	// raises: may panic or return zero value if pool is exhausted (depends on implementation)
	Get() T

	// purpose: returns an item back to the pool when you're done with it
	// params: item T - the item you're giving back
	// args: resets and stores the item for future use
	// returns: none
	// raises: none
	Put(item T)

	// purpose: gets current statistics about how the pool is performing
	// params: none
	// args: gathers and calculates all the interesting numbers
	// returns: PoolStats - snapshot of pool performance
	// raises: none
	Stats() PoolStats

	// purpose: shuts down the pool and releases all resources
	// params: none
	// args: runs destructors, stops background tasks, cleans everything up
	// returns: error - if something went wrong during shutdown
	// raises: ErrClosed if already closed
	Close() error
}

purpose: this is the main blueprint that all our different pool types follow - it defines

the basic operations any pool must support like getting items, returning them, and checking stats

params: none (this is an interface) args: n/a returns: n/a raises: n/a

func NewPoolWithOptions

func NewPoolWithOptions[T any](constructor func() T, opts ...Option[T]) (Pool[T], error)

purpose: creates a pool using functional options pattern params: constructor func() T - function to create items

opts ...Option[T] - variable number of options

args: applies each option to a default config, then creates pool returns: (Pool[T], error) - the pool or an error raises: ErrInvalidConfiguration, ErrInvalidCapacity, ErrMissingConstructor

type PoolBuilder

type PoolBuilder[T any] struct {
	// contains filtered or unexported fields
}

purpose: a helper that lets us build a pool configuration step-by-step using a fluent style,

like building with lego blocks where each method adds another piece

params: none (this is a type definition) args: n/a returns: n/a raises: n/a

func NewPoolBuilder

func NewPoolBuilder[T any]() *PoolBuilder[T]

purpose: starts building a new pool configuration params: none args: creates a builder with default settings returns: pointer to PoolBuilder - ready to chain methods raises: none

func (*PoolBuilder[T]) Build

func (pb *PoolBuilder[T]) Build() (Pool[T], error)

purpose: finishes building and creates the actual pool params: none args: validates config and creates a generic pool returns: (Pool[T], error) - the pool or an error if config is invalid raises: ErrInvalidConfiguration, ErrInvalidCapacity, ErrMissingConstructor

func (*PoolBuilder[T]) BuildFixed

func (pb *PoolBuilder[T]) BuildFixed() (Pool[T], error)

purpose: builds a fixed-size pool instead of a growing one params: none args: validates config and creates a fixed pool returns: (Pool[T], error) - the pool or an error raises: ErrInvalidConfiguration, ErrInvalidCapacity, ErrMissingConstructor

func (*PoolBuilder[T]) BuildGrowing

func (pb *PoolBuilder[T]) BuildGrowing() (Pool[T], error)

purpose: builds a growing pool that can expand and shrink params: none args: validates config and creates a growing pool returns: (Pool[T], error) - the pool or an error raises: ErrInvalidConfiguration, ErrInvalidCapacity, ErrMissingConstructor

func (*PoolBuilder[T]) BuildSharded

func (pb *PoolBuilder[T]) BuildSharded() (Pool[T], error)

purpose: builds a sharded pool with multiple sub-pools params: none args: validates config and creates a sharded pool returns: (Pool[T], error) - the pool or an error raises: ErrInvalidConfiguration, ErrInvalidCapacity, ErrMissingConstructor

func (*PoolBuilder[T]) WithConstructor

func (pb *PoolBuilder[T]) WithConstructor(constructor func() T) *PoolBuilder[T]

purpose: sets the function that creates new items params: constructor func() T - function to create items args: stores this in our config returns: self - for method chaining raises: none

func (*PoolBuilder[T]) WithCustomGrowth

func (pb *PoolBuilder[T]) WithCustomGrowth(growthFunc func(int) int) *PoolBuilder[T]

purpose: sets a custom function for calculating growth params: growthFunc func(int) int - function that decides new capacity args: stores this in our config and sets strategy to custom returns: self - for method chaining raises: none

func (*PoolBuilder[T]) WithDestructor

func (pb *PoolBuilder[T]) WithDestructor(destructor func(T)) *PoolBuilder[T]

purpose: sets the function that destroys items permanently params: destructor func(T) - function to destroy items args: stores this in our config returns: self - for method chaining raises: none

func (*PoolBuilder[T]) WithEagerWarmup

func (pb *PoolBuilder[T]) WithEagerWarmup(eager bool) *PoolBuilder[T]

purpose: sets whether to create all items at startup params: eager bool - true to warmup immediately args: stores this in our config returns: self - for method chaining raises: none

func (*PoolBuilder[T]) WithGrowthStrategy

func (pb *PoolBuilder[T]) WithGrowthStrategy(strategy GrowthStrategy) *PoolBuilder[T]

purpose: sets how the pool should grow when it needs more space params: strategy GrowthStrategy - the growth strategy to use args: stores this in our config returns: self - for method chaining raises: none

func (*PoolBuilder[T]) WithHealthCheck

func (pb *PoolBuilder[T]) WithHealthCheck(healthCheck func(T) bool) *PoolBuilder[T]

purpose: sets the function that checks if items are healthy params: healthCheck func(T) bool - function to check health args: stores this in our config returns: self - for method chaining raises: none

func (*PoolBuilder[T]) WithIdleTimeout

func (pb *PoolBuilder[T]) WithIdleTimeout(timeout time.Duration) *PoolBuilder[T]

purpose: sets how long items can sit idle before shrinking params: timeout time.Duration - idle timeout duration args: stores this in our config returns: self - for method chaining raises: none

func (*PoolBuilder[T]) WithInitialCapacity

func (pb *PoolBuilder[T]) WithInitialCapacity(capacity int) *PoolBuilder[T]

purpose: sets how many items the pool starts with params: capacity int - initial number of items args: stores this in our config returns: self - so we can chain more methods raises: none

func (*PoolBuilder[T]) WithLinearGrowthStep

func (pb *PoolBuilder[T]) WithLinearGrowthStep(step int) *PoolBuilder[T]

purpose: sets the step size for linear growth params: step int - how many items to add each growth args: stores this in our config returns: self - for method chaining raises: none

func (*PoolBuilder[T]) WithMaxCapacity

func (pb *PoolBuilder[T]) WithMaxCapacity(capacity int) *PoolBuilder[T]

purpose: sets the maximum number of items the pool can hold params: capacity int - max capacity (0 means unlimited) args: stores this in our config returns: self - for method chaining raises: none

func (*PoolBuilder[T]) WithMetrics

func (pb *PoolBuilder[T]) WithMetrics(enabled bool) *PoolBuilder[T]

purpose: sets whether to collect performance metrics params: enabled bool - true to enable metrics args: stores this in our config returns: self - for method chaining raises: none

func (*PoolBuilder[T]) WithReset

func (pb *PoolBuilder[T]) WithReset(reset func(T)) *PoolBuilder[T]

purpose: sets the function that cleans up items when returned params: reset func(T) - function to reset items args: stores this in our config returns: self - for method chaining raises: none

func (*PoolBuilder[T]) WithShardCount

func (pb *PoolBuilder[T]) WithShardCount(count int) *PoolBuilder[T]

purpose: sets how many shards to create (for sharded pools) params: count int - number of shards args: stores this in our config returns: self - for method chaining raises: none

func (*PoolBuilder[T]) WithValidate

func (pb *PoolBuilder[T]) WithValidate(validate func(T) bool) *PoolBuilder[T]

purpose: sets the function that validates items are still good params: validate func(T) bool - function to check items args: stores this in our config returns: self - for method chaining raises: none

type PoolStats

type PoolStats struct {
	// purpose: how many items are currently being used (borrowed from pool)
	InUse int

	// purpose: how many items can the pool hold in total
	Capacity int

	// purpose: how many times someone asked for an item (Get calls)
	Gets int64

	// purpose: how many times someone returned an item (Put calls)
	Puts int64

	// purpose: how many times we couldn't provide an item (pool was empty)
	Misses int64

	// purpose: what fraction of Get requests found items (0.0 to 1.0, where 1.0 = 100%)
	HitRate float64

	// purpose: how many times the pool shrank to save memory
	Shrinks int64

	// purpose: how many times the pool grew to hold more items
	Grows int64

	// purpose: total number of new items created from scratch
	Allocated int64

	// purpose: total number of items reused from the pool
	Recycled int64

	// purpose: when was the last garbage collection cycle
	LastGC time.Time

	// purpose: how many shards does this pool have (for sharded pools)
	Shards int

	// purpose: how many goroutines are currently waiting for an item
	Waiters int

	// purpose: how long has this pool been running
	Uptime time.Duration
}

purpose: holds all the interesting numbers and statistics about how our pool is performing,

like how many items we're using, how often we find items, and memory usage

params: none (this is a type definition) args: n/a returns: n/a raises: n/a

func (*PoolStats) AllocationSavings

func (ps *PoolStats) AllocationSavings() float64

purpose: calculates how much the pool has saved us from allocations params: none args: computes the ratio of recycled to allocated items returns: savings float64 - higher means more savings (e.g., 0.9 = 90% recycled) raises: none

func (*PoolStats) Available

func (ps *PoolStats) Available() int

purpose: tells us how many items are available to be borrowed right now params: none args: subtracts in-use items from total capacity returns: available int - number of items sitting in the pool ready to use raises: none

func (*PoolStats) IsHealthy

func (ps *PoolStats) IsHealthy(threshold float64) bool

purpose: checks if this pool has good performance by looking at its hit rate params: threshold float64 - the minimum hit rate we consider healthy (like 0.8 for 80%) args: compares our actual hit rate to the threshold returns: healthy bool - true if we're meeting or exceeding the threshold raises: none

func (*PoolStats) TotalOperations

func (ps *PoolStats) TotalOperations() int64

purpose: calculates the total number of operations performed params: none args: adds up all gets and puts returns: operations int64 - total operations raises: none

func (*PoolStats) Utilization

func (ps *PoolStats) Utilization() float64

purpose: calculates what percentage of pool capacity is currently in use params: none args: divides items in use by total capacity returns: utilization float64 - a number from 0.0 to 1.0 showing how full the pool is raises: none

type ShardConfig

type ShardConfig[T any] struct {
	// purpose: base configuration for each shard
	BaseConfig Config[T]

	// purpose: how many shards to create (if 0, uses GOMAXPROCS)
	ShardCount int
}

purpose: configuration specific to sharded pools params: none (this is a type definition) args: n/a returns: n/a raises: n/a

type ShardedPool

type ShardedPool[T any] struct {
	// contains filtered or unexported fields
}

purpose: a pool split into multiple smaller pools (shards) to reduce contention when many

goroutines are competing for items - like having multiple checkout lanes instead of one

params: none (this is a type definition) args: n/a returns: n/a raises: n/a

func NewShardedPool

func NewShardedPool[T any](cfg ShardConfig[T]) (*ShardedPool[T], error)

purpose: creates a new sharded pool with multiple sub-pools params: cfg ShardConfig[T] - configuration including shard count args: validates config, creates each shard as an individual pool returns: (*ShardedPool[T], error) - the sharded pool or an error raises: ErrInvalidConfiguration

func (*ShardedPool[T]) Close

func (sp *ShardedPool[T]) Close() error

purpose: closes all shards params: none args: closes each shard individually returns: error raises: ErrClosed

func (*ShardedPool[T]) Get

func (sp *ShardedPool[T]) Get() T

purpose: gets an item from one of the shards params: none args: picks a shard and gets item from it returns: item T raises: none

func (*ShardedPool[T]) Put

func (sp *ShardedPool[T]) Put(item T)

purpose: returns item to one of the shards params: item T - what we're returning args: picks a shard and returns item to it returns: none raises: none

func (*ShardedPool[T]) Stats

func (sp *ShardedPool[T]) Stats() PoolStats

purpose: aggregates statistics across all shards params: none args: collects stats from each shard and sums them returns: PoolStats raises: none

type SyncConfig

type SyncConfig[T any] struct {
	// purpose: function to create new items
	New func() T

	// purpose: function to reset items
	Reset func(T)

	// purpose: optional capacity limit (0 means unlimited)
	MaxCapacity int

	// purpose: whether to collect metrics
	Metrics bool
}

purpose: configuration for sync.Pool wrapper params: none (this is a type definition) args: n/a returns: n/a raises: n/a

type SyncPool

type SyncPool[T any] struct {
	// contains filtered or unexported fields
}

purpose: wraps Go's built-in sync.Pool with extra features like size limits and metrics,

giving us the speed of sync.Pool with more control and visibility

params: none (this is a type definition) args: n/a returns: n/a raises: n/a

func NewSyncPool

func NewSyncPool[T any](cfg SyncConfig[T]) (*SyncPool[T], error)

purpose: creates a new sync.Pool wrapper with enhanced features params: cfg SyncConfig[T] - configuration for the pool args: sets up sync.Pool with constructor, initializes metrics returns: (*SyncPool[T], error) - the pool or an error raises: ErrMissingConstructor if no constructor provided

func (*SyncPool[T]) Close

func (sp *SyncPool[T]) Close() error

purpose: closes the pool params: none args: marks as closed returns: error raises: ErrClosed

func (*SyncPool[T]) Get

func (sp *SyncPool[T]) Get() T

purpose: gets an item from the sync pool params: none args: tries to get from sync.Pool, tracks metrics, enforces capacity limits returns: item T raises: none

func (*SyncPool[T]) Put

func (sp *SyncPool[T]) Put(item T)

purpose: returns item to pool params: item T - what we're returning args: resets item, checks capacity limit, stores in sync.Pool returns: none raises: none

func (*SyncPool[T]) Stats

func (sp *SyncPool[T]) Stats() PoolStats

purpose: gets current statistics params: none args: collects metrics from collector returns: PoolStats raises: none

Jump to

Keyboard shortcuts

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