This package contains simple mechanisms used by other darvaza-proxy projects. It's not allowed to have dependencies outside of Go's Standard Library, and if something should be on a subdirectory, it shouldn't be here.
Generic type constraints for use with Go generics:
Signed
- signed integer typesUnsigned
- unsigned integer typesInteger
- all integer types (signed and unsigned)Float
- floating-point typesComplex
- complex number typesBool
- boolean typeString
- string typeOrdered
- types that support ordering operations
ContextKey[T]
- type-safe context key typeNewContextKey[T]()
creates a ContextKey adding type-safety and ease of use to the standardcontext.WithValue()
WithTimeout()
andWithTimeoutCause()
are equivalent tocontext.WithDeadline()
andcontext.WithDeadlineCause()
but receiving a duration instead of an absolute time
GetIPAddresses()
- get IP addresses asnetip.Addr
GetNetIPAddresses()
- get IP addresses asnet.IP
GetStringIPAddresses()
- get IP addresses as stringsAddrFromNetIP(ip)
- convertnet.IP
tonetip.Addr
ParseAddr(s)
- parse string tonetip.Addr
ParseNetIP(s)
- parse string tonet.IP
SplitHostPort(hostport)
- split host:port stringSplitAddrPort(addrport)
- split address:port stringJoinHostPort(host, port)
- join host and portMakeHostPort(host, port)
- create host:port stringAddrPort(addr, port)
- createnetip.AddrPort
GetInterfacesNames()
- get network interface names
Zero[T]()
returns the zero value for type TIsZero[T](v)
checks if a value is the zero value for its typeCoalesce[T](values...)
returns the first non-zero valueIIf[T](condition, ifTrue, ifFalse)
conditional expression
As[T,V](v)
attempts to convert value to target typeAsFn[T,V](v, fn)
converts value using a provided functionAsError[T](v)
attempts to convert value to errorAsErrors[T](v)
attempts to convert value to error slice
SliceContains[T]
/SliceContainsFn[T]
SliceEqual[T]
/SliceEqualFn[T]
SliceAs[T,V]
/SliceAsFn[T,V]
SliceMap[T1,T2]
- maps slice elements to new typeSliceReplaceFn[T]
- replaces elements matching conditionSliceCopy[T]
/SliceCopyFn[T]
SliceMinus[T]
/SliceMinusFn[T]
- set differenceSliceUnique[T]
/SliceUniqueFn[T]
- unique elementsSliceUniquify[T]
/SliceUniquifyFn[T]
- remove duplicates in-place
SliceSort[T]
/SliceSortFn[T]
/SliceSortOrdered[T]
SliceReverse[T]
/SliceReversed[T]
/SliceReversedFn[T]
SliceRandom[T]
- random element selection
ListContains[T]
/ListContainsFn[T]
ListForEach[T]
/ListForEachElement
ListForEachBackward[T]
/ListForEachBackwardElement
ListCopy[T]
/ListCopyFn[T]
MapContains[K]()
checks if a map contains a keyMapValue[K,V]()
returns the value for a key, or a fallback valueKeys[K,T]()
returns a slice of the keys in the mapSortedKeys[K,T]()
returns a sorted slice of the keysSortedValues[K,T]()
returns values sorted by keySortedValuesCond[K,T]()
returns filtered values sorted by keySortedValuesUnlikelyCond[K,T]()
likeSortedValuesCond
but more efficient
MapListContains[K,T]
/MapListContainsFn[K,T]
MapListForEach[K,T]
/MapListForEachElement[K]
MapListInsert[K,T]
/MapListAppend[K,T]
MapListInsertUnique[K,T]
/MapListInsertUniqueFn[K,T]
MapListAppendUnique[K,T]
/MapListAppendUniqueFn[K,T]
MapListCopy[T]
/MapListCopyFn[K,V]
MapAllListContains[K,T]
/MapAllListContainsFn[K,T]
MapAllListForEach[K,T]
/MapAllListForEachElement[K]
Predefined error values for common conditions:
ErrNotImplemented
- functionality not yet implementedErrTODO
- placeholder for future implementationErrExists
- resource already existsErrNotExists
- resource does not existErrInvalid
- invalid input or stateErrUnknown
- unknown or unspecified errorErrNilReceiver
- method called on nil receiverErrUnreachable
- indicates impossible condition
The Unwrappable
interface represents the classic Unwrap() error
pattern,
implemented by WrappedError
. The Errors
interface represents multi-error
containers with Errors() []error
.
Error wrapping functions:
Wrap(err, note)
- wrap with simple string noteWrapf(err, format, args...)
- wrap with formatted noteQuietWrap(err, note)
- wrap without including original error textUnwrap(err) []error
- extract all sub-errors from wrapped errors
The CompoundError
type aggregates multiple errors:
- Implements both
Unwrap() []error
andErrors() []error
interfaces .AppendError(err)
/.Append(errs...)
- add errors.AsError()
- convert to single error or nil.Ok()
- check if no errors
The PanicError
type wraps panic values with stack traces:
NewPanicError()
/NewPanicErrorf()
- create panic errorsNewPanicWrap()
/NewPanicWrapf()
- wrap existing errors as panicsPanic()
/Panicf()
/PanicWrap()
/PanicWrapf()
- panic withPanicError
Panic recovery utilities:
Recovered
interface - marks errors from recovered panicsAsRecovered(v)
- convertrecover()
result to errorCatcher
type - safely call functions that might panicCatch(fn)
- execute function, returning error if panic occurs
defer func() {
if err := core.AsRecovered(recover()); err != nil {
// handle panic as error
}
}()
For indicating impossible code paths:
NewUnreachableError()
- create unreachable errorNewUnreachableErrorf(format, args...)
- create formatted unreachable error
These create PanicError
instances with stack traces.
Special error types for network-style temporary and timeout conditions:
TemporaryError
type - implementsTemporary() bool
NewTemporaryError(err)
- wrap error as temporaryNewTimeoutError(err)
- wrap error as timeoutIsTemporary(err)
/CheckIsTemporary(err)
- test if error is temporaryIsTimeout(err)
/CheckIsTimeout(err)
- test if error is timeout
IsError[T](err)
/IsErrorFn[T](err, fn)
/IsErrorFn2[T](err, fn)
- type-safe error testingCoalesceError(errs...)
- return first non-nil error
Utilities for capturing and working with call stacks:
Frame
- represents a single stack frameStack
- represents a call stackMaxDepth
- maximum stack depth constantCallStacker
interface - types that provide call stacks
Here()
- capture current stack frameStackFrame(skip)
- capture-specific stack frameStackTrace(skip, depth)
- capture call stack
.Name()
/.FuncName()
/.PkgName()
- function/package names.SplitName()
- split full name into package and function.File()
/.Line()
/.FileLine()
- source location.Format()
- formatted representation
Enhanced wait group with error handling:
WaitGroup
- wait group that collects errors.OnError(fn)
- set error handler.Go(fn)
/.GoCatch(fn)
- run functions in goroutines.Wait()
- wait for completion.Err()
- get first error
Context-aware error group with cancellation:
ErrGroup
- context-based error group.SetDefaults()
- configure with defaults.OnError(fn)
- set error handler.Cancel()
/.Context()
- cancellation control.Go(fn)
/.GoCatch(fn)
- run functions with context.Wait()
- wait and return first error.IsCancelled()
/.Cancelled()
- check cancellation state
SpinLockDeprecated in favour of darvaza.org/x/sync/spinlock