stdlib

package
v1.61.1 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2025 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// DefaultTaskTimeout is the default timeout for a task to run.
	DefaultTaskTimeout = 30 * time.Second
	// DefaultCancelFn is the default cancel function for a task.
	DefaultCancelFn = func(context.Context) error { return nil }
	// DefaultCancelTimeout is the default timeout for a task cancel fn to run.
	DefaultCancelTimeout = 5 * time.Second
)
View Source
var ErrConversionNotSupported = Error{
	Code:      "conversion_not_supported",
	Message:   "data type could not be converted safety",
	Namespace: "com.github.ahawker.stdlib",
}
View Source
var ErrInvalidDataType = fmt.Errorf("not a valid DataType, try [%s]", strings.Join(_DataTypeNames, ", "))
View Source
var ErrInvalidFakeStrategy = fmt.Errorf("not a valid FakeStrategy, try [%s]", strings.Join(_FakeStrategyNames, ", "))
View Source
var ErrPrecisionLoss = Error{
	Code:      "precision_loss",
	Message:   "data type could not be converted without loss of precision",
	Namespace: "com.github.ahawker.stdlib",
}
View Source
var ErrTaskTimeout = Error{
	Code:      "task_timeout",
	Message:   "task reached its timeout and was cancelled",
	Namespace: ErrorNamespaceDefault,
}

ErrTaskTimeout is returned when a task reaches its timeout cancelled.

View Source
var ErrTypeAssertionFailed = Error{
	Code:      "type_assertion_failed",
	Message:   "type assertion failed",
	Namespace: ErrorNamespaceDefault,
}

ErrTypeAssertionFailed is returned when attempting to type assert a value that cannot be converted.

View Source
var ErrTypeConversionFailed = Error{
	Code:      "type_conversion_failed",
	Message:   "type conversion failed",
	Namespace: ErrorNamespaceDefault,
}

ErrTypeConversionFailed is returned when attempting a type conversion that cannot be performed.

View Source
var ErrUndefined = Error{
	Code:      "undefined",
	Flags:     ErrorFlagUnknown,
	Message:   "wrapped the following error which is not well-defined",
	Namespace: ErrorNamespaceDefault,
}

ErrUndefined indicates the wrapped error is not well-known or previously defined. This likely means it's coming from an external system/library and not a domain error.

View Source
var TimestampLayouts = [3]string{
	time.Layout,
	time.RFC3339,
	time.RFC3339Nano,
}

Functions

func AnyTo added in v1.32.0

func AnyTo[T any](v any) any

AnyTo converts an any interface value to a value that can be type asserted to type T.

func As added in v1.33.0

func As[T any](v any) (T, error)

As performs a type assertion of 'any' value to type T. If it fails an error is returned.

func Bool added in v1.53.0

func Bool(value any) (bool, error)

func Build added in v1.17.0

func Build[T any](t T, builders ...Builder[T]) (T, error)

Build applies all functional builders to type t and returns the type built.

func Bytes added in v1.53.0

func Bytes(value any) ([]byte, error)

func DataTypeConvert added in v1.53.0

func DataTypeConvert(dt DataType, value any) (any, error)

func DataTypeNames added in v1.53.0

func DataTypeNames() []string

DataTypeNames returns a list of possible string values of DataType.

func Date added in v1.53.0

func Date(value any) (time.Time, error)

func Defer added in v1.6.0

func Defer(err *error, errs ...error)

Defer is a helper for capturing errors from calls inside a 'defer'.

func DeferCall added in v1.29.0

func DeferCall(err *error, fn func() error)

DeferCall is a helper for deferring a function call (closer) that can return an error when in a function context that can return multiple errors.

func DeferCloser added in v1.28.0

func DeferCloser(err *error, closer io.Closer)

DeferCloser is a helper for deferring a io.Closer that can return an error when in a function context that can return multiple errors.

func DeferCloserToGroup added in v1.51.0

func DeferCloserToGroup(c **CloserGroup, closer ...io.Closer) io.Closer

DeferCloserToGroup is a helper for deferring a closer to a group.

func Dereference added in v1.54.0

func Dereference[T any](t *T) T

Dereference dereference the given pointer.

func ErrorGroupFormatterDefault

func ErrorGroupFormatterDefault(errors []Error) string

ErrorGroupFormatterDefault is a basic Formatter that outputs the number of errors that occurred along with a bullet point list of the errors.

func ErrorKey added in v1.27.0

func ErrorKey(namespace, code string) string

ErrorKey returns a slug that should be unique for each error (namespace + code).

func FakeStrategyNames added in v1.42.0

func FakeStrategyNames() []string

FakeStrategyNames returns a list of possible string values of FakeStrategy.

func Float32 added in v1.53.0

func Float32(value any) (float32, error)

func Float64 added in v1.53.0

func Float64(value any) (float64, error)

func Int16 added in v1.53.0

func Int16(value any) (int16, error)

func Int32 added in v1.53.0

func Int32(value any) (int32, error)

func Int64 added in v1.53.0

func Int64(value any) (int64, error)

func Int8 added in v1.53.0

func Int8(value any) (int8, error)

func IsZero

func IsZero[T any](t T) bool

IsZero returns true if the given value is equal to the zero value of the type.

func IsZeroAny added in v1.19.0

func IsZeroAny(t any) bool

IsZeroAny returns true if the given value is equal to the zero value of the type.

func MapFilter

func MapFilter[K comparable, V any](input map[K]V, predicate KeyedPredicate[K, V]) map[K]V

MapFilter will return a new map containing only items from the input map that match the predicate function.

func MapFilterRange

func MapFilterRange[K comparable, V any](input KeyedRanger[K, V], predicate KeyedPredicate[K, V]) map[K]V

MapFilterRange will return a new map containing only items from the input keyed ranger that match the predicate function.

func MapKeys added in v1.23.0

func MapKeys[K comparable, V any](input map[K]V) []K

MapKeys returns a slice of all keys for the map.

func MapValues added in v1.23.0

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

MapValues returns a slice of all values for the map.

func Must

func Must[T any](t T) T

Must panics if given value is equal to the zero value of the type.

func MustBool added in v1.35.0

func MustBool[T any](value T) bool

MustBool returns the bool representation of the given value and panics if it cannot.

func MustDuration added in v1.35.0

func MustDuration[T any](value T) time.Duration

MustDuration returns the time.Duration representation of the given value and panics if it cannot.

func MustE

func MustE[T any](fn func() (T, error)) T

MustE panics if the given func returns an error for the value returned is equal to the zero value of the type.

func MustInt added in v1.35.0

func MustInt[T any](value T) int

MustInt returns the int representation of the given value and panics if it cannot.

func MustMapAny added in v1.38.0

func MustMapAny[T any](value T) map[string]any

MustMapAny returns the map[string]any of the given value and panics if it cannot.

func MustMapString added in v1.38.0

func MustMapString[T any](value T) map[string]string

MustMapString returns the map[string]string of the given value and panics if it cannot.

func MustString added in v1.35.0

func MustString[T any](value T) string

MustString returns the string representation of the given value and panics if it cannot.

func MustT added in v1.14.0

func MustT[T any](v any) T

MustT panics if given 'any' value cannot be aliased to the type t.

func MustTime added in v1.50.0

func MustTime[T any](value T) time.Time

MustTime returns the time.Time representation of the given value and panics if it cannot.

func Null added in v1.53.0

func Null(value any) (any, error)

func OptionApply

func OptionApply[T any](t T, options ...Option[T]) (T, error)

OptionApply applies all functional options to type t and returns the error if any fail to apply.

func Pointer

func Pointer[T any](t T) *T

Pointer returns a pointer to the given value.

func RandomExcluding added in v1.46.0

func RandomExcluding[T comparable](fn func() T, exclude map[T]struct{}) T

RandomExcluding generates a random value that is not in the excluded set.

Note: Depending on the content of the excluded set, this function may be extremely inefficient.

func RandomNumber added in v1.44.0

func RandomNumber[T constraints.Integer | constraints.Float](r *Random) T

RandomNumber returns a random number between primitive value min & max.

func RandomNumberRange added in v1.44.0

func RandomNumberRange[T constraints.Integer | constraints.Float](r *Random, min, max T) T

RandomNumberRange returns a random number between min (inclusive) and max (exclusive).

func RandomRegex added in v1.44.0

func RandomRegex[T ~string](r *Random, pattern string) T

RandomRegex returns a random string that matches a regular expression.

func RandomSelection added in v1.44.0

func RandomSelection[T any](r *Random, items []T) T

RandomSelection returns a random item from the provided list of items.

func RandomString added in v1.44.0

func RandomString[T ~string](r *Random, min, max uint64) T

RandomString returns a random string between min length (inclusive) and max length (exclusive).

func ReturnGlobal added in v1.60.0

func ReturnGlobal(random *Random)

ReturnGlobal returns the global Random instance and unlocks it.

func SafeDereference added in v1.54.0

func SafeDereference[T any](t *T) T

SafeDereference dereference the given pointer and return the zero value if the pointer is nil.

func SliceFilter

func SliceFilter[T any](input []T, predicate Predicate[T]) []T

SliceFilter will return a new slice containing only items from the given input that match the predicate function.

func SliceFilterRange

func SliceFilterRange[T any](input Ranger[T], predicate Predicate[T]) []T

SliceFilterRange will return a new slice containing only items from the given input ranger that match the predicate function.

func SliceFlatten

func SliceFlatten[T any](input ...[]T) []T

SliceFlatten will flatten a slice of slices into a single slice.

func SliceMap added in v1.24.0

func SliceMap[TIn any, TOut any](input []TIn, mapper Mapper[TIn, TOut]) []TOut

SliceMap returns a slice with the results from the given 'map' function.

func SliceSet added in v1.39.0

func SliceSet[T comparable](input []T) map[T]struct{}

SliceSet returns a set from the given slice.

func SliceToMap

func SliceToMap[K comparable, V any](input []V, key func(v V) K) map[K]V

SliceToMap returns a map from the given slice and key function.

func SliceTypeAssert added in v1.7.0

func SliceTypeAssert[TIn any, TOut any](input []TIn) []TOut

SliceTypeAssert takes a slice of one type and asserts individual items to the other.

func Task added in v1.56.0

func Task(ctx context.Context, task TaskFn, options ...Option[*TaskConfig]) error

Task executes the given task with the provided context and options.

func Timestamp added in v1.55.0

func Timestamp(value any) (time.Time, error)

func TimestampMs added in v1.53.0

func TimestampMs(value any) (time.Time, error)

func TimestampS added in v1.53.0

func TimestampS(value any) (time.Time, error)

func TitleCase

func TitleCase(s string) string

TitleCase returns the given string in title case per English language rules.

Ref: https://en.wikipedia.org/wiki/Title_case

func ToBool added in v1.36.0

func ToBool[T any](value T) (bool, error)

ToBool returns the bool representation of the given value and errors if it cannot.

func ToDuration added in v1.36.0

func ToDuration[T any](value T) (time.Duration, error)

ToDuration returns the time.Duration representation of the given value and errors if it cannot.

func ToInt added in v1.36.0

func ToInt[T any](value T) (int, error)

ToInt returns the int representation of the given value and errors if it cannot.

func ToMapAny added in v1.38.0

func ToMapAny[T any](value T) (map[string]any, error)

ToMapAny returns the map[string]any representation of the given value and errors if it cannot.

func ToMapString added in v1.38.0

func ToMapString[T any](value T) (map[string]string, error)

ToMapString returns the map[string]any representation of the given value and errors if it cannot.

func ToString added in v1.36.0

func ToString[T any](value T) (string, error)

ToString returns the string representation of the given value and errors if it cannot.

func ToTime added in v1.50.0

func ToTime[T any](value T) (time.Time, error)

ToTime returns the time.Time representation of the given value and errors if it cannot.

func URLPort

func URLPort(u *url.URL) (int, error)

URLPort returns a port number for the given URL.

If a port was not defined during URL creation, an attempt is made to derive it from the scheme.

func Uint16 added in v1.53.0

func Uint16(value any) (uint16, error)

func Uint32 added in v1.53.0

func Uint32(value any) (uint32, error)

func Uint64 added in v1.53.0

func Uint64(value any) (uint64, error)

func Uint8 added in v1.53.0

func Uint8(value any) (uint8, error)

func Utf8 added in v1.53.0

func Utf8(value any) (string, error)

func ZeroPad added in v1.49.0

func ZeroPad[T constraints.Integer](width T, v T) string

ZeroPad returns the given integer as a zero-padded string.

Types

type Bitmask

type Bitmask uint8

Bitmask is a `uint8` with helper methods for bitwise operations.

const (
	// ErrorNamespaceDefault is the default namespace for errors generated by this package.
	ErrorNamespaceDefault = "stdlibx-go"
	// ErrorFlagUnknown is set to represent unknown/unregistered errors.
	ErrorFlagUnknown Bitmask = 1 << iota
	// ErrorFlagRetryable is set to represent errors that can be retried.
	ErrorFlagRetryable
	// ErrorFlagTimeout is set to represent errors indicating a timeout occurred.
	ErrorFlagTimeout
)

func ParseBitmask

func ParseBitmask(binary string) (Bitmask, error)

ParseBitmask creates a new Bitmask from a binary string.

func (Bitmask) Clear

func (b Bitmask) Clear(bits Bitmask) Bitmask

Clear given bits from the current mask and return a new copy.

func (Bitmask) Has

func (b Bitmask) Has(bits Bitmask) bool

Has checks if bits are set.

func (Bitmask) MarshalText

func (b Bitmask) MarshalText() ([]byte, error)

MarshalText implements the text marshaller method.

func (Bitmask) Set

func (b Bitmask) Set(bits Bitmask) Bitmask

Set bits in the current mask and return a new copy.

func (Bitmask) String

func (b Bitmask) String() string

String returns the Bitmask in binary string (001101010) form.

func (Bitmask) Toggle

func (b Bitmask) Toggle(bits Bitmask) Bitmask

Toggle bits on/off and return a new copy.

type Builder added in v1.17.0

type Builder[T any] func(t T) (T, error)

Builder defines functional builder for type t.

type Causer

type Causer interface {
	Cause() error
}

Causer defines types that return the underlying cause of an error.

type CloserFn added in v1.52.0

type CloserFn func() error

CloserFn is a function that can be used to close resources.

func (CloserFn) Close added in v1.52.0

func (fn CloserFn) Close() error

type CloserGroup added in v1.51.0

type CloserGroup struct {
	Closers []io.Closer
}

CloserGroup is a collection of io.Closer instances that can be closed together.

func CloserJoin added in v1.51.0

func CloserJoin(closer io.Closer, closers ...io.Closer) *CloserGroup

CloserJoin is a helper function that will append more closers onto an CloserGroup.

If err is not already an ErrorGroup, then it will be turned into one. If any of the errs are ErrorGroup, they will be flattened one level into err. Any nil errors within errs will be ignored. If err is nil, a new *ErrorGroup will be returned containing the given errs.

func NewCloserGroup added in v1.51.0

func NewCloserGroup(closers ...io.Closer) *CloserGroup

NewCloserGroup creates a new *CloserGroup with sane defaults.

func (*CloserGroup) Append added in v1.51.0

func (g *CloserGroup) Append(closers ...io.Closer)

Append adds the given closers to the group.

func (*CloserGroup) Close added in v1.51.0

func (g *CloserGroup) Close() error

Close closes all closers in the group.

type ContextKey added in v1.10.0

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

ContextKey is a generic key type associated with a specific value type. This should be used with non-exported Go types to avoid potential key collisions within the context object.

func NewContextKey added in v1.10.0

func NewContextKey[T any](name string, def T) ContextKey[T]

NewContextKey creates a new context key for a generic type.

func (ContextKey[T]) String added in v1.10.0

func (k ContextKey[T]) String() string

String returns the name of the key.

func (ContextKey[T]) Value added in v1.10.0

func (k ContextKey[T]) Value(ctx context.Context) T

Value returns the value in the context associated with this key. If the value is not present, it returns the default value.

func (ContextKey[T]) ValueOk added in v1.10.0

func (k ContextKey[T]) ValueOk(ctx context.Context) (T, bool)

ValueOk returns the value in the context associated with this key and also reports whether it was present. If the value is not present, it returns the default value.

func (ContextKey[T]) WithValue added in v1.10.0

func (k ContextKey[T]) WithValue(parent context.Context, value T) context.Context

WithValue returns a copy of parent in which the value associated with key is value.

It is a type-safe equivalent of context.WithValue.

type DataType added in v1.53.0

type DataType string

DataType is a primitive data type which can be used across system implementations.

ENUM( null, bool, int8, int16, int32, int64, int128, uint8, uint16, uint32, uint64, uint128, float32, float64, bytes, utf8, date, timestamp, timestamp_s, timestamp_ms, list ).

const (
	// DataTypeNull is a DataType of type null.
	DataTypeNull DataType = "null"
	// DataTypeBool is a DataType of type bool.
	DataTypeBool DataType = "bool"
	// DataTypeInt8 is a DataType of type int8.
	DataTypeInt8 DataType = "int8"
	// DataTypeInt16 is a DataType of type int16.
	DataTypeInt16 DataType = "int16"
	// DataTypeInt32 is a DataType of type int32.
	DataTypeInt32 DataType = "int32"
	// DataTypeInt64 is a DataType of type int64.
	DataTypeInt64 DataType = "int64"
	// DataTypeInt128 is a DataType of type int128.
	DataTypeInt128 DataType = "int128"
	// DataTypeUint8 is a DataType of type uint8.
	DataTypeUint8 DataType = "uint8"
	// DataTypeUint16 is a DataType of type uint16.
	DataTypeUint16 DataType = "uint16"
	// DataTypeUint32 is a DataType of type uint32.
	DataTypeUint32 DataType = "uint32"
	// DataTypeUint64 is a DataType of type uint64.
	DataTypeUint64 DataType = "uint64"
	// DataTypeUint128 is a DataType of type uint128.
	DataTypeUint128 DataType = "uint128"
	// DataTypeFloat32 is a DataType of type float32.
	DataTypeFloat32 DataType = "float32"
	// DataTypeFloat64 is a DataType of type float64.
	DataTypeFloat64 DataType = "float64"
	// DataTypeBytes is a DataType of type bytes.
	DataTypeBytes DataType = "bytes"
	// DataTypeUtf8 is a DataType of type utf8.
	DataTypeUtf8 DataType = "utf8"
	// DataTypeDate is a DataType of type date.
	DataTypeDate DataType = "date"
	// DataTypeTimestamp is a DataType of type timestamp.
	DataTypeTimestamp DataType = "timestamp"
	// DataTypeTimestampS is a DataType of type timestamp_s.
	DataTypeTimestampS DataType = "timestamp_s"
	// DataTypeTimestampMs is a DataType of type timestamp_ms.
	DataTypeTimestampMs DataType = "timestamp_ms"
	// DataTypeList is a DataType of type list.
	DataTypeList DataType = "list"
)

func ParseDataType added in v1.53.0

func ParseDataType(name string) (DataType, error)

ParseDataType attempts to convert a string to a DataType.

func ReflectTypeToDataType added in v1.55.0

func ReflectTypeToDataType(rt reflect.Type) (DataType, error)

func (DataType) IsValid added in v1.53.0

func (x DataType) IsValid() bool

IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values

func (DataType) MarshalText added in v1.53.0

func (x DataType) MarshalText() ([]byte, error)

MarshalText implements the text marshaller method.

func (DataType) String added in v1.53.0

func (x DataType) String() string

String implements the Stringer interface.

func (*DataType) UnmarshalText added in v1.53.0

func (x *DataType) UnmarshalText(text []byte) error

UnmarshalText implements the text unmarshaller method.

type DebugExtras

type DebugExtras struct {
	// StackTrace of the error.
	StackTrace string `json:"stack_trace,omitempty"`
}

DebugExtras contains helpful information for debugging the error.

func (DebugExtras) IsZero

func (e DebugExtras) IsZero() bool

IsZero returns true if the Extras object is the zero/empty struct value.

type Error

type Error struct {
	// Code is a machine-readable representation for the error.
	Code string `json:"code"`
	// Extras is an optional struct to store execution context
	// that is helpful for understanding the error.
	Extras ErrorExtras `json:"extras,omitempty"`
	// Flags is a bitmask that contains additional classification/context
	// for the error, e.g. indicating if the error can be retried.
	Flags Bitmask `json:"flags,omitempty"`
	// Message is a human-readable representation for the error.
	Message string `json:"message"`
	// Namespace is a machine-readable representation for a bucketing/grouping
	// concept of errors. This is commonly used to indicate the package/repository/service
	// an error originated from.
	Namespace string `json:"namespace"`
	// Wrapped is a wrapped error if this was created from another via `Wrap`. This
	// is hidden from human consumers and only visible to machine/operators.
	Wrapped error `json:"-"`
}

Error defines a standard application error primitive.

TODO(ahawker) Add Format interface (for pretty strings) TODO(ahawker) Namespace field? Embed in the code?

func (Error) AsGroup

func (e Error) AsGroup() *ErrorGroup

AsGroup returns a *ErrorGroup containing this error and all wrapped errors it contains.

func (Error) Copy

func (e Error) Copy() Error

Copy returns a full copy of this Error, including copies of all wrapped errors within.

func (Error) Equal

func (e Error) Equal(e2 Error) bool

Equal returns true if the two Error values are equal.

func (Error) Error

func (e Error) Error() string

Error returns the string representation of the Error.

Interface: error.

func (Error) Format

func (e Error) Format(s fmt.State, verb rune)

Format returns a complex string representation of the Error for the given verbs.

Interface: fmt.Formatter.

func (Error) Is

func (e Error) Is(target error) bool

Is implements error equality checking.

Interface: HasIs.

func (Error) IsRetryable

func (e Error) IsRetryable() bool

IsRetryable returns true if the error indicates the failed operation is safe to retry.

func (Error) IsTimeout

func (e Error) IsTimeout() bool

IsTimeout returns true if the error indicates an operation timeout.

func (Error) IsTransient

func (e Error) IsTransient() bool

IsTransient returns true if the error indicates the operation failure is transient and a result might be different if tried at another time.

func (Error) IsZero

func (e Error) IsZero() bool

IsZero returns true if the Error is an empty/zero value.

func (Error) Key added in v1.26.0

func (e Error) Key() string

Key returns a value that uniquely identifies the type of error.

func (Error) String

func (e Error) String() string

String returns the Error string representation.

Interface: fmt.Stringer.

func (Error) Unwrap

func (e Error) Unwrap() error

Unwrap implements error unwrapping for nested errors.

Interface: Unwrap.

func (Error) WithDebugInfo

func (e Error) WithDebugInfo(extras DebugExtras) Error

WithDebugInfo returns a new copy of the Error with the given debug info added.

func (Error) WithFlag

func (e Error) WithFlag(attribute Bitmask) Error

WithFlag returns a new copy of the Error with the given attribute applied.

func (Error) WithHelp

func (e Error) WithHelp(extras HelpExtras) Error

WithHelp returns a new copy of the Error with the given help info added.

func (Error) WithRetry

func (e Error) WithRetry(extras RetryExtras) Error

WithRetry returns a new copy of the Error with the given retry info added.

func (Error) WithTag added in v1.31.0

func (e Error) WithTag(tags ...string) Error

WithTag returns a new copy of the Error with the given tags added.

func (Error) Wrap

func (e Error) Wrap(err error) Error

Wrap returns a new Error with the given err wrapped.

If the given err is also an Error and the current instance is a zero value, just return a copy of the given Error. This allows us to avoid checking this case at every call-site; we can just Wrap the error and handle it.

func (Error) Wrapf

func (e Error) Wrapf(format string, a ...any) Error

Wrapf returns a new Error with an error created by the given format + args.

type ErrorExtras

type ErrorExtras struct {
	// Debug information captured from the error.
	Debug DebugExtras `json:"debug,omitempty"`
	// Help information to inform operators about the error.
	Help HelpExtras `json:"help,omitempty"`
	// Retry information regarding the failed operation.
	Retry RetryExtras `json:"retry,omitempty"`
	// Tags are additional labels that can be used to categorize errors.
	Tags []string `json:"tags,omitempty"`
}

ErrorExtras contains common additional info attached to errors.

func (ErrorExtras) IsZero

func (e ErrorExtras) IsZero() bool

IsZero returns true if the ErrorExtras object is the zero/empty struct value.

func (ErrorExtras) WithDebugExtras

func (e ErrorExtras) WithDebugExtras(extras DebugExtras) ErrorExtras

WithDebugExtras returns a new copy of the ErrorExtras with the given debug info set.

func (ErrorExtras) WithHelpExtras

func (e ErrorExtras) WithHelpExtras(extras HelpExtras) ErrorExtras

WithHelpExtras returns a new copy of the ErrorExtras with the given help info set.

func (ErrorExtras) WithRetryExtras

func (e ErrorExtras) WithRetryExtras(extras RetryExtras) ErrorExtras

WithRetryExtras returns a new copy of the ErrorExtras with the given retry info set.

func (ErrorExtras) WithTag added in v1.31.0

func (e ErrorExtras) WithTag(tags ...string) ErrorExtras

WithTag returns a new copy of the ErrorExtras with the given tags set.

type ErrorGroup

type ErrorGroup struct {
	// Errors in the group.
	Errors []Error `json:"errors"`
	// Formatter to convert error group to string representation.
	Formatter ErrorGroupFormatter `json:"-"`
}

ErrorGroup stores multiple Error instances.

TODO(ahawker) Flatten JSON output to a single error when group only has one.

func ErrorJoin added in v1.7.0

func ErrorJoin(err error, errs ...error) *ErrorGroup

ErrorJoin is a helper function that will append more errors onto an ErrorGroup.

If err is not already an ErrorGroup, then it will be turned into one. If any of the errs are ErrorGroup, they will be flattened one level into err. Any nil errors within errs will be ignored. If err is nil, a new *ErrorGroup will be returned containing the given errs.

func NewErrorGroup added in v1.12.0

func NewErrorGroup(errs ...error) *ErrorGroup

NewErrorGroup creates a new *ErrorGroup with sane defaults.

func NewTranslatedErrorGroup added in v1.22.0

func NewTranslatedErrorGroup(translate ErrorTranslate, errs ...error) *ErrorGroup

NewTranslatedErrorGroup creates a new *ErrorGroup with sane defaults and translated errors.

func (*ErrorGroup) Append

func (g *ErrorGroup) Append(errs ...error)

Append adds a new error to the group.

If the given error is not an Error instance, it will be wrapped with ErrUndefined.

func (*ErrorGroup) Empty

func (g *ErrorGroup) Empty() bool

Empty will return true if the group is empty.

func (*ErrorGroup) Error

func (g *ErrorGroup) Error() string

Error string value of the ErrorGroup struct.

Interface: error.

func (*ErrorGroup) ErrorOrNil

func (g *ErrorGroup) ErrorOrNil() error

ErrorOrNil returns an error interface if this Error represents a list of errors, or returns nil if the list of errors is empty. This function is useful at the end of accumulation to make sure that the value returned represents the existence of errors.

func (*ErrorGroup) GroupOrNil

func (g *ErrorGroup) GroupOrNil() *ErrorGroup

GroupOrNil returns the ErrorGroup interface if this group represents contains one or more errors. If it's empty, nil is returned.

func (*ErrorGroup) Len

func (g *ErrorGroup) Len() int

Len returns the number of errors in the group.

Interface: sort.Interface.

func (*ErrorGroup) Less

func (g *ErrorGroup) Less(i, j int) bool

Less determines order for sorting a group.

Interface: sort.Interface.

func (*ErrorGroup) Slice

func (g *ErrorGroup) Slice() []Error

Slice returns a slice of all errors in the group.

func (*ErrorGroup) Swap

func (g *ErrorGroup) Swap(i, j int)

Swap moves errors in the group during sorting.

Interface: sort.Interface.

func (*ErrorGroup) Translate added in v1.21.0

func (g *ErrorGroup) Translate(translate ErrorTranslate)

Translate performs an in-place translation of errors in the group for swapping context.

func (*ErrorGroup) Unwrap

func (g *ErrorGroup) Unwrap() error

Unwrap returns the next error in the group or nil if there are no more errors.

Interface: errors.Unwrap, HasUnwrap.

type ErrorGroupFormatter

type ErrorGroupFormatter func([]Error) string

ErrorGroupFormatter is a function callback that is called by ErrorGroup to turn the list of errors into a string.

type ErrorTranslate

type ErrorTranslate func(err error) error

ErrorTranslate defines function that can translate errors between two different contexts.

This is commonly used to convert between domain and adapter error types.

type FakeConstraintsNumeric added in v1.44.0

type FakeConstraintsNumeric[T constraints.Integer | constraints.Float] struct {
	// Cardinality is the number of distinct values.
	Cardinality uint64
	// Dataset is a set of values to choose from.
	Dataset []T
	// Min is the minimum value.
	Min T
	// Max is the maximum value.
	Max T
}

type FakeConstraintsTextual added in v1.44.0

type FakeConstraintsTextual[T ~string] struct {
	// Cardinality is the number of distinct values.
	Cardinality uint64
	// Dataset is a set of values to choose from.
	Dataset   []T
	MinLength uint64
	MaxLength uint64
}

type FakeNumber added in v1.44.0

type FakeNumber[T constraints.Integer | constraints.Float] struct {
	// Strategy to use for selecting fake values.
	Strategy FakeStrategy
	// State holds necessary persistent values for some strategies.
	State *FakeState[T]

	// Cardinality is the number of distinct values relative to the total number of generations.
	Cardinality uint64
	// Possible is a fixed set of values to choose from.
	Possible []T
	// Min is the minimum value.
	Min T
	// Max is the maximum value.
	Max T

	// RandomFn is a function that generates a random value without limitations.
	RandomFn func(ctx context.Context, n *FakeNumber[T]) T
	// RangeFn is a function that generates a random value within the bounds.
	RangeFn func(ctx context.Context, n *FakeNumber[T]) T
	// SelectFn is a function that generates a random value from a set of values.
	SelectFn func(ctx context.Context, n *FakeNumber[T]) T
	// StateFn is a function that generates a value based on some state/previous value.
	StateFn func(ctx context.Context, n *FakeNumber[T])
}

FakeNumber represents a fake number generator.

func (*FakeNumber[T]) Generate added in v1.44.0

func (n *FakeNumber[T]) Generate(ctx context.Context) T

Generate generates a fake number based on the configured options.

type FakeRequest added in v1.44.0

type FakeRequest struct {
	Generations uint64
	Rand        *rand.Rand
}

type FakeState added in v1.42.0

type FakeState[T any] struct {
	// Generation is the numeric value of the previous generation (incrementing).
	Generation uint64
	// Init is the initial stored value from the first generation.
	Init T
	// Curr is the stored value from the previous generation.
	Curr T
}

FakeState holds persistent values for some strategies.

type FakeStrategy added in v1.42.0

type FakeStrategy string

FakeStrategy represents a strategy for choosing a fake value.

unspecified: No strategy specified. random: Randomly generate a value with no bounds or limitations. random_range: Randomly select a value within the bounds. random_select: Randomly select a value from loaded set of values. random_pattern: Randomly select a value from a regex pattern. distribution_normal: Select a value from a normal distribution. distribution_uniform: Select a value from a uniform distribution. stateful: Select a value based on some state/previous value.

ENUM(unspecified, random, random_range, random_pattern, random_select, distribution_normal, distribution_uniform, stateful).

const (
	// FakeStrategyUnspecified is a FakeStrategy of type unspecified.
	FakeStrategyUnspecified FakeStrategy = "unspecified"
	// FakeStrategyRandom is a FakeStrategy of type random.
	FakeStrategyRandom FakeStrategy = "random"
	// FakeStrategyRandomRange is a FakeStrategy of type random_range.
	FakeStrategyRandomRange FakeStrategy = "random_range"
	// FakeStrategyRandomPattern is a FakeStrategy of type random_pattern.
	FakeStrategyRandomPattern FakeStrategy = "random_pattern"
	// FakeStrategyRandomSelect is a FakeStrategy of type random_select.
	FakeStrategyRandomSelect FakeStrategy = "random_select"
	// FakeStrategyDistributionNormal is a FakeStrategy of type distribution_normal.
	FakeStrategyDistributionNormal FakeStrategy = "distribution_normal"
	// FakeStrategyDistributionUniform is a FakeStrategy of type distribution_uniform.
	FakeStrategyDistributionUniform FakeStrategy = "distribution_uniform"
	// FakeStrategyStateful is a FakeStrategy of type stateful.
	FakeStrategyStateful FakeStrategy = "stateful"
)

func ParseFakeStrategy added in v1.42.0

func ParseFakeStrategy(name string) (FakeStrategy, error)

ParseFakeStrategy attempts to convert a string to a FakeStrategy.

func (FakeStrategy) IsValid added in v1.42.0

func (x FakeStrategy) IsValid() bool

IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values

func (FakeStrategy) MarshalText added in v1.42.0

func (x FakeStrategy) MarshalText() ([]byte, error)

MarshalText implements the text marshaller method.

func (FakeStrategy) String added in v1.42.0

func (x FakeStrategy) String() string

String implements the Stringer interface.

func (*FakeStrategy) UnmarshalText added in v1.42.0

func (x *FakeStrategy) UnmarshalText(text []byte) error

UnmarshalText implements the text unmarshaller method.

type FakeText added in v1.44.0

type FakeText[T ~string] struct {
	// Strategy to use for selecting fake values.
	Strategy FakeStrategy
	// State holds necessary persistent values for some strategies.
	State *FakeState[T]

	// Cardinality is the number of distinct values relative to the total number of generations.
	Cardinality uint64
	// Possible is a fixed set of values to choose from.
	Possible []T
	// Regex is a regular expression that the value must match.
	Regex *regexp.Regexp
	// MinLength is the minimum text length.
	MinLength uint64
	// MaxLength is the maximum text value.
	MaxLength uint64

	// RandomFn is a function that generates a random value without limitations.
	RandomFn func(ctx context.Context, t *FakeText[T]) T
	// RangeFn is a function that generates a random value within the bounds.
	RangeFn func(ctx context.Context, t *FakeText[T]) T
	// PatternFn is a function that generates a random value that matches a regular expression pattern.
	PatternFn func(ctx context.Context, t *FakeText[T]) T
	// SelectFn is a function that generates a random value from a set of values.
	SelectFn func(ctx context.Context, t *FakeText[T]) T
	// StateFn is a function that generates a value based on some state/previous value.
	StateFn func(ctx context.Context, t *FakeText[T])
}

func (*FakeText[T]) Generate added in v1.44.0

func (t *FakeText[T]) Generate(ctx context.Context) T

Generate generates fake text based on the configured options.

type HasAs

type HasAs interface {
	As(target any) bool
}

HasAs defines types necessary for stdlib `errors.As` support.

type HasIs

type HasIs interface {
	Is(target error) bool
}

HasIs defines types necessary for stdlib `errors.Is` support.

type HasUnwrap

type HasUnwrap interface {
	Unwrap() error
}

HasUnwrap defines types necessary for stdlib `errors.Unwrap` support.

type HelpExtras

type HelpExtras struct {
	// Links to help documentation regarding the error.
	Links []Link `json:"links,omitempty"`
}

HelpExtras contains helpful hyperlinks for the error.

func (HelpExtras) IsZero

func (e HelpExtras) IsZero() bool

IsZero returns true if the Extras object is the zero/empty struct value.

type KeyedMapper added in v1.24.0

type KeyedMapper[K comparable, VIn any, VOut any] func(k K, v VIn) VOut

KeyedMapper describes a 'map' function for a given key/value input.

type KeyedPredicate

type KeyedPredicate[K comparable, V any] func(k K, v V) bool

KeyedPredicate describes functions which return true/false based on a given key/value input.

type KeyedRanger

type KeyedRanger[K comparable, V any] interface {
	// Range calls the given function for all items available for iteration.
	//
	// If Range returns `false`, iteration will stop.
	Range(predicate KeyedPredicate[K, V])
}

KeyedRanger describes types that export a `Range` method for iteration over key/value collections.

type Link struct {
	URL         string
	Description string
}

Link contains a description and hyperlink.

type ListType added in v1.55.0

type ListType struct {
	ItemType DataType
	Items    []any
}

func List added in v1.55.0

func List(value any) (*ListType, error)

type Mapper added in v1.24.0

type Mapper[TIn any, TOut any] func(t TIn) TOut

Mapper describes a 'map' function applied to another type.

type Memoize

type Memoize[T any] struct {
	// Fn is called once and its result/error is cached.
	Fn func() (T, error)
	// contains filtered or unexported fields
}

Memoize is a simple struct that wraps a `sync.Once` to provide thread safe memoized results for costly computation.

func (*Memoize[T]) Get

func (m *Memoize[T]) Get() (T, error)

Get returns the value + error from the

type Option

type Option[T any] func(t T) error

Option defines functional options for type t.

func WithTaskCancel added in v1.56.0

func WithTaskCancel(fn TaskCancelFn) Option[*TaskConfig]

WithTaskCancel sets the cancel function for the task.

func WithTaskTimeout added in v1.56.0

func WithTaskTimeout(timeout time.Duration) Option[*TaskConfig]

WithTaskTimeout sets the timeout for the task.

type Optional added in v1.34.0

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

Optional wraps a value of type `T` tracks a default value and whether it changed.

func Default added in v1.34.0

func Default[T any](v T) *Optional[T]

Default creates an Optional with an empty value and distinct default value.

func Some added in v1.34.0

func Some[T any](v T) *Optional[T]

Some creates an Optional with a value.

func (*Optional[T]) Changed added in v1.34.0

func (o *Optional[T]) Changed() bool

Changed returns true if the value has been set.

func (*Optional[T]) Get added in v1.34.0

func (o *Optional[T]) Get() T

Get returns the value if it has been set, otherwise the default value.

func (*Optional[T]) Set added in v1.34.0

func (o *Optional[T]) Set(v T)

Set sets the value and marks it as changed.

type Predicate

type Predicate[T any] func(t T) bool

Predicate describes functions which return true/false based on a given input.

type Random added in v1.60.0

type Random struct {
	Rand   *rand.Rand
	Source rand.Source
	Seed   int64
}

Random represents a random number generator with its source and seed.

Callers are free to create their own and pass them into functions or use the 'Get' and 'Return' functions to borrow the global one.

func GetGlobal added in v1.60.0

func GetGlobal() *Random

GetGlobal returns the global Random instance and locks it for exclusive use.

func NewRandom added in v1.60.0

func NewRandom(seed int64) *Random

NewRandom creates a new Random instance with the provided seed.

type Ranger

type Ranger[T any] interface {
	// Range calls the given function for all items available for iteration.
	//
	// If Range returns `false`, iteration will stop.
	Range(predicate Predicate[T])
}

Ranger describes types that export a `Range` method for iteration over single item collections.

type RetryExtras

type RetryExtras struct {
	// Delay duration abide by before retrying the failed operation.
	Delay time.Duration
}

RetryExtras contains helpful information for dictating how/why retries can/should happen.

func (RetryExtras) IsZero

func (e RetryExtras) IsZero() bool

IsZero returns true if the Extras object is the zero/empty struct value.

type TaskCancelFn added in v1.56.0

type TaskCancelFn func(ctx context.Context) error

TaskCancelFn is a function that represents a task cancellation function.

type TaskConfig added in v1.56.0

type TaskConfig struct {
	// Timeout is the max duration for the task to run before cancellation.
	Timeout time.Duration
	// Cancel is the function to call when the task is cancelled.
	Cancel TaskCancelFn
	// CancelTimeout is the max duration for the 'TaskCancelFn' to run.
	CancelTimeout time.Duration
}

TaskConfig for a task execution.

type TaskFn added in v1.56.0

type TaskFn func(context.Context) error

TaskFn is a function that represents a task to be executed.

type Valid added in v1.13.0

type Valid[T any] struct {
	// Value of type T which has been validated.
	Value T
}

Valid is a struct that wraps an arbitrary value to indicate that it is valid and has passed all checks.

func ValidCheck added in v1.13.0

func ValidCheck[T any](t T, validators ...Validator[T]) (*Valid[T], error)

ValidCheck applies all functional validators to type t and returns the error if any fail to apply.

If all return successfully, a Valid[T] is returned.

type Validator added in v1.13.0

type Validator[T any] func(t T) error

Validator defines functional validator for type t.

type Zeroer

type Zeroer interface {
	// IsZero returns true if the value of the instance is equal
	// to the "zero" value of the type.
	IsZero() bool
}

Zeroer describes types that support `IsZero` checks.

Jump to

Keyboard shortcuts

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