utils

package
v0.0.0-...-0a9161b Latest Latest
Warning

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

Go to latest
Published: Jan 20, 2026 License: Apache-2.0 Imports: 12 Imported by: 1

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrAlreadySet = fmt.Errorf("value already set")

Functions

func CastPtr

func CastPtr[S any, T any](s *S, castFunc func(S) T) *T

func Cleanup

func Cleanup(ctx context.Context, msg string, fn func() error)

func CleanupCtx

func CleanupCtx(ctx context.Context, msg string, fn func(ctx context.Context) error)

func DerefOrDefault

func DerefOrDefault[T any](s *T, defaultValue T) T

func Filter

func Filter[T any](input []T, f func(T) bool) []T

Filter takes a slice of any type T and a predicate function f. It returns a new slice containing only the elements from the input slice for which the predicate function returns true.

func FromPtr

func FromPtr[T any](s *T) T

func IsGTEVersion

func IsGTEVersion(curVersion, minVersion string) (bool, error)

func IsSmallerVersion

func IsSmallerVersion(curVersion, maxVersionExcluded string) (bool, error)

func IsVersion

func IsVersion(curVersion, eqVersion string) bool

func Map

func Map[T any, U any](input []T, f func(T) U) []U

Map goes through each item in the input slice and applies the function f to it. It returns a new slice with the results.

func MapValues

func MapValues[K comparable, V any](m map[K]V) []V

MapValues takes a map and returns a slice of all its values.

func Must

func Must[T any](obj T, err error) T

func OptionalEnv

func OptionalEnv(key string, envUsageMsg string) (string, bool)

OptionalEnv returns the value of the environment variable for key if it is set, non-empty and not only whitespace.

Pass the envUsageMsg to describe what the environment variable is used for. This will be used in the message that is printed if the environment variable is not returned.

func RenameOrDeleteFile

func RenameOrDeleteFile(ctx context.Context, oldPath, newPath string) error

RenameOrDeleteFile tries to rename a file but will not replace the target if it already exists. If the file already exists, the file will be deleted. The old file will always be deleted.

func RequiredEnv

func RequiredEnv(key string, envUsageMsg string) string

RequiredEnv returns the value of the environment variable for key if it is set, non-empty and not only whitespace. It panics otherwise.

Pass the envUsageMsg to describe what the environment variable is used for. This will be used in the error message.

func ShallowCopyMap

func ShallowCopyMap[K comparable, V any](m map[K]V) map[K]V

ShallowCopyMap creates a new map with the same keys and values as the input map. Warning: Do not use this function to copy maps that contain maps or slices.

func Sprintp

func Sprintp[T any](s *T) string

func SymlinkForce

func SymlinkForce(oldname, newname string) error

func ToPtr

func ToPtr[T any](v T) *T

func TransformTo

func TransformTo[S, T any](iterator iter.Seq[S], f func(S) T) iter.Seq[T]

func Truncate

func Truncate(s string, maxLen int) string

Types

type AdjustableSemaphore

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

func NewAdjustableSemaphore

func NewAdjustableSemaphore(limit int64) (*AdjustableSemaphore, error)

func (*AdjustableSemaphore) Acquire

func (s *AdjustableSemaphore) Acquire(ctx context.Context, n int64) error

func (*AdjustableSemaphore) Release

func (s *AdjustableSemaphore) Release(n int64)

func (*AdjustableSemaphore) SetLimit

func (s *AdjustableSemaphore) SetLimit(limit int64) error

func (*AdjustableSemaphore) TryAcquire

func (s *AdjustableSemaphore) TryAcquire(n int64) bool

type ErrorCollector

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

ErrorCollector collects errors from multiple goroutines. This has a similar API to `errgroup.Group`, except that it runs all goroutines, and returns all errors; it does not stop after the first error.

func NewErrorCollector

func NewErrorCollector(maxConcurrency int) *ErrorCollector

NewErrorCollector creates a new ErrorCollector

func (*ErrorCollector) Go

func (ec *ErrorCollector) Go(ctx context.Context, fn func() error)

func (*ErrorCollector) Wait

func (ec *ErrorCollector) Wait() error

type ErrorOnce

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

ErrorOnce is a wrapper around SetOnce that can only be set with an error. It's useful for cases where you only need to signal completion with a potential error, without carrying any value.

func NewErrorOnce

func NewErrorOnce() *ErrorOnce

NewErrorOnce creates a new ErrorOnce instance.

func (*ErrorOnce) Done

func (e *ErrorOnce) Done() <-chan struct{}

Done returns a channel that's closed when an error is set. This allows using ErrorOnce in select statements.

func (*ErrorOnce) Error

func (e *ErrorOnce) Error() error

Error returns the error if one has been set, or ErrNotSet if not set yet. Unlike Wait, this doesn't block.

func (*ErrorOnce) SetError

func (e *ErrorOnce) SetError(err error) error

SetError sets the error once. Subsequent calls will return ErrAlreadySet.

func (*ErrorOnce) SetSuccess

func (e *ErrorOnce) SetSuccess() error

SetSuccess marks the operation as completed successfully (no error). This is equivalent to SetError(nil).

func (*ErrorOnce) Wait

func (e *ErrorOnce) Wait() error

Wait blocks until an error is set and returns it. Returns nil if the operation completed successfully.

func (*ErrorOnce) WaitWithContext

func (e *ErrorOnce) WaitWithContext(ctx context.Context) error

WaitWithContext waits for an error to be set with context cancellation support. Returns the set error or ctx.Err() if the context is cancelled first.

type Lazy

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

Lazy provides lazy initialization with memoization. Similar to sync.OnceValue, but accepts the function at call time rather than initialization, allowing the caller to pass context or other parameters.

GetOrInit is safe for concurrent use. Only the first call executes f, and all callers receive the same result. Concurrent callers block until f completes.

Implemented as described here: https://goperf.dev/01-common-patterns/lazy-init/

func (*Lazy[T]) GetOrInit

func (l *Lazy[T]) GetOrInit(f func() T) T

GetOrInit returns the stored value, initializing it with f on the first call. Subsequent calls return the cached value without calling f. Concurrent calls block until the first call to f completes.

type NotSetError

type NotSetError struct{}

func (NotSetError) Error

func (e NotSetError) Error() string

type Promise

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

Promise represents an asynchronous computation that will eventually produce a value or error. The computation starts immediately when the promise is created. Multiple goroutines can safely wait on the same promise.

func NewPromise

func NewPromise[T any](fn func() (T, error)) *Promise[T]

NewPromise creates a new Promise that immediately starts executing the given function in a goroutine. The result (value or error) will be available via Wait.

func (*Promise[T]) Done

func (p *Promise[T]) Done() <-chan struct{}

Done returns a channel that's closed when the promise is resolved. This allows using Promise in select statements.

func (*Promise[T]) Result

func (p *Promise[T]) Result() (T, error)

Result returns the current result without blocking. Returns NotSetError if the promise hasn't resolved yet.

func (*Promise[T]) Wait

func (p *Promise[T]) Wait(ctx context.Context) (T, error)

Wait blocks until the promise is resolved and returns the result. Returns the value and nil error on success, or zero value and the error on failure. If the context is cancelled before the promise resolves, returns ctx.Err().

type Semaphore

type Semaphore interface {
	Acquire(ctx context.Context, n int64) error
	TryAcquire(n int64) bool
	Release(n int64)
}

type SetOnce

type SetOnce[T any] struct {

	// Don't close the channel from outside, it's used to signal that the value is set.
	Done chan struct{}
	// contains filtered or unexported fields
}

func NewSetOnce

func NewSetOnce[T any]() *SetOnce[T]

func (*SetOnce[T]) Result

func (s *SetOnce[T]) Result() (T, error)

Result returns the value or error set by SetValue or SetError. It can be called multiple times, returning the same value or error. If called before the value is set, it will return the zero value and NotSetError error.

func (*SetOnce[T]) SetError

func (s *SetOnce[T]) SetError(err error) error

func (*SetOnce[T]) SetResult

func (s *SetOnce[T]) SetResult(value T, err error) error

func (*SetOnce[T]) SetValue

func (s *SetOnce[T]) SetValue(value T) error

func (*SetOnce[T]) Wait

func (s *SetOnce[T]) Wait() (T, error)

Wait returns the value or error set by SetValue or SetError. It can be called multiple times, returning the same value or error.

func (*SetOnce[T]) WaitWithContext

func (s *SetOnce[T]) WaitWithContext(ctx context.Context) (T, error)

WaitWithContext TODO: Use waitWithContext in all places instead of Wait.

type WaitMap

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

WaitMap allows you to wait for functions with given keys and execute them only once.

func NewWaitMap

func NewWaitMap() *WaitMap

func (*WaitMap) Wait

func (m *WaitMap) Wait(key int64, fn func() error) error

Wait waits for the function with the given key to be executed. If the function is already executing, it waits for it to finish. If the function is not yet executing, it executes the function and returns its result.

Jump to

Keyboard shortcuts

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