toolbelt

package module
v0.2.14-0...-569f696 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2026 License: MIT Imports: 12 Imported by: 0

README

toolbelt

A set of utilities used in every go project

wisshes mascot

Package splits

Several helpers were moved out of the root toolbelt package to avoid pulling external dependencies into every import.

  • toolbelt/db: sqlite + timestamp helpers from database.go (Database, NewDatabase, Julian/Stmt helpers, migrations).
  • toolbelt/protobuf: protobuf marshal/unmarshal helpers from protobuf.go.
  • toolbelt/egctx: errgroup helpers from egctx.go.
  • toolbelt/id: ID generation/encoding helpers from id.go (no chi dependency).
  • toolbelt/web: chi-based request param helpers (ChiParamInt64, ChiParamEncodedID).

If you were importing these from toolbelt directly, update your imports to the package listed above.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Camel

func Camel(s string) string

func Cased

func Cased(s string, fn ...CasedFn) string

func Clamp

func Clamp[T Float](v T, minimum T, maximum T) T

func Clamp01

func Clamp01[T Float](v T) T

func ClampFit

func ClampFit[T Float](
	x T,
	oldMin T,
	oldMax T,
	newMin T,
	newMax T,
) T

func ClampFit01

func ClampFit01[T Float](x T, newMin T, newMax T) T

func CtxSlog

func CtxSlog(ctx context.Context) (logger *slog.Logger, ok bool)

func CtxWithSlog

func CtxWithSlog(ctx context.Context, slog *slog.Logger) context.Context

func DebounceWithMaxWait

func DebounceWithMaxWait(waitTime time.Duration, maxWaitTime time.Duration, fn func(context.Context) error) func(context.Context) error

DebounceWithMaxWait creates a debounced function that waits for a quiet period before executing, but guarantees execution within a maximum wait time.

func EaseInBack

func EaseInBack[T Float](t T) T

Back

func EaseInBounce

func EaseInBounce[T Float](t T) T

Bounce

func EaseInCirc

func EaseInCirc[T Float](t T) T

Circ

func EaseInCubic

func EaseInCubic[T Float](t T) T

Cubic

func EaseInElastic

func EaseInElastic[T Float](t T) T

Elastic

func EaseInExpo

func EaseInExpo[T Float](t T) T

Expo

func EaseInOutBack

func EaseInOutBack[T Float](t T) T

func EaseInOutBounce

func EaseInOutBounce[T Float](t T) T

func EaseInOutCirc

func EaseInOutCirc[T Float](t T) T

func EaseInOutCubic

func EaseInOutCubic[T Float](t T) T

func EaseInOutElastic

func EaseInOutElastic[T Float](t T) T

func EaseInOutExpo

func EaseInOutExpo[T Float](t T) T

func EaseInOutQuad

func EaseInOutQuad[T Float](t T) T

func EaseInOutQuart

func EaseInOutQuart[T Float](t T) T

func EaseInOutQuint

func EaseInOutQuint[T Float](t T) T

func EaseInOutSine

func EaseInOutSine[T Float](t T) T

func EaseInQuad

func EaseInQuad[T Float](t T) T

Quad

func EaseInQuart

func EaseInQuart[T Float](t T) T

Quart

func EaseInQuint

func EaseInQuint[T Float](t T) T

Quint

func EaseInSine

func EaseInSine[T Float](t T) T

Sine

func EaseLinear

func EaseLinear[T Float](t T) T

Linear

func EaseOutBack

func EaseOutBack[T Float](t T) T

func EaseOutBounce

func EaseOutBounce[T Float](t T) T

func EaseOutCirc

func EaseOutCirc[T Float](t T) T

func EaseOutCubic

func EaseOutCubic[T Float](t T) T

func EaseOutElastic

func EaseOutElastic[T Float](t T) T

func EaseOutExpo

func EaseOutExpo[T Float](t T) T

func EaseOutQuad

func EaseOutQuad[T Float](t T) T

func EaseOutQuart

func EaseOutQuart[T Float](t T) T

func EaseOutQuint

func EaseOutQuint[T Float](t T) T

func EaseOutSine

func EaseOutSine[T Float](t T) T

func Fit

func Fit[T Float](
	x T,
	oldMin T,
	oldMax T,
	newMin T,
	newMax T,
) T

func Fit01

func Fit01[T Float](x T, newMin T, newMax T) T

func FitMax

func FitMax[T Float](x T, newMax T) T

func FreePort

func FreePort() (port int, err error)

Returns a free port number that can be used to listen on.

func Kebab

func Kebab(s string) string

func Lower

func Lower(s string) string

func MusicalRatio

func MusicalRatio(name MusicalRatioName) float64

func Pascal

func Pascal(s string) string

func RandIntRange

func RandIntRange[T Integer](r *rand.Rand, min, max T) T

func RandNegOneToOneClamped

func RandNegOneToOneClamped[T Float](r *rand.Rand) T

func RandSliceItem

func RandSliceItem[T any](r *rand.Rand, slice []T) T

func ReadFloat32

func ReadFloat32(r io.Reader) (float32, error)

ReadFloat32 reads a little-endian IEEE 754 float32.

func ReadInt32

func ReadInt32(r io.Reader) (int32, error)

ReadInt32 reads a little-endian int32.

func ReadInt64

func ReadInt64(r io.Reader) (int64, error)

ReadInt64 reads a little-endian int64.

func ReadString

func ReadString(r io.Reader) (string, error)

ReadString reads a length-prefixed string with a uint32 length.

func ReadUint8

func ReadUint8(r io.Reader) (uint8, error)

ReadUint8 reads a little-endian uint8.

func ReadUint32

func ReadUint32(r io.Reader) (uint32, error)

ReadUint32 reads a little-endian uint32.

func ReadUint64

func ReadUint64(r io.Reader) (uint64, error)

ReadUint64 reads a little-endian uint64.

func RoundFit01

func RoundFit01[T Float](x T, newMin T, newMax T) T

func ScreamingSnake

func ScreamingSnake(s string) string

func Snake

func Snake(s string) string

func Upper

func Upper(s string) string

func WriteFloat32

func WriteFloat32(w io.Writer, v float32) error

WriteFloat32 writes v in little-endian IEEE 754 binary form.

func WriteInt32

func WriteInt32(w io.Writer, v int32) error

WriteInt32 writes v in little-endian order.

func WriteInt64

func WriteInt64(w io.Writer, v int64) error

WriteInt64 writes v in little-endian order.

func WriteString

func WriteString(w io.Writer, s string) error

WriteString writes a length-prefixed string with a uint32 length.

func WriteUint8

func WriteUint8(w io.Writer, v uint8) error

WriteUint8 writes v in little-endian order.

func WriteUint32

func WriteUint32(w io.Writer, v uint32) error

WriteUint32 writes v in little-endian order.

func WriteUint64

func WriteUint64(w io.Writer, v uint64) error

WriteUint64 writes v in little-endian order.

Types

type CasedFn

type CasedFn func(string) string

type CasedString

type CasedString struct {
	Original       string
	Pascal         string
	Camel          string
	Snake          string
	ScreamingSnake string
	Kebab          string
	Upper          string
	Lower          string
}

func ToCasedString

func ToCasedString(s string) CasedString

type CtxErrFunc

type CtxErrFunc func(ctx context.Context) error

func CallNTimesWithDelay

func CallNTimesWithDelay(d time.Duration, n int, fn CtxErrFunc) CtxErrFunc

func Debounce

func Debounce(d time.Duration, fn CtxErrFunc) CtxErrFunc

Debounce will only call the function after d duration has passed since the last call.

func Throttle

func Throttle(d time.Duration, fn CtxErrFunc) CtxErrFunc

Throttle will only allow the function to be called once every d duration.

type CtxKey

type CtxKey string
const CtxSlogKey CtxKey = "slog"

type EasingFunc

type EasingFunc[T Float] func(t T) T

EasingFunc is a function that takes a normalized time t in [0,1] and returns the eased value in [0,1].

func Ease

func Ease[T Float](mode EasingMode) EasingFunc[T]

Ease returns a named easing function. Unknown names fall back to linear. Accepted names are case-insensitive and allow dashes/underscores/spaces, e.g.:

"linear", "in-quad", "easeInCubic", "inout-sine", "out_bounce", etc.

type EasingMode

type EasingMode string
const (
	EasingModeLinear       EasingMode = "linear"
	EasingModeInQuad       EasingMode = "inquad"
	EasingModeOutQuad      EasingMode = "outquad"
	EasingModeInOutQuad    EasingMode = "inoutquad"
	EasingModeInCubic      EasingMode = "incubic"
	EasingModeOutCubic     EasingMode = "outcubic"
	EasingModeInOutCubic   EasingMode = "inoutcubic"
	EasingModeInQuart      EasingMode = "inquart"
	EasingModeOutQuart     EasingMode = "outquart"
	EasingModeInOutQuart   EasingMode = "inoutquart"
	EasingModeInQuint      EasingMode = "inquint"
	EasingModeOutQuint     EasingMode = "outquint"
	EasingModeInOutQuint   EasingMode = "inoutquint"
	EasingModeInSine       EasingMode = "insine"
	EasingModeOutSine      EasingMode = "outsine"
	EasingModeInOutSine    EasingMode = "inoutsine"
	EasingModeInExpo       EasingMode = "inexpo"
	EasingModeOutExpo      EasingMode = "outexpo"
	EasingModeInOutExpo    EasingMode = "inoutexpo"
	EasingModeInCirc       EasingMode = "incirc"
	EasingModeOutCirc      EasingMode = "outcirc"
	EasingModeInOutCirc    EasingMode = "inoutcirc"
	EasingModeInElastic    EasingMode = "inelastic"
	EasingModeOutElastic   EasingMode = "outelastic"
	EasingModeInOutElastic EasingMode = "inoutelastic"
	EasingModeInBack       EasingMode = "inback"
	EasingModeOutBack      EasingMode = "outback"
	EasingModeInOutBack    EasingMode = "inoutback"
	EasingModeInBounce     EasingMode = "inbounce"
	EasingModeOutBounce    EasingMode = "outbounce"
	EasingModeInOutBounce  EasingMode = "inoutbounce"
)

type EventBus

type EventBus[T any] interface {
	Subscribe(ctx context.Context, fn Subscriber[T]) context.CancelFunc
	Emit(ctx context.Context, msg T) error
	Count() int
}

type EventBusAsync

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

func NewEventBusAsync

func NewEventBusAsync[T any]() *EventBusAsync[T]

func (EventBusAsync) Count

func (b EventBusAsync) Count() int

func (*EventBusAsync[T]) Emit

func (b *EventBusAsync[T]) Emit(ctx context.Context, msg T) error

func (EventBusAsync) Subscribe

func (b EventBusAsync) Subscribe(ctx context.Context, fn Subscriber[T]) context.CancelFunc

type EventBusSync

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

func NewEventBusSync

func NewEventBusSync[T any]() *EventBusSync[T]

func (EventBusSync) Count

func (b EventBusSync) Count() int

func (*EventBusSync[T]) Emit

func (b *EventBusSync[T]) Emit(ctx context.Context, msg T) error

func (EventBusSync) Subscribe

func (b EventBusSync) Subscribe(ctx context.Context, fn Subscriber[T]) context.CancelFunc

type Float

type Float interface {
	~float32 | ~float64
}

type Handle

type Handle struct {
	Index      uint32
	Generation uint32
}

Handle is a stable reference to an element in a SparseSet. Index and Generation are both uint32. A handle is valid if its generation matches the current generation for its slot in the set in which it was created.

type Integer

type Integer interface {
	~int | ~uint8 | ~int8 | ~uint16 | ~int16 | ~uint32 | ~int32 | ~uint64 | ~int64
}

type MusicalRatioName

type MusicalRatioName string
const (
	MusicalRatioMinorSecond     MusicalRatioName = "Minor Second"
	MusicalRatioMajorSecond     MusicalRatioName = "Major Second"
	MusicalRatioMinorThird      MusicalRatioName = "Minor Third"
	MusicalRatioMajorThird      MusicalRatioName = "Major Third"
	MusicalRatioPerfectFourth   MusicalRatioName = "Perfect Fourth"
	MusicalRatioAugmentedFourth MusicalRatioName = "Augmented Fourth"
	MusicalRatioPerfectFifth    MusicalRatioName = "Perfect Fifth"
	MusicalRatioGoldenRatio     MusicalRatioName = "Golden Ratio"
	MusicalRatioMinorSixth      MusicalRatioName = "Minor Sixth"
	MusicalRatioMajorSixth      MusicalRatioName = "Major Sixth"
	MusicalRatioMajorSeventh    MusicalRatioName = "Major Seventh"
	MusicalRatioOctave          MusicalRatioName = "Octave"
)

type Pool

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

A Pool is a generic wrapper around a sync.Pool.

func New

func New[T any](fn func() T, opts ...PoolOption[T]) *Pool[T]

New creates a new Pool with the provided new function.

The equivalent sync.Pool construct is "sync.Pool{New: fn}"

func (*Pool[T]) Clear

func (p *Pool[T]) Clear(keepCapacity bool)

Clear resets the pool. If keepCapacity is true, the pool is left intact.

func (*Pool[T]) Get

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

Get is a generic wrapper around sync.Pool's Get method.

func (*Pool[T]) GetWithReset

func (p *Pool[T]) GetWithReset() T

GetWithReset returns an item from the pool and applies the optional reset.

func (*Pool[T]) Put

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

Put is a generic wrapper around sync.Pool's Put method.

type PoolOption

type PoolOption[T any] func(*Pool[T])

PoolOption configures pool behavior.

func WithReset

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

WithReset configures a reset function applied by GetWithReset.

type SparseSet

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

SparseSet is a growable, O(1) add/get/remove container that uses stable, generational handles to reference elements without exposing internal indices. Removals are constant time by swapping the last element into the removed slot in the dense array.

This is a Go port inspired by Karl Zylinski's odin-handle-map (handle_map_growing), adapted to Go generics and idioms.

The zero value is ready to use; use NewSparseSet to pre-reserve.

func NewSparseSet

func NewSparseSet[T any](initialCapacity int) *SparseSet[T]

NewSparseSet constructs a SparseSet with an optional initial slot capacity. A capacity of 0 creates an empty set with no pre-allocated slots.

func (*SparseSet[T]) Cap

func (s *SparseSet[T]) Cap() int

Cap returns the number of total slots (live + free) that can be used without growing the sparse structures.

func (*SparseSet[T]) Clear

func (s *SparseSet[T]) Clear()

Clear removes all elements. Existing handles become invalid.

func (*SparseSet[T]) Contains

func (s *SparseSet[T]) Contains(h Handle) bool

Contains reports whether h refers to a live element in s.

func (*SparseSet[T]) Get

func (s *SparseSet[T]) Get(h Handle) (T, bool)

Get returns the value for h if it is valid and present.

func (*SparseSet[T]) GetRef

func (s *SparseSet[T]) GetRef(h Handle) (*T, bool)

GetRef returns a pointer to the value for h if valid. Note: Removing other elements may move the value due to swap-remove, invalidating previously taken pointers. Use only transiently.

func (*SparseSet[T]) Handles

func (s *SparseSet[T]) Handles() []Handle

Handles returns a snapshot of handles for all live elements.

func (*SparseSet[T]) Insert

func (s *SparseSet[T]) Insert(v T) Handle

Insert adds v to the set and returns a stable handle to it. Amortized O(1). May grow the internal storage.

func (*SparseSet[T]) Len

func (s *SparseSet[T]) Len() int

Len returns the number of live elements.

func (*SparseSet[T]) Range

func (s *SparseSet[T]) Range(f func(h Handle, v *T) bool)

Range iterates over all live elements. The callback receives a current handle for each element and a pointer to its value. If f returns false, iteration stops early.

func (*SparseSet[T]) Remove

func (s *SparseSet[T]) Remove(h Handle) bool

Remove deletes the element referenced by h if present. Returns true if the element existed and was removed.

func (*SparseSet[T]) Reserve

func (s *SparseSet[T]) Reserve(n int)

Reserve ensures the set can accommodate at least n live elements without reallocating dense storage. Note: this does not change the number of available slots for handles. To increase the number of potential handles without insertions, call ReserveSlots.

func (*SparseSet[T]) ReserveSlots

func (s *SparseSet[T]) ReserveSlots(n int)

ReserveSlots ensures the set has at least n slots available to be populated by future Insert calls before growing the sparse structures.

func (*SparseSet[T]) Values

func (s *SparseSet[T]) Values() []T

Values returns a shallow copy of all live elements in dense order.

type Subscriber

type Subscriber[T any] func(msg T) error

Jump to

Keyboard shortcuts

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