gg

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2022 License: Unlicense Imports: 20 Imported by: 3

README

Overview

Essential utilities missing from the Go standard library.

Docs: https://pkg.go.dev/github.com/mitranim/gg

Features:

  • Designed for Go 1.18. Takes massive advantage of generics.
  • Errors with stack traces.
  • Various functional programming utilities: map, filter, fold, and more.
  • Various shortcuts for reflection.
  • Various shortcuts for manipulating slices.
  • Various shortcuts for manipulating maps.
  • Various shortcuts for manipulating strings.
  • Common-sense generic data types: zero optionals, true optionals, sets, indexed collections, and more.
  • Various utilities for exception-style error handling, using panic and recover.
  • Various utilities for testing.
    • Assertion shortcuts with descriptive errors and full stack traces.
  • Carefully designed for compatibility with standard interfaces and interfaces commonly supported by 3rd parties.
  • No over-modularization.
  • No external dependencies.

Current limitations:

  • Not fully tested.
  • Not fully documented.

License

https://unlicense.org

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	Indent  = `    `
	Space   = ` `
	Newline = "\n"
)
View Source
var (
	TraceTable     = true
	TraceSkipLang  = true
	TraceShortName = true
	TraceRelPath   = false // Disabled by default due to cost.
)

These variables control how stack traces are printed.

View Source
var ReWord = Lazy1(
	regexp.MustCompile,
	`\p{Lu}[\p{Ll}\d]*|\p{Lu}[\p{Lu}\d]*|\p{Ll}[\p{Ll}\d]*`,
)

Regexp for splitting arbitrary text into words, Unicode-aware. Used by `ToWords`.

View Source
var StructFieldCache = TypeCacheOf[StructFields]()

Functions

func AnyIs

func AnyIs[A any](src any) bool

Returns true if the given `any` can be usefully converted into a value of the given type. If the result is true, `src.(A)` doesn't panic. If the output is false, `src.(A)` panics.

func AnyNoEscUnsafe

func AnyNoEscUnsafe(src any) any

Dangerous tool for performance fine-tuning.

func AnyTo

func AnyTo[A any](src any) A

Non-asserting interface conversion. Safely converts the given `any` into the given type, returning zero value on failure.

func AnyToString

func AnyToString(src any) (string, bool)

If the underlying type is compatible with `Text`, unwraps and converts it to a string. Otherwise returns zero value. Boolean indicates success.

func AnyToText

func AnyToText[A Text](src any) (A, bool)

If the underlying type is compatible with `Text`, unwraps and converts it to the given text type. Otherwise returns zero value. Boolean indicates success. If the given value is backed by `string` but the output type is backed by `[]byte`, or vice versa, this performs a copy. Otherwise this doesn't allocate.

func Append

func Append[A ~[]byte, B any](buf A, src B) A

Appends text representation of the input to the given buffer, using `AppendCatch`. Panics on errors.

func AppendCatch

func AppendCatch[A ~[]byte, B any](buf A, src B) (A, error)

Same as `StringCatch`, but instead of returning a string, appends the text representation of the input to the given buffer. See `StringCatch` for the encoding rules.

func AppendGoString

func AppendGoString[A any](inout []byte, val A) []byte

Appends the `fmt.GoStringer` representation of the given input to the given buffer. Also see the function `GoString`.

func AppendNull

func AppendNull[A any, B NullableValGetter[A]](buf []byte, src B) []byte

Shortcut for implementing string encoding of `Nullable` types. Mostly for internal use.

func AppendPtr

func AppendPtr[Slice ~[]Elem, Elem any](tar *Slice, val Elem) *Elem

Appends the given element to the given slice, returning the pointer to the newly appended position in the slice.

func AppendPtrZero

func AppendPtrZero[Slice ~[]Elem, Elem any](tar *Slice) *Elem

Appends a zero element to the given slice, returning the pointer to the newly appended position in the slice.

func AppendTo

func AppendTo[Slice ~[]Elem, Elem any](tar *Slice, val Elem)

Appends the given element to the given slice. Similar to built-in `append` but less noisy.

func AppenderString

func AppenderString[A Appender](val A) string

Shortcut for stringifying a type that implements `Appender`. Mostly for internal use.

func Cap

func Cap[Slice ~[]Elem, Elem any](val Slice) int

Same as `cap(val)` but can be passed to higher-order functions.

func CastUnsafe

func CastUnsafe[Out, Src any](val Src) Out

Self-explanatory. Slightly cleaner and less error prone than direct use of unsafe pointers.

func Catch

func Catch(fun func()) (err error)

Runs the given function, converting a panic to an error. Idempotently adds a stack trace.

func Catch01

func Catch01[A any](fun func() A) (val A, err error)

Runs the given function, returning the function's result along with its panic converted to an error. Idempotently adds a stack trace.

func Catch10

func Catch10[A any](fun func(A), val A) (err error)

Runs the given function with the given input, converting a panic to an error. Idempotently adds a stack trace.

func Catch11

func Catch11[A, B any](fun func(A) B, val0 A) (val1 B, err error)

Runs the given function with the given input, returning the function's result along with its panic converted to an error. Idempotently adds a stack trace.

func CatchOnly

func CatchOnly(test func(error) bool, fun func()) (err error)

Runs a given function, converting a panic to an error IF the error satisfies the provided test. Idempotently adds a stack trace.

func Caught

func Caught(fun func()) bool

Shortcut for `Catch() != nil`. Useful when you want to handle all errors while ignoring their content.

func CaughtOnly

func CaughtOnly(test func(error) bool, fun func()) bool

Shortcut for `CatchOnly() != nil`. Useful when you want to handle a specific error while ignoring its content.

func Clear

func Clear[A any](val *A)

Zeroes the memory referenced by the given pointer. If the pointer is nil, this is a nop.

func Clone

func Clone[Slice ~[]Elem, Elem any](src Slice) Slice

Returns a shallow copy of the given slice. The capacity of the resulting slice is equal to its length.

func CloneAppend

func CloneAppend[Slice ~[]Elem, Elem any](src Slice, val ...Elem) Slice

Same as `append`, but makes a copy instead of mutating the original. Useful when reusing one "base" slice for in multiple append calls.

func Close

func Close(val io.Closer)

If the given closer is non-nil, closes it, ignoring the error.

func Compact

func Compact[Slice ~[]Elem, Elem any](src Slice) Slice

Returns a version of the given slice without any zero values.

func Conc

func Conc(val ...func())

Concurrently runs the given functions.

func ConcCatch

func ConcCatch(val ...func()) []error

Concurrently runs the given functions, returning their panics.

func ConcEach

func ConcEach[A any](src []A, fun func(A))

Concurrently calls the given function on each element of the given slice.

func ConcEachCatch

func ConcEachCatch[A any](src []A, fun func(A)) []error

Concurrently calls the given function on each element of the given slice, returning the resulting panics if any.

func ConcMap

func ConcMap[A, B any](src []A, fun func(A) B) []B

Like `Map` but concurrent.

func ConcMapCatch

func ConcMapCatch[A, B any](src []A, fun func(A) B) ([]B, []error)

Like `Map` but concurrent. Returns the resulting values along with the caught panics, if any.

func ConcMapFunc

func ConcMapFunc[A, B any](out *[]B, src []A, fun func(A) B) func()

Partial application / thunk of `ConcMap`, suitable for `Conc`.

func Concat

func Concat[Slice ~[]Elem, Elem any](val ...Slice) Slice

Concatenates the inputs. If no inputs are given, the output is nil.

func Count

func Count[A any](src []A, fun func(A) bool) int

Counts the number of elements for which the given function returns true.

func CtxGet

func CtxGet[A any](ctx context.Context) A

Same as `CtxGot` but returns only the resulting value. If value was not found, output is zero.

func CtxGot

func CtxGot[A any](ctx context.Context) (A, bool)

Uses `ctx.Value` to get the value of the given type, using the type's nil pointer "(*A)(nil)" as the key. If the context is nil or doesn't contain the value, returns zero value and false.

func CtxHas

func CtxHas[A any](ctx context.Context) bool

Same as `CtxGot` but returns only the boolean.

func CtxSet

func CtxSet[A any](ctx context.Context, val A) context.Context

Uses `context.WithValue` to create a context with the given value, using the type's nil pointer "(*A)(nil)" as the key.

func Cwd

func Cwd() string

Shortcut for `os.Getwd` that panics on error.

func Dec

func Dec[A Num](val A) A

Same as input - 1.

func Deref

func Deref[A any](val *A) A

If the pointer is non-nil, dereferences it. Otherwise returns zero value.

func DetailOnlyf

func DetailOnlyf(test func(error) bool, pat string, val ...any)

Must be deferred. Wraps non-nil panics, prepending the error message, ONLY if they satisfy the provided test. Idempotently adds a stack trace.

func Detailf

func Detailf(pat string, val ...any)

Must be deferred. Wraps non-nil panics, prepending the error message and idempotently adding a stack trace. Usage:

defer gg.Detailf(`unable to %v`, `do X`)

func Drop

func Drop[Slice ~[]Elem, Elem any](src Slice, size int) Slice

Returns a subslice excluding N elements from the start.

func DropWhile

func DropWhile[Slice ~[]Elem, Elem any](src Slice, fun func(Elem) bool) Slice

Returns a subslice excluding elements at the start of the slice for which the given function contiguously returned `true`.

func Each

func Each[A any](val []A, fun func(A))

Calls the given function for each element of the given slice.

func Each2

func Each2[A, B any](one []A, two []B, fun func(A, B))

Similar to `Each` but iterates two slices pairwise. If slice lengths don't match, panics.

func EachPtr

func EachPtr[A any](val []A, fun func(*A))

Calls the given function for each element's pointer in the given slice. The pointer is always non-nil.

func Eq

func Eq[A comparable](one, two A) bool

Same as `==`. Sometimes useful with higher-order functions.

func EqNonZero

func EqNonZero[A comparable](one, two A) bool

True if both inputs are not zero values of their type, and are equal to each other via `==`.

func Equal

func Equal[A any](one, two A) bool

Short for "equal". Same as `reflect.DeepEqual` but with better type safety and performance.

func ErrConv

func ErrConv(src any, typ r.Type) error

Returns an error that describes a failure to convert the given input to the given output type. Used internally in various conversions.

func ErrParse

func ErrParse[A Text](err error, src A, typ r.Type) error

Returns an error that describes a failure to decode the given string into the given output type. Used internally in various conversions.

func ErrString

func ErrString(val error) string

If the error is nil, returns “. Otherwise uses `.Error`.

func ErrTraced

func ErrTraced(err error, skip int) error

Idempotently adds a stack trace, skipping the given number of frames.

func Every

func Every[A any](src []A, fun func(A) bool) bool

True if the given function returns true for every element of the given slice. False if the function is nil. True if the slice is empty.

func EveryPair

func EveryPair[A any](one, two []A, fun func(A, A) bool) bool

Utility for comparing slices pairwise. Returns true if the slices have the same length and the function returns true for every pair.

func Exclude

func Exclude[Slice ~[]Elem, Elem comparable](base Slice, sub ...Elem) Slice

Returns a version of the given slice excluding any additionally supplied values.

func Fail

func Fail(fun func(error))

Must be deferred. Runs the function ONLY if there's an ongoing panic, and then re-panics. Idempotently adds a stack trace.

func Fellback

func Fellback[A any](tar *A, fallback A) bool

Takes a pointer and a fallback value which must be non-zero. If the pointer destination is zero, sets the fallback and returns true. Otherwise returns false.

func FieldDbName

func FieldDbName(val r.StructField) string

Returns the field's DB/SQL column name from the "db" tag, following the same conventions as the `encoding/json` package.

func FieldJsonName

func FieldJsonName(val r.StructField) string

Returns the field's JSON column name from the "json" tag, following the same conventions as the `encoding/json` package.

func Filter

func Filter[Slice ~[]Elem, Elem any](src Slice, fun func(Elem) bool) Slice

Returns only the elements for which the given function returned `true`.

func Finally

func Finally(fun func(error))

Must be deferred. Always runs the given function, passing either the current panic or nil. If the error is non-nil, re-panics.

func Find

func Find[A any](src []A, fun func(A) bool) A

Returns the first element for which the given function returns true. If nothing is found, returns a zero value.

func FindIndex

func FindIndex[A any](src []A, fun func(A) bool) int

Tests each element by calling the given function and returns the first element for which it returns `true`. If none match, returns `-1`.

func Fold

func Fold[Acc, Val any](src []Val, acc Acc, fun func(Acc, Val) Acc) Acc

Folds the given slice by calling the given function for each element, additionally passing the "accumulator". Returns the resulting accumulator.

func Fold1

func Fold1[A any](src []A, fun func(A, A) A) A

Similar to `Fold` but uses the first slice element as the accumulator, falling back on zero value. The given function is invoked only for 2 or more elements.

func Foldz

func Foldz[Acc, Val any](src []Val, fun func(Acc, Val) Acc) Acc

Similar to `Fold` but accumulator automatically starts with zero value.

func ForkReadCloser

func ForkReadCloser(src io.ReadCloser) (_, _ io.ReadCloser)

Fully reads the given stream via `io.ReadAll`, closing it at the end, and returns two "forks". Used internally by `(*gh.Req).CloneBody` and `(*gh.Res).CloneBody`. If reading fails, panics. If the input is nil, both outputs are nil.

func Found

func Found[A any](src []A, fun func(A) bool) (A, bool)

Returns the first element for which the given function returns `true`. If nothing is found, returns a zero value. The additional boolean indicates whether something was actually found.

func FuncName

func FuncName(val any) string

Takes an arbitrary function and returns its name.

func FuncNameBase

func FuncNameBase(fun *rt.Func) string

Returns the given function's name without the package path prefix.

func FuncNameShort

func FuncNameShort(name string) string

Returns the name of the given function stripped of various namespaces: package path prefix, package name, type name.

func Get

func Get[A any](src []A, ind int) A

If the index is within bounds, returns the value at that index. Otherwise returns zero value.

func GetNull

func GetNull[A any, B NullableValGetter[A]](val B) any

Shortcut for implementing `Getter` on `Nullable` types that wrap other types, such as `Opt`. Mostly for internal use.

func GetOpt

func GetOpt(src any) any

If the input implements `Getter`, unwraps it by calling `.Get`. Otherwise returns the input as-is. Mostly for internal use.

func GetPtr

func GetPtr[A any](src []A, ind int) *A

If the index is within bounds, returns a pointer to the value at that index. Otherwise returns nil.

func GoString

func GoString[A any](val A) string

Returns the `fmt.GoStringer` representation of the given input. Equivalent to `fmt.Sprintf("%#v", val)` but marginally more efficient.

func Got

func Got[A any](src []A, ind int) (A, bool)

If the index is within bounds, returns the value at that index and true. Otherwise returns zero value and false.

func GrowCap

func GrowCap[Slice ~[]Elem, Elem any](src Slice, size int) Slice

Missing feature of the language / standard library. Grows the slice to ensure at least this much additional capacity (not total capacity), returning a modified version of the slice. The returned slice always has the same length as the original, but its capacity and backing array may have changed. This doesn't ensure EXACTLY the given additional capacity. It follows the usual hidden Go rules for slice growth, and may allocate significantly more than asked. Similar to `(*bytes.Buffer).Grow` but without wrapping, unwrapping, or spurious escapes to the heap.

TODO variant that grows capacity to the given TOTAL amount.

func GrowLen

func GrowLen[Slice ~[]Elem, Elem any](src Slice, size int) Slice

Grows the length of the given slice by appending N zero values.

func Has

func Has[A comparable](src []A, val A) bool

True if the given slice contains the given value. Should be used ONLY for very small inputs: no more than a few tens of elements. For larger data, consider using indexed data structures such as maps.

func HasAll

func HasAll[A comparable](src, exp []A) bool

True if the first slice has all elements from the second slice. In other words, true if A is a superset of B: A >= B. Should be used ONLY for very small inputs: no more than a few tens of elements.

func HasLen

func HasLen[Slice ~[]Elem, Elem any](val Slice) bool

True if slice length is above 0.

func HasNewlineSuffix

func HasNewlineSuffix[A Text](val A) bool

True if the string ends with a line feed or carriage return.

func HasNone

func HasNone[A comparable](src, exp []A) bool

True if the first slice has NO elements from the second slice. In other words, true if the sets A and B don't intersect. Should be used ONLY for very small inputs: no more than a few tens of elements.

func Head[A any](val []A) A

Returns the first element of the given slice. If the slice is empty, returns the zero value.

func HeadPtr

func HeadPtr[A any](val []A) *A

Returns a pointer to the first element of the given slice. If the slice is empty, the pointer is nil.

func Id1

func Id1[A any](val A) A

Identity function. Returns input as-is.

func Id2

func Id2[A, B any](val0 A, val1 B) (A, B)

Identity function. Returns input as-is.

func Id3

func Id3[A, B, C any](val0 A, val1 B, val2 C) (A, B, C)

Identity function. Returns input as-is.

func Inc

func Inc[A Num](val A) A

Same as input + 1.

func Init

func Init[Slice ~[]Elem, Elem any](val Slice) Slice

Returns the initial part of the given slice: all except the last value. If the slice is nil, returns nil.

func Intersect

func Intersect[Slice ~[]Elem, Elem comparable](one, two Slice) Slice

Returns intersection of two slices: elements that occur in both.

func IsEmpty

func IsEmpty[Slice ~[]Elem, Elem any](val Slice) bool

True if slice length is 0. The slice may or may not be nil.

func IsErrNil

func IsErrNil(val error) bool

func IsErrNonNil

func IsErrNonNil(val error) bool

func IsErrTraced

func IsErrTraced(val error) bool

True if the error has a stack trace. Relies on a hidden interface implemented by `Err`.

func IsNeg

func IsNeg[A Signed](val A) bool

True if the given number is < 0.

func IsNonNull

func IsNonNull[A Nullable](val A) bool

Inverse of `IsNull`.

func IsNonZero

func IsNonZero[A any](val A) bool

True if the input is not a zero value of its type.

func IsNonZeroComp

func IsNonZeroComp[A comparable](val A) bool

True if the input is not a zero value of its type. For non-`comparable` types, use `IsNonZero`.

func IsNull

func IsNull[A Nullable](val A) bool

Generic variant of `Nullable.IsNull`.

func IsPos

func IsPos[A Signed](val A) bool

True if the given number is > 0.

func IsStrEmpty

func IsStrEmpty[A Text](val A) bool

True if len == 0.

func IsStrNonEmpty

func IsStrNonEmpty[A Text](val A) bool

True if len > 0.

func IsTypeBytes

func IsTypeBytes(typ r.Type) bool

True if the type is convertible to `[]byte`.

func IsValueBytes

func IsValueBytes(val r.Value) bool

True if the value's underlying type is convertible to `[]byte`.

func IsZero

func IsZero[A any](val A) bool

True if the input is a zero value of its type.

func IsZeroComp

func IsZeroComp[A comparable](val A) bool

True if the given value is a zero value of its type. For non-`comparable` types, use `IsZero`.

func Iter

func Iter(size int) []struct{}

Short for "iterator". Returns a slice of the given length that can be iterated by using a `range` loop. Usage:

for range Iter(size) { ... }
for i := range Iter(size) { ... }

Because `struct{}` is zero-sized, `[]struct{}` is backed by "zerobase" (see Go source → "runtime/malloc.go") and does not allocate. The example loops should compile to approximately the same instructions as "normal" counted loops.

func JoinLines

func JoinLines(val ...string) string

Joins the given strings with newlines.

func JoinLinesOpt

func JoinLinesOpt[A Text](val ...A) string

Joins non-empty strings with newlines.

func JoinOpt

func JoinOpt[A Text](val []A, sep string) string

Similar to `strings.Join` but ignores empty strings.

func JsonBytes

func JsonBytes[A any](val A) []byte

Uses `json.Marshal` to encode the given value as JSON, panicking on error.

func JsonBytesCatch

func JsonBytesCatch[A any](val A) ([]byte, error)

Same as `json.Marshal` but sometimes marginally more efficient. Avoids spurious heap escape of the input.

func JsonBytesIndent

func JsonBytesIndent[A any](val A) []byte

Uses `json.MarshalIndent` to encode the given value as JSON with indentation controlled by the `Indent` variable, panicking on error.

func JsonBytesIndentCatch

func JsonBytesIndentCatch[A any](val A) ([]byte, error)

Same as `json.MarshalIndent`, but uses the default indentation controlled by the `Indent` variable. Also sometimes marginally more efficient. Avoids spurious heap escape of the input.

func JsonBytesNullCatch

func JsonBytesNullCatch[A any, B NullableValGetter[A]](val B) ([]byte, error)

Shortcut for implementing JSON encoding of `Nullable` types. Mostly for internal use.

func JsonDecodeClose

func JsonDecodeClose[A any](src io.ReadCloser, out *A)

Uses `json.Decoder` to decode one JSON entry/line from the reader, writing to the given output. Always closes the reader. Panics on errors.

func JsonDecodeFile

func JsonDecodeFile[A any](path string, out *A)

Shortcut for decoding the content of the given file into a pointer of the given type. Panics on error.

func JsonDecodeFileTo

func JsonDecodeFileTo[A any](path string) (out A)

Shortcut for decoding the content of the given file into a value of the given type. Panics on error.

func JsonParse

func JsonParse[Out any, Src Text](src Src, out *Out)

Shortcut for parsing the given string or byte slice into a pointer of the given type. Panics on errors.

func JsonParseCatch

func JsonParseCatch[Out any, Src Text](src Src, out *Out) error

Parses the given string or byte slice into a pointer of the given type. Similar to `json.Unmarshal`, but avoids the overhead of byte-string conversion and spurious escapes.

func JsonParseClearCatch

func JsonParseClearCatch[
	Out any,
	Tar ClearerPtrGetter[Out],
	Src Text,
](src Src, tar Tar) error

Shortcut for implementing JSON decoding of types that wrap other types, such as `Opt`. Mostly for internal use.

func JsonParseTo

func JsonParseTo[Out any, Src Text](src Src) (out Out)

Shortcut for parsing the given string or byte slice into a value of the given type. Panics on errors.

func JsonString

func JsonString[A any](val A) string

Encodes the input as a JSON string, panicking on error.

func JsonStringIndent

func JsonStringIndent[A any](val A) string

Encodes the input as a JSON string, using default indentation controlled by the `Indent` variable.

func Kind

func Kind[A any]() r.Kind

Returns `reflect.Kind` of the given type. Never returns `reflect.Invalid`. If the type parameter is an interface, the output is `reflect.Interface`.

func KindOf

func KindOf[A any](A) r.Kind

Returns `reflect.Kind` of the given type. Never returns `reflect.Invalid`. If the type parameter is an interface, the output is `reflect.Interface`.

func KindOfAny

func KindOfAny(val any) r.Kind

Returns `reflect.Kind` of the given `any`. Compare our generic functions `Kind` and `KindOf` which take a concrete type.

func Last

func Last[A any](val []A) A

Returns the last element of the given slice. If the slice is empty, returns the zero value.

func LastPtr

func LastPtr[A any](val []A) *A

Returns a pointer to the last element of the given slice. If the slice is empty, the pointer is nil.

func Lazy

func Lazy[A any](fun func() A) func() A

Takes a function that ought to be called no more than once. Returns a function that caches and reuses the result of the original function. Uses `sync.Once` internally.

func Lazy1

func Lazy1[A, B any](fun func(B) A, val B) func() A

Variant of `Lazy` that takes an additional argument and passes it to the given function when it's executed, which happens no more than once.

func Lazy2

func Lazy2[A, B, C any](fun func(B, C) A, val0 B, val1 C) func() A

Variant of `Lazy` that takes additional arguments and passes them to the given function when it's executed, which happens no more than once.

func Lazy3

func Lazy3[A, B, C, D any](fun func(B, C, D) A, val0 B, val1 C, val2 D) func() A

Variant of `Lazy` that takes additional arguments and passes them to the given function when it's executed, which happens no more than once.

func Len

func Len[Slice ~[]Elem, Elem any](val Slice) int

Same as `len(val)` but can be passed to higher-order functions.

func Lens

func Lens[Slice ~[]Elem, Elem any](val ...Slice) int

Counts the total length of the given slices.

func Locked

func Locked[A interface{ Lock() }](val A) A

func Map

func Map[A, B any](src []A, fun func(A) B) []B

Maps one slice to another. The resulting slice has exactly the same length as the original. Each element is created by calling the given function on the corresponding element of the original slice. The name refers to a well-known functional programming abstraction which doesn't have anything in common with the Go `map` types. Unlike many other higher-order slice functions, this one requires a non-nil function.

func MapClear

func MapClear[Map ~map[Key]Val, Key comparable, Val any](tar Map) map[Key]Val

func MapClone

func MapClone[Coll ~map[Key]Val, Key comparable, Val any](src Coll) Coll

func MapCompact

func MapCompact[A, B any](src []A, fun func(A) B) []B

Similar to `Map` but excludes any zero values produced by the given function.

func MapDel

func MapDel[Map ~map[Key]Val, Key comparable, Val any](tar Map, key Key) map[Key]Val

func MapGet

func MapGet[Map ~map[Key]Val, Key comparable, Val any](tar Map, key Key) Val

func MapGot

func MapGot[Map ~map[Key]Val, Key comparable, Val any](tar Map, key Key) (Val, bool)

func MapHas

func MapHas[Map ~map[Key]Val, Key comparable, Val any](tar Map, key Key) bool

func MapInit

func MapInit[Map ~map[Key]Val, Key comparable, Val any](val Map) Map

func MapKeys

func MapKeys[Key comparable, Val any](src map[Key]Val) []Key

func MapPtrInit

func MapPtrInit[Map ~map[Key]Val, Key comparable, Val any](val *Map) Map

func MapSet

func MapSet[Map ~map[Key]Val, Key comparable, Val any](tar Map, key Key, val Val) map[Key]Val

func MapVals

func MapVals[Key comparable, Val any](src map[Key]Val) []Val

func Marshal

func Marshal(val any) ([]byte, error)

Shortcut for implementing `encoding.TextMarshaler` on arbitrary types. Mostly for internal use. Uses `StringCatch` internally. The resulting bytes may be backed by constant storage and must not be mutated.

func MarshalNullCatch

func MarshalNullCatch[A any, B NullableValGetter[A]](val B) ([]byte, error)

Shortcut for implementing `encoding.TextMarshaler` on `Nullable` types. Mostly for internal use. Uses `StringCatch` internally. The resulting bytes may be backed by constant storage and must not be mutated.

func Max

func Max[A Lesser[A]](val ...A) A

Returns the largest value from among the inputs. For primitive types that don't implement `Lesser`, see `MaxPrim`.

func Max2

func Max2[A Lesser[A]](one, two A) A

Returns the larger of the two inputs. For primitive types that don't implement `Lesser`, see `MaxPrim2`.

func MaxBy

func MaxBy[Src any, Out Lesser[Out]](src []Src, fun func(Src) Out) Out

Calls the given function for each element of the given slice and returns the largest value from among the results. For primitive types that don't implement `Lesser`, see `MaxPrimBy`.

func MaxPrim

func MaxPrim[A LesserPrim](val ...A) A

Returns the largest value from among the inputs, which must be comparable primitives. For non-primitives, see `Max`.

func MaxPrim2

func MaxPrim2[A LesserPrim](one, two A) A

Returns the larger of the two inputs, which must be comparable primitives. For non-primitives, see `Max2`.

func MaxPrimBy

func MaxPrimBy[Src any, Out LesserPrim](src []Src, fun func(Src) Out) Out

Calls the given function for each element of the given slice and returns the largest value from among the results, which must be comparable primitives. For non-primitives, see `MaxBy`.

func Min

func Min[A Lesser[A]](val ...A) A

Returns the smallest value from among the inputs. For primitive types that don't implement `Lesser`, see `MinPrim`.

func Min2

func Min2[A Lesser[A]](one, two A) A

Returns the lesser of the two inputs. For primitive types that don't implement `Lesser`, see `MinPrim2`.

func MinBy

func MinBy[Src any, Out Lesser[Out]](src []Src, fun func(Src) Out) Out

Calls the given function for each element of the given slice and returns the smallest value from among the results. For primitive types that don't implement `Lesser`, see `MinPrimBy`.

func MinPrim

func MinPrim[A LesserPrim](val ...A) A

Returns the smallest value from among the inputs, which must be comparable primitives. For non-primitives, see `Min`.

func MinPrim2

func MinPrim2[A LesserPrim](one, two A) A

Returns the lesser of the two inputs, which must be comparable primitives. For non-primitives, see `Min2`.

func MinPrimBy

func MinPrimBy[Src any, Out LesserPrim](src []Src, fun func(Src) Out) Out

Calls the given function for each element of the given slice and returns the smallest value from among the results, which must be comparable primitives. For non-primitives, see `MinBy`.

func NoEscUnsafe

func NoEscUnsafe[A any](val A) A

Dangerous tool for performance fine-tuning.

func None

func None[A any](src []A, fun func(A) bool) bool

Inverse of `Some`.

func Nop

func Nop()

Does nothing.

func Nop1

func Nop1[A any](A)

Does nothing.

func Nop2

func Nop2[A, B any](A, B)

Does nothing.

func Nop3

func Nop3[A, B, C any](A, B, C)

Does nothing.

func NullOr

func NullOr[A Nullable](val ...A) A

Variant of `Or` compatible with `Nullable`. Returns the first non-"null" value from among the inputs.

func Ok

func Ok(fun func())

Must be deferred. Runs the function only if there's no panic. Idempotently adds a stack trace.

func Or

func Or[A any](val ...A) A

Returns the first non-zero value from among the inputs.

func Parse

func Parse[Out any, Src Text](src Src, out *Out)

Decodes arbitrary text into value of specific type, using `ParseCatch`. Panics on errors.

func ParseCatch

func ParseCatch[Out any, Src Text](src Src, out *Out) error

Missing feature of the standard library. Decodes arbitrary text into a value of an arbitrary type. The output must either implement `Parser`, or implement `encoding.TextUnmarshaler`, or be a pointer to any of the types described by the constraint `Textable` defined by this package. If the output is not decodable, this returns an error.

func ParseClearCatch

func ParseClearCatch[Out any, Tar ClearerPtrGetter[Out], Src Text](src Src, tar Tar) error

Shortcut for implementing text decoding of types that wrap other types, such as `Opt`. Mostly for internal use.

func ParseTo

func ParseTo[Out any, Src Text](src Src) (out Out)

Decodes arbitrary text into value of specific type, using `Parse`.

func ParseValueCatch

func ParseValueCatch[A Text](src A, out r.Value) error

Reflection-based component of `ParseCatch`. Mostly for internal use.

func Plus

func Plus[A Plusable](val ...A) A

Combines all inputs via "+". If the input is empty, returns the zero value.

func Plus2

func Plus2[A Plusable](one, two A) A

Combines two inputs via "+". Also see variadic `Add`.

func Procure

func Procure[Src, Out any](src []Src, fun func(Src) Out) Out

Similar to `Find`, but instead of returning the first approved element, returns the first non-zero result of the given function. If nothing is procured, returns a zero value.

func Procured

func Procured[Src, Out any](src []Src, fun func(Src) (Out, bool)) (Out, bool)

Similar to `Found`, but instead of returning an element, returns the first product of the given function for which the returned boolean is true. If nothing is procured, returns zero value and false.

func Ptr

func Ptr[A any](val A) *A

Takes an arbitrary value and returns a non-nil pointer to it.

func PtrInit

func PtrInit[A any](val **A) *A

If the outer pointer is nil, returns nil. If the inner pointer is nil, uses `new` to allocate a new value, sets and returns the resulting new pointer. Otherwise returns the inner pointer as-is.

func PtrInited

func PtrInited[A any](val *A) *A

If the pointer is nil, uses `new` to allocate a new value of the given type, returning the resulting pointer. Otherwise returns the input as-is.

func PtrNoEscUnsafe

func PtrNoEscUnsafe[A any](val *A) u.Pointer

Dangerous tool for performance fine-tuning. Converts the given pointer to `unsafe.Pointer` and tricks the compiler, preventing escape analysis of the resulting pointer from moving the underlying memory to the heap. Can negate failures of Go escape analysis, but can also introduce tricky bugs. The caller MUST ensure that the original is not freed while the resulting pointer is still in use.

func PtrSet

func PtrSet[A any](tar *A, val A)

If the pointer is nil, does nothing. If non-nil, set the given value.

func Range

func Range[A Int](min, max A) []A

Returns a slice of numbers from "min" to "max". The range is inclusive at the start but exclusive at the end: "[min,max)".

func ReadAll

func ReadAll(src io.Reader) []byte

Same as `io.ReadAll` but with different error handling. If reader is nil, returns nil. Panics on errors.

func ReadCloseAll

func ReadCloseAll(src io.ReadCloser) []byte

Variant of `ReadAll` that closes the provided reader when done. If reader is nil, returns nil. Panics on errors.

func ReadFile

func ReadFile[A Text](path string) A

Shortcut for `os.ReadFile`. Panics on error. Converts the content to the requested text type without an additional allocation.

func Rec

func Rec(out *error)

Must be deferred. Recovers from panics, writing the resulting error, if any, to the given pointer. Should be used together with "try"-style functions. Idempotently adds a stack trace.

func RecN

func RecN(out *error, skip int)

Must be deferred. Same as `Rec`, but skips the given amount of stack frames when capturing a trace.

func RecOnly

func RecOnly(ptr *error, test func(error) bool)

Must be deferred. Filtered version of `Rec`. Recovers from panics that satisfy the provided test. Re-panics on non-nil errors that don't satisfy the test. Does NOT check errors that are returned normally, without a panic. Idempotently adds a stack trace.

func RecWith

func RecWith(fun func(error))

Must be deferred. Recovery for background goroutines which are not allowed to crash. Calls the provided function ONLY if the error is non-nil.

func Reject

func Reject[Slice ~[]Elem, Elem any](src Slice, fun func(Elem) bool) Slice

Inverse of `Filter`. Returns only the elements for which the given function returned `false`.

func RelOpt

func RelOpt(base, src string) string

"Optional" variant of `filepath.Rel`. If the given path can't be made relative, it's returned as-is.

func Reverse

func Reverse[A any](val []A)

Reverses the given slice in-place, mutating it.

func Reversed

func Reversed[Slice ~[]Elem, Elem any](val Slice) Slice

Reverses the given slice in-place, mutating it and returning that slice.

func RuntimeFunc

func RuntimeFunc(val any) *rt.Func

Takes an arbitrary function and returns its `runtime.Func`.

func ScanCatch

func ScanCatch[Inner any, Outer PtrGetter[Inner]](src any, tar Outer) error

Shortcut for implementing `sql.Scanner` on types that wrap other types, such as `Opt`. Mostly for internal use.

func Skip

func Skip()

Must be deferred. Catches and ignores ALL panics.

func SkipOnly

func SkipOnly(test func(error) bool)

Must be deferred. Catches panics; ignores errors that satisfy the provided test; re-panics on other non-nil errors. Idempotently adds a stack trace.

func Skipping

func Skipping(fun func())

Runs a function, catching and ignoring ALL panics.

func SkippingOnly

func SkippingOnly(test func(error) bool, fun func())

Runs a function, catching and ignoring only the panics that satisfy the provided test. Idempotently adds a stack trace.

func SliceDat

func SliceDat[A any](src []A) *A

Returns the underlying data pointer of the given slice.

func SliceOf

func SliceOf[A any](val ...A) []A

Like `[]typ{...}` but with parens.

func SliceTrunc

func SliceTrunc[Slice ~[]Elem, Elem any](tar *Slice)

Collapses the slice's length, preserving the capacity. Does not modify any elements.

func SliceZero

func SliceZero[A any](val []A)

Zeroes each element of the given slice.

func Some

func Some[A any](src []A, fun func(A) bool) bool

True if the given function returns true for any element of the given slice. False if the function is nil. False if the slice is empty.

func SomePair

func SomePair[A any](one, two []A, fun func(A, A) bool) bool

Utility for comparing slices pairwise. Returns true if the slices have the same length and the function returns true for at least one pair.

func Sort

func Sort[A Lesser[A]](val []A)

Sorts a slice of comparable primitives. For primitives, see `SortPrim`.

func SortPrim

func SortPrim[A LesserPrim](val []A)

Sorts a slice of comparable primitives. For non-primitives, see `Sort`.

func Sorted

func Sorted[Slice ~[]Elem, Elem Lesser[Elem]](val Slice) Slice

Sorts a slice of comparable values, mutating and returning that slice. For primitives, see `SortedPrim`.

func SortedPrim

func SortedPrim[Slice ~[]Elem, Elem LesserPrim](val Slice) Slice

Sorts a slice of comparable primitives, mutating and returning that slice. For non-primitives, see `Sort`.

func Spaced

func Spaced(val ...string) string

Joins the given strings with a space.

func SpacedOpt

func SpacedOpt[A Text](val ...A) string

Joins non-empty strings with a space.

func Span

func Span[A Int](val A) []A

Shortcut for creating a range from 0 to N.

func StrDat

func StrDat[A Text](src A) *byte

Returns the underlying data pointer of the given string or byte slice. Mutations may trigger segfaults or cause undefined behavior.

func StrHead

func StrHead[A Text](val A) byte

Returns the first byte or 0.

func StrLast

func StrLast[A Text](val A) byte

Returns the last byte or 0.

func StrLen

func StrLen[A Text](val A) int

Same as `len`. Limited to `Text` types but can be passed to higher-order functions.

func StrPop

func StrPop[A, B ~string](ptr *A, sep B) A

Searches for the given separator and returns the part of the string before the separator, removing that prefix from the original string referenced by the pointer. The separator is excluded from both chunks. As a special case, if the separator is empty, pops the entire given string.

func String

func String[A any](val A) string

Stringifies an arbitrary value via `StringCatch`. Panics on errors.

func StringAny

func StringAny[A any](val A) string

Alias for `fmt.Sprint` defined as a generic function for compatibility with higher-order functions like `Map`. Slightly more efficient than `fmt.Sprint`: avoids spurious heap escape and copying.

The output of this function is intended only for debug purposes. For machine consumption or user display, use `String`, which is more restrictive.

func StringCatch

func StringCatch[A any](val A) (string, error)

Missing feature of the standard library. Converts an arbitrary value to a string, allowing only INTENTIONALLY stringable values. Rules:

  • Nil is considered "".

  • A string is returned as-is.

  • A byte slice is cast to a string.

  • Any other primitive value (see constraint `Prim`) is encoded via `strconv`.

  • Types that support `fmt.Stringer`, `Appender` or `encoding.TextMarshaler` are encoded by using the corresponding method.

  • Any other type causes an error.

func StringNull

func StringNull[A any, B NullableValGetter[A]](val B) string

Shortcut for implementing string encoding of `Nullable` types. Mostly for internal use.

func Subtract

func Subtract[Slice ~[]Elem, Elem comparable](base Slice, sub ...Slice) Slice

Returns a version of the given slice excluding any additionally supplied values.

func Sum

func Sum[Src any, Out Plusable](src []Src, fun func(Src) Out) Out

Calls the given function on each element of the given slice and returns the sum of all results, combined via "+".

func TagIdent

func TagIdent(val string) string

Takes a struct field tag and returns its identifier part, following the "encoding/json" conventions. Ident "-" is converted to "". Usage:

ident := TagIdent(someField.Tag.Get(`json`))
ident := TagIdent(someField.Tag.Get(`db`))

Rules:

json:"ident"         -> "ident"
json:"ident,<extra>" -> "ident"
json:"-"             -> ""
json:"-,<extra>"     -> ""

func Tail

func Tail[Slice ~[]Elem, Elem any](val Slice) Slice

Returns the tail part of the given slice: all except the first value. If the slice is nil, returns nil.

func Take

func Take[Slice ~[]Elem, Elem any](src Slice, size int) Slice

Returns a subslice containing N elements from the start.

func TakeWhile

func TakeWhile[Slice ~[]Elem, Elem any](src Slice, fun func(Elem) bool) Slice

Returns a subslice containing only elements at the start of the slice for which the given function contiguously returned `true`.

func Times

func Times[A any](src int, fun func(int) A) []A

Somewhat similar to `Map`. Creates a slice by "mapping" source values to outputs. Calls the given function N times, passing an index, starting with 0.

func ToBytes

func ToBytes[A Text](val A) []byte

Allocation-free conversion. Reinterprets an arbitrary string-like or bytes-like value as bytes.

func ToErrAny

func ToErrAny(val any) error

Idempotently converts the input to an error. If the input is nil, the output is nil. If the input implements `error`, it's returned as-is. If the input does not implement `error`, it's converted to `ErrStr` or wrapped with `ErrAny`.

func ToErrTraced

func ToErrTraced(val any, skip int) error

Converts an arbitrary value to an error. Idempotently adds a stack trace. If the input is a non-nil non-error, it's wrapped into `ErrAny`.

func ToString

func ToString[A Text](val A) string

Allocation-free conversion. Reinterprets an arbitrary string-like or bytes-like value as a regular string.

func Traced

func Traced()

Must be deferred. Tool for adding a stack trace to an arbitrary panic. Unlike the "rec" functions, this does NOT prevent the panic from propagating. It simply ensures that there's a stack trace, then re-panics.

Caution: due to idiosyncrasies of `recover()`, this works ONLY when deferred directly. Anything other than `defer gg.Traced()` will NOT work.

func Trans

func Trans(fun func(error) error)

Must be deferred. Short for "transmute" or "transform". Catches an ongoing panic, transforms the error by calling the provided function, and then re-panics via `Try`. Idempotently adds a stack trace.

func Transing

func Transing(trans func(error) error, fun func())

Runs a function, "transmuting" or "transforming" the resulting panic by calling the provided transformer. See `Trans`.

func Try

func Try(err error)

If the error is nil, returns void. If the error is non-nil, idempotently adds a stack trace and panics.

func Try1

func Try1[A any](val A, err error) A

If the error is nil, returns the given value. If the error is non-nil, idempotently adds a stack trace and panics.

func Try2

func Try2[A, B any](one A, two B, err error) (A, B)

If the error is nil, returns the given values. If the error is non-nil, idempotently adds a stack trace and panics.

func Try3

func Try3[A, B, C any](one A, two B, three C, err error) (A, B, C)

If the error is nil, returns the given values. If the error is non-nil, idempotently adds a stack trace and panics.

func Type

func Type[A any]() r.Type

Returns `reflect.Type` of the given type. Differences from `reflect.TypeOf`:

  • Avoids spurious heap escape and copying.

  • Output is always non-nil.

  • When the given type is an interface, including the empty interface `any`, the output is a non-nil `reflect.Type` describing the given interface.

func TypeDeref

func TypeDeref(val r.Type) r.Type

Returns the element type of the provided type, automatically dereferencing pointer types. If the input is nil, returns nil.

func TypeKind

func TypeKind(val r.Type) r.Kind

Nil-safe version of `reflect.Type.Kind`. If the input is nil, returns `reflect.Invalid`.

func TypeOf

func TypeOf[A any](A) r.Type

Similar to `reflect.TypeOf`, with the following differences:

  • Avoids spurious heap escape and copying.

  • Output is always non-nil.

  • When the given type is an interface, including the empty interface `any`, the output is a non-nil `reflect.Type` describing the given interface.

func ValidPk

func ValidPk[
	Key comparable,
	Val Pked[Key],
](val Val) Key

Short for "valid primary key". Returns the primary key generated by the given input, asserts that the key is non-zero, and returns the resulting key. Used internally by `Coll`.

func ValueAppendCatch

func ValueAppendCatch[A ~[]byte](buf A, val r.Value) (A, error)

Reflection-based component of `AppendCatch`. Mostly for internal use.

func ValueDeref

func ValueDeref(val r.Value) r.Value

Dereferences the provided value until it's no longer a pointer. If the input is a nil pointer or a pointer to a nil pointer (recursively), returns an empty/invalid value.

func ValueNull

func ValueNull[A any, B NullableValGetter[A]](src B) (driver.Value, error)

Shortcut for implementing `driver.Valuer` on `Nullable` types that wrap other types, such as `Opt`. Mostly for internal use.

func ValueStringCatch

func ValueStringCatch(val r.Value) (string, error)

Reflection-based component of `StringCatch`. Mostly for internal use.

func ValueToString

func ValueToString(val r.Value) (string, bool)

Reflection-based component of `AnyToString`. For internal use.

func ValueToStringCatch

func ValueToStringCatch(val r.Value) (string, error)

Same as `ValueToString` but instead of boolean true/false, returns a nil/non-nil error. The error describes the failure to convert the input to a string.

func ValueToText

func ValueToText[A Text](val r.Value) (A, bool)

Reflection-based component of `AnyToText`. For internal use.

func Wrapf

func Wrapf(err error, pat string, val ...any) error

Wraps the given error, prepending the given message and idempotently adding a stack trace.

func Zero

func Zero[A any]() (val A)

Returns a zero value of the given type.

func ZeroValue

func ZeroValue[A any]() r.Value

Uses `reflect.Zero` to create a zero value of the given type.

Types

type Appender

type Appender interface{ Append([]byte) []byte }

Appends a text representation to the given buffer, returning the modified buffer. Counterpart to `fmt.Stringer`. All types that implement this interface should also implement `fmt.Stringer`, and in most cases this should be semantically equivalent to appending the output of `.String`. However, this interface allows significantly more efficient text encoding.

type Buf

type Buf []byte

Short for "buffer". Simpler, cleaner, more usable alternative to `strings.Builder` and `bytes.Buffer`.

func (Buf) Append

func (self Buf) Append(val []byte) []byte

Implement `Appender`. Appends its own content to the given buffer. If the given buffer has no capacity, returns itself.

func (*Buf) AppendAny

func (self *Buf) AppendAny(val any) *Buf

Appends the text representation of the input, using the `Append` function. Mutates and returns the receiver.

func (*Buf) AppendBool

func (self *Buf) AppendBool(val bool) *Buf

Appends text representation of the input, using "strconv". Mutates and returns the receiver.

func (*Buf) AppendByte

func (self *Buf) AppendByte(val byte) *Buf

Appends the given byte. Mutates and returns the receiver.

func (*Buf) AppendByteN

func (self *Buf) AppendByteN(val byte, count int) *Buf

Appends the given byte N times. Mutates and returns the receiver.

func (*Buf) AppendBytes

func (self *Buf) AppendBytes(val []byte) *Buf

Appends the given bytes. Mutates and returns the receiver.

func (*Buf) AppendError

func (self *Buf) AppendError(val error) *Buf

Appends the string representation of the given error. If the input is nil, this is a nop. Mutates and returns the receiver.

func (*Buf) AppendFloat32

func (self *Buf) AppendFloat32(val float32) *Buf

Appends text representation of the input, using "strconv". Mutates and returns the receiver.

func (*Buf) AppendFloat64

func (self *Buf) AppendFloat64(val float64) *Buf

Appends text representation of the input, using "strconv". Mutates and returns the receiver.

func (*Buf) AppendGoString

func (self *Buf) AppendGoString(val any) *Buf

Appends the text representation of the input, using the `AppendGoString` function. Mutates and returns the receiver.

func (*Buf) AppendIndent

func (self *Buf) AppendIndent() *Buf

Appends `Indent`. Mutates and returns the receiver.

func (*Buf) AppendIndents

func (self *Buf) AppendIndents(lvl int) *Buf

Appends `Indent` N times. Mutates and returns the receiver.

func (*Buf) AppendInt

func (self *Buf) AppendInt(val int) *Buf

Appends text representation of the input, using "strconv". Mutates and returns the receiver.

func (*Buf) AppendInt64

func (self *Buf) AppendInt64(val int64) *Buf

Appends text representation of the input, using "strconv". Mutates and returns the receiver.

func (*Buf) AppendNewline

func (self *Buf) AppendNewline() *Buf

Appends `Newline`. Mutates and returns the receiver.

func (*Buf) AppendNewlines

func (self *Buf) AppendNewlines(count int) *Buf

Appends `Newline` N times. Mutates and returns the receiver.

func (*Buf) AppendRune

func (self *Buf) AppendRune(val rune) *Buf

Appends the given rune. Mutates and returns the receiver.

func (*Buf) AppendSpace

func (self *Buf) AppendSpace() *Buf

Appends a single space. Mutates and returns the receiver.

func (*Buf) AppendSpaces

func (self *Buf) AppendSpaces(count int) *Buf

Appends a space N times. Mutates and returns the receiver.

func (*Buf) AppendString

func (self *Buf) AppendString(val string) *Buf

Appends the given string. Mutates and returns the receiver.

func (*Buf) AppendStringN

func (self *Buf) AppendStringN(val string, count int) *Buf

Appends the given string N times. Mutates and returns the receiver.

func (*Buf) Clear

func (self *Buf) Clear() *Buf

Truncates the buffer's length, preserving the capacity. Does not modify the content. Mutates and returns the receiver.

func (*Buf) Fprintf

func (self *Buf) Fprintf(pat string, val ...any) *Buf

Shortcut for appending a formatted string.

func (*Buf) Fprintlnf

func (self *Buf) Fprintlnf(pat string, val ...any) *Buf

Shortcut for appending a formatted string with an idempotent trailing newline.

func (*Buf) GrowCap

func (self *Buf) GrowCap(size int) *Buf

Increases the buffer's capacity sufficiently to accommodate N additional elements. Mutates and returns the receiver.

func (*Buf) GrowLen

func (self *Buf) GrowLen(size int) *Buf

Increases the buffer's length by N zero values. Mutates and returns the receiver.

func (Buf) Len

func (self Buf) Len() int

Same as `len(buf)`.

func (Buf) String

func (self Buf) String() string

Free cast to a string. Mutation of the original buffer affects the resulting string.

func (*Buf) Write

func (self *Buf) Write(val []byte) (int, error)

Implement `io.Writer`, appending the input to the buffer. The error is always nil and may be ignored.

func (*Buf) WriteString

func (self *Buf) WriteString(val string) (int, error)

Implement `io.StringWriter`, appending the input to the buffer. The error is always nil and may be ignored.

type BytesReadCloser

type BytesReadCloser struct{ bytes.Reader }

Variant of `bytes.Reader` that also implements nop `io.Closer`.

func (*BytesReadCloser) Close

func (*BytesReadCloser) Close() error

Implement `io.Closer`. This is a nop. The error is always nil.

func (*BytesReadCloser) Reset

func (self *BytesReadCloser) Reset(src []byte) *BytesReadCloser

Calls `(*bytes.Reader).Reset`.

type Cache

type Cache[
	Key comparable,
	Val any,
	Ptr Initer1[Val, Key],
] struct {
	Lock sync.RWMutex
	Map  map[Key]Ptr
}

func CacheOf

func CacheOf[
	Key comparable,
	Val any,
	Ptr Initer1[Val, Key],
]() *Cache[Key, Val, Ptr]

func (*Cache[Key, _, _]) Del

func (self *Cache[Key, _, _]) Del(key Key)

func (*Cache[Key, Val, Ptr]) Get

func (self *Cache[Key, Val, Ptr]) Get(key Key) Val

func (*Cache[Key, Val, Ptr]) GetPtr

func (self *Cache[Key, Val, Ptr]) GetPtr(key Key) Ptr

type Caller

type Caller uintptr

Represents an entry in a call stack. Used for formatting.

func (Caller) Append

func (self Caller) Append(buf []byte) []byte

func (Caller) AppendIndent

func (self Caller) AppendIndent(buf []byte, lvl int) []byte

func (Caller) AppendNewlineIndent

func (self Caller) AppendNewlineIndent(buf []byte, lvl int) []byte

func (Caller) Frame

func (self Caller) Frame() (out Frame)

Converts to `Frame`, which is used for formatting.

func (Caller) Func

func (self Caller) Func() *rt.Func

Uses `runtime.FuncForPC` to return the function corresponding to this frame.

func (Caller) Pc

func (self Caller) Pc() uintptr

Short for "program counter".

func (Caller) String

func (self Caller) String() string

Returns a single-line representation of the frame that includes function name, file path, and row.

type Clearer

type Clearer interface{ Clear() }

Must clear the receiver. In collection types backed by slices and maps, this should reduce length to 0, but is allowed to keep capacity.

type ClearerPtrGetter

type ClearerPtrGetter[A any] interface {
	Clearer
	PtrGetter[A]
}

Used by some utility functions.

type Coll

type Coll[
	Key comparable,
	Val Pked[Key],
] struct {
	Slice []Val
	Index map[Key]int
}

Short for "collection". Represents an ordered map where keys are automatically derived from values, and must be non-zero.

func (*Coll[Key, Val]) Add

func (self *Coll[Key, Val]) Add(val ...Val) *Coll[Key, Val]

Adds the given elements to both the inner slice and the inner index.

func (*Coll[Key, Val]) Calc

func (self *Coll[Key, Val]) Calc()

Reindexes the collection. Must be invoked after appending elements to the slice through external means. Note that all built-in methods of this type perform indexing automatically.

func (*Coll[Key, Val]) Clear

func (self *Coll[Key, Val]) Clear() *Coll[Key, Val]

Clears the collection, keeping capacity.

func (Coll[Key, Val]) Get

func (self Coll[Key, Val]) Get(key Key) Val

Returns the value indexed on the given key, or the zero value of that type.

func (Coll[Key, Val]) GetPtr

func (self Coll[Key, Val]) GetPtr(key Key) *Val

Find the value indexed on the given key and returns the pointer to its position in the slice. If the value is not found, returns nil.

func (Coll[Key, Val]) Got

func (self Coll[Key, Val]) Got(key Key) (Val, bool)

Returns the value indexed on the given key and a boolean indicating if the value was actually present.

func (Coll[Key, _]) Has

func (self Coll[Key, _]) Has(key Key) bool

True if the index has the given key. Doesn't check if the index is within the bounds of the inner slice.

func (Coll[_, _]) Len

func (self Coll[_, _]) Len() int

func (Coll[_, _]) MarshalJSON

func (self Coll[_, _]) MarshalJSON() ([]byte, error)

Implement `json.Marshaler`. Encodes the inner slice, ignoring the index.

func (*Coll[_, _]) UnmarshalJSON

func (self *Coll[_, _]) UnmarshalJSON(src []byte) error

Unmarshals the input into the inner slice and rebuilds the index.

type Decoder

type Decoder interface {
	Clearer
	Parser
	Scanner
}

Combination of interfaces related to text decoding implemented by some types in this package.

type Encoder

type Encoder interface {
	fmt.Stringer
	Appender
	Nullable
	Getter
	driver.Valuer
}

Combination of interfaces related to text encoding implemented by some types in this package.

type Err

type Err struct {
	Msg   string
	Cause error
	Trace *Trace // Included by pointer to allow `==` for errors.
}

Superior alternative to standard library errors. Supports stack traces and error wrapping. Provides a convenient builder API.

func Errf

func Errf(pat string, val ...any) Err

Creates an error with a stack trace and a message formatted via `fmt.Sprintf`.

func (Err) Append

func (self Err) Append(inout []byte) []byte

Implement `Appender`, appending the same representation as `.Error`.

func (Err) AppendStack

func (self Err) AppendStack(inout []byte) []byte

Appends a text representation of the full error message with the stack trace, if any. The representation is the same as in `.Stack`.

func (Err) Caused

func (self Err) Caused(val error) Err

Returns a modified version with the given `.Cause`.

func (Err) ErrOpt

func (self Err) ErrOpt() error

func (Err) Error

func (self Err) Error() string

Implement `error`.

func (Err) Format

func (self Err) Format(out fmt.State, verb rune)

Implement `fmt.Formatter`.

func (Err) Is

func (self Err) Is(err error) bool

Implement a hidden interface for compatibility with `"errors".Is`.

func (Err) IsTraced

func (self Err) IsTraced() bool

True if either the error or its cause has a non-empty stack trace.

func (Err) Msgd

func (self Err) Msgd(val string) Err

Returns a modified version where `.Msg` is set to the input.

func (Err) Msgf

func (self Err) Msgf(pat string, val ...any) Err

Returns a modified version where `.Msg` is set from `fmt.Sprintf`.

func (Err) Stack

func (self Err) Stack() string

Returns a text representation of the full error message with the stack trace, if any.

func (Err) StackTrace

func (self Err) StackTrace() []uintptr

Implement `StackTraced`, which allows to retrieve stack traces from nested errors.

func (Err) String

func (self Err) String() string

Implement `fmt.Stringer`.

func (Err) Traced

func (self Err) Traced(skip int) Err

Returns a modified version where `.Trace` is initialized idempotently if `.Trace` was nil. Skips the given amount of stack frames when capturing the trace, where 1 corresponds to the caller's frame.

func (Err) TracedOpt

func (self Err) TracedOpt(skip int) Err

Returns a modified version where `.Trace` is initialized idempotently if neither the error nor `.Cause` had a trace. Skips the given amount of stack frames when capturing the trace, where 1 corresponds to the caller's frame.

func (Err) Unwrap

func (self Err) Unwrap() error

Implement a hidden interface for compatibility with `"errors".Unwrap`.

type ErrAny

type ErrAny struct{ Val any }

Implementation of `error` that wraps an arbitrary value. Useful in panic recovery. Used internally by `Rec`.

func (ErrAny) Error

func (self ErrAny) Error() string

Implement `error`.

func (ErrAny) Unwrap

func (self ErrAny) Unwrap() error

Implement a hidden interface in "errors".

type ErrStr

type ErrStr string

String typedef that implements `error`. Errors of this type can be defined as constants.

const (
	ErrInvalidInput ErrStr = `invalid input`
	ErrNyi          ErrStr = `not yet implemented`
)

func (ErrStr) Error

func (self ErrStr) Error() string

Implement `error`.

func (ErrStr) String

func (self ErrStr) String() string

Implement `fmt.Stringer`.

type Errs

type Errs []error

Combines multiple errors. Used by `Conc`. Avoid casting this to `error`. Instead call the method `Errs.ErrOpt`, which will correctly return a nil interface when all errors are nil.

func (Errs) Append

func (self Errs) Append(buf []byte) []byte

Appends a text representation of the error or errors. The text is the same as returned by `.Error`.

func (Errs) As

func (self Errs) As(out any) bool

Implement a hidden interface for compatibility with `"errors".As`.

func (Errs) ErrOpt

func (self Errs) ErrOpt() error

If there are any non-nil errors, returns a non-nil error, unwrapping if possible. Otherwise returns nil.

func (Errs) Error

func (self Errs) Error() string

Implement `error`.

func (Errs) First

func (self Errs) First() error

First non-nil error.

func (Errs) HasLen

func (self Errs) HasLen() bool

True if there are any non-nil errors.

func (Errs) Is

func (self Errs) Is(err error) bool

Implement a hidden interface for compatibility with `"errors".Is`.

func (Errs) LenNil

func (self Errs) LenNil() int

Counts nil errors.

func (Errs) LenNonNil

func (self Errs) LenNonNil() int

Counts non-nil errors.

func (Errs) String

func (self Errs) String() string

Returns an error message. Same as `.Error`.

func (Errs) Try

func (self Errs) Try()

If there are any non-nil errors, panic with a stack trace.

func (Errs) Unwrap

func (self Errs) Unwrap() error

Implement a hidden interface for compatibility with `"errors".Unwrap`.

type Float

type Float interface{ ~float32 | ~float64 }

Describes all built-in float types and their typedefs.

type Frame

type Frame struct {
	Caller Caller
	Func   *rt.Func
	Name   string
	File   string
	Line   int
}

Represents a stack frame. Generated by `Caller`. Used for formatting.

func (Frame) Append

func (self Frame) Append(inout []byte) []byte

Appends a single-line representation of the frame that includes function name, file path, and row.

func (Frame) AppendIndent

func (self Frame) AppendIndent(inout []byte, lvl int) []byte

func (Frame) AppendNewlineIndent

func (self Frame) AppendNewlineIndent(inout []byte, lvl int) []byte

func (Frame) AppendRowIndent

func (self Frame) AppendRowIndent(inout []byte, lvl, wid int) []byte

func (*Frame) Init

func (self *Frame) Init(val Caller)

func (*Frame) IsLang

func (self *Frame) IsLang() bool

True if the frame represents a "language" frame which is mostly not useful for debugging app code.

func (Frame) IsValid

func (self Frame) IsValid() bool

True if the frame has a known associated function.

func (*Frame) NameShort

func (self *Frame) NameShort() string

func (*Frame) Path

func (self *Frame) Path() string

func (*Frame) Pkg

func (self *Frame) Pkg() string

Returns the package name of the given frame.

func (*Frame) Skip

func (self *Frame) Skip() bool

True if the frame should not be displayed, either because it's invalid, or because `TraceSkipLang` is set and the frame represents a "language" frame which is mostly not useful for debugging app code.

func (Frame) String

func (self Frame) String() string

Returns a single-line representation of the frame that includes function name, file path, and row.

type Frames

type Frames []Frame

func (Frames) AppendIndentTable

func (self Frames) AppendIndentTable(buf []byte, lvl int) []byte

func (Frames) NameWidth

func (self Frames) NameWidth() int

type Getter

type Getter interface{ Get() any }

Implemented by various utility types. Enables compatibility with 3rd party libraries such as `pgx`.

type Initer1

type Initer1[A, B any] interface {
	*A
	Init(B)
}

Used by `Cache`.

type Int

type Int interface{ Sint | Uint }

Describes all built-in integer types and their typedefs.

type Lesser

type Lesser[A any] interface{ Less(A) bool }

Describes arbitrary types that support comparison via `.Less`, similar to "<". Used by various sorting/ordering utilities.

type LesserPrim

type LesserPrim interface {
	Num | Float | ~uintptr | ~string
}

Describes all primitive types that support the "<" operator. Counterpart to `Lesser` which describes types that support comparison via the `.Less` method.

type Maybe

type Maybe[A any] struct {
	Val A     `json:"val,omitempty"`
	Err error `json:"err,omitempty"`
}

Contains a value or an error.

func MaybeErr

func MaybeErr[A any](err error) Maybe[A]

Shortcut for creating a `Maybe` with the given error.

func MaybeVal

func MaybeVal[A any](val A) Maybe[A]

Shortcut for creating a `Maybe` with the given value.

func (Maybe[_]) GetErr

func (self Maybe[_]) GetErr() error

Returns the underlying error as-is.

func (Maybe[A]) GetVal

func (self Maybe[A]) GetVal() A

Implement `ValGetter`, returning the underlying value as-is.

func (Maybe[_]) HasErr

func (self Maybe[_]) HasErr() bool

True if error is non-nil.

func (Maybe[A]) MarshalJSON

func (self Maybe[A]) MarshalJSON() ([]byte, error)

Implement `json.Marshaler`. If the underlying error is non-nil, returns that error. Otherwise uses `json.Marshal` to encode the underlying value.

func (Maybe[A]) Ok

func (self Maybe[A]) Ok() A

Asserts that the error is nil, returning the resulting value. If the error is non-nil, panics via `Try`, idempotently adding a stack trace to the error.

func (*Maybe[A]) SetErr

func (self *Maybe[A]) SetErr(err error)

Sets the error. If the error is non-nil, clears the value.

func (*Maybe[A]) SetVal

func (self *Maybe[A]) SetVal(val A)

Implement `ValSetter`. Sets the underlying value and clears the error.

func (*Maybe[A]) UnmarshalJSON

func (self *Maybe[A]) UnmarshalJSON(src []byte) error

Implement `json.Unmarshaler`, decoding into the underlying value.

type Nullable

type Nullable interface{ IsNull() bool }

Implemented by various utility types where zero value is considered null in encoding/decoding contexts such as JSON and SQL.

type NullableValGetter

type NullableValGetter[A any] interface {
	Nullable
	ValGetter[A]
}

Used by some utility functions.

type Num

type Num interface{ Int | Float }

Describes all built-in numeric types and their typedefs, excluding complex numbers.

type Opt

type Opt[A any] struct {
	Val A
	Ok  bool
}

Short for "optional". Wraps an arbitrary type. When `.Ok` is false, the value is considered empty/null in various contexts such as text encoding, JSON encoding, SQL encoding, even if the value is not "zero".

func OptFrom

func OptFrom[A any](val A, ok bool) Opt[A]

Shortcut for creating an optional from a given value and boolean indicating validity. If the boolean is false, the output is considered "null" even if the value is not "zero".

func OptMap

func OptMap[A, B any](src Opt[A], fun func(A) B) (out Opt[B])

FP-style "mapping". If the original value is considered "null", or if the function is nil, the output is "zero" and "null". Otherwise the output is the result of calling the function with the previous value, and is considered non-"null" even if the value is zero.

func OptVal

func OptVal[A any](val A) Opt[A]

Short for "optional value". Instantiates an optional with the given val. The result is considered non-null.

func (Opt[A]) Append

func (self Opt[A]) Append(buf []byte) []byte

Implement `Appender`, appending the same representation as `.String`.

func (*Opt[A]) Clear

func (self *Opt[A]) Clear()

Implement `Clearer`. Zeroes the receiver.

func (Opt[A]) Get

func (self Opt[A]) Get() any

Implement `Getter` for compatibility with 3rd party libraries such as `pgx`. If `.IsNull`, returns nil. Otherwise returns the underlying value, invoking its own `Getter` if possible.

func (*Opt[A]) GetPtr

func (self *Opt[A]) GetPtr() *A

Implement `PtrGetter`, returning a pointer to the underlying value.

func (Opt[A]) GetVal

func (self Opt[A]) GetVal() A

Implement `ValGetter`, returning the underlying value as-is.

func (Opt[A]) IsNonNull

func (self Opt[A]) IsNonNull() bool

Inverse of `.IsNull`.

func (Opt[A]) IsNull

func (self Opt[A]) IsNull() bool

Implement `Nullable`. True if not `.Ok`.

func (Opt[A]) MarshalJSON

func (self Opt[A]) MarshalJSON() ([]byte, error)

Implement `json.Marshaler`. If `.IsNull`, returns a representation of JSON null. Otherwise uses `json.Marshal` to encode the underlying value.

func (Opt[A]) MarshalText

func (self Opt[A]) MarshalText() ([]byte, error)

Implement `encoding.TextMarshaler`, returning the same representation as `.String`.

func (*Opt[A]) Parse

func (self *Opt[A]) Parse(src string) error

Implement `Parser`. If the input is empty, clears the receiver via `.Clear`. Otherwise uses the `ParseCatch` function, decoding into the underlying value.

func (*Opt[A]) Scan

func (self *Opt[A]) Scan(src any) error

Implement SQL `Scanner`, decoding an arbitrary input into the underlying value. If the underlying type implements `Scanner`, its own implementation is used. Otherwise input must be nil or text-like (see `Text`). Text decoding uses the same logic as `.Parse`.

func (*Opt[A]) SetVal

func (self *Opt[A]) SetVal(val A)

Implement `ValSetter`. Modifies the underlying value and sets `.Ok = true`. The result is considered non-null even if the value is "zero".

func (Opt[A]) String

func (self Opt[A]) String() string

Implement `fmt.Stringer`. If `.IsNull`, returns an empty string. Otherwise uses the `String` function to encode the inner value.

func (*Opt[A]) UnmarshalJSON

func (self *Opt[A]) UnmarshalJSON(src []byte) error

Implement `json.Unmarshaler`. If the input is empty or represents JSON null, clears the receiver via `.Clear`. Otherwise uses `json.Unmarshaler` to decode into the underlying value.

func (*Opt[A]) UnmarshalText

func (self *Opt[A]) UnmarshalText(src []byte) error

Implement `encoding.TextUnmarshaler`, using the same logic as `.Parse`.

func (Opt[A]) Value

func (self Opt[A]) Value() (driver.Value, error)

Implement SQL `driver.Valuer`. If `.IsNull`, returns nil. If the underlying value implements `driver.Valuer`, delegates to its method. Otherwise returns the underlying value, invoking its own `Getter` if possible.

type Parser

type Parser interface{ Parse(string) error }

Interface for types that support parsing from a string. Counterpart to `encoding.TextUnmarshaler`. Implemented by some utility types.

type Pked

type Pked[A comparable] interface{ Pk() A }

Short for "primary keyed". See type `Coll` which acts as an ordered map where each value is indexed on its primary key. Keys must be non-zero. A zero value is considered an invalid key.

type Plusable

type Plusable interface{ Num | ~string }

Describes all types that support the "+" operator.

type Prim

type Prim interface{ ~bool | ~string | Num }

Set of "primitive" types which may be constant.

type PtrGetter

type PtrGetter[A any] interface{ GetPtr() *A }

Implemented by utility types that wrap arbitrary types, such as `Opt`. The returned pointer must reference the memory of the wrapper, instead of referring to new memory. Its mutation must affect the wrapper.

type Runner

type Runner interface{ Run() }

Used by some utilities.

type Scanner

type Scanner interface{ Scan(any) error }

Copy of `sql.Scanner`. Copied here to avoid a huge import.

type Set

type Set[A comparable] map[A]struct{}

Generic unordered set backed by a map.

func SetFrom

func SetFrom[Slice ~[]Elem, Elem comparable](val ...Slice) Set[Elem]

Syntactic shortcut for making a set from multiple slices, with element type inference and capacity preallocation.

func SetMapped

func SetMapped[
	Slice ~[]Elem,
	Elem any,
	Val comparable,
](src Slice, fun func(Elem) Val) Set[Val]

Creates a set by "mapping" the elements of a given slice via the provided function.

func SetOf

func SetOf[A comparable](val ...A) Set[A]

Syntactic shortcut for making a set from a slice, with element type inference and capacity preallocation.

func (Set[A]) Add

func (self Set[A]) Add(val ...A) Set[A]

func (Set[A]) AddFrom

func (self Set[A]) AddFrom(val ...Set[A]) Set[A]

func (Set[A]) Clear

func (self Set[A]) Clear() Set[A]

func (Set[A]) Del

func (self Set[A]) Del(val ...A) Set[A]

func (Set[A]) DelFrom

func (self Set[A]) DelFrom(val ...Set[A]) Set[A]

func (Set[A]) GoString

func (self Set[A]) GoString() string

Implement `fmt.GoStringer`, returning valid Go code that constructs the set.

func (Set[A]) Has

func (self Set[A]) Has(val A) bool

func (*Set[A]) Init

func (self *Set[A]) Init() Set[A]

Idempotently inits the map via `make`, making it writable. The output pointer must be non-nil.

func (Set[A]) MarshalJSON

func (self Set[A]) MarshalJSON() ([]byte, error)

JSON-encodes as a list. Order is random.

func (Set[A]) Reset

func (self Set[A]) Reset(val ...A) Set[A]

func (Set[A]) Slice

func (self Set[A]) Slice() []A

Converts the map to a slice of its values. The order is random.

func (*Set[A]) UnmarshalJSON

func (self *Set[A]) UnmarshalJSON(src []byte) error

JSON-decodes the input, which must either represent JSON "null" or a JSON list of values compatible with the value type.

type Signed

type Signed interface{ Sint | Float }

Describes all built-in signed numeric types and their typedefs, excluding complex numbers.

type Sint

type Sint interface {
	~int8 | ~int16 | ~int32 | ~int64 | ~int
}

Short for "signed integer".

type SliceHeader

type SliceHeader struct {
	Dat u.Pointer
	Len int
	Cap int
}

Memory representation of an arbitrary Go slice.

type Sortable

type Sortable[A Lesser[A]] []A

Implements `sort.Interface`.

func (Sortable[_]) Len

func (self Sortable[_]) Len() int

func (Sortable[_]) Less

func (self Sortable[_]) Less(one, two int) bool

func (Sortable[_]) Sort

func (self Sortable[_]) Sort()

func (Sortable[A]) Sorted

func (self Sortable[A]) Sorted() Sortable[A]

func (Sortable[_]) Swap

func (self Sortable[_]) Swap(one, two int)

type SortablePrim

type SortablePrim[A LesserPrim] []A

Implements `sort.Interface`.

func (SortablePrim[_]) Len

func (self SortablePrim[_]) Len() int

func (SortablePrim[_]) Less

func (self SortablePrim[_]) Less(one, two int) bool

func (SortablePrim[_]) Sort

func (self SortablePrim[_]) Sort()

func (SortablePrim[A]) Sorted

func (self SortablePrim[A]) Sorted() SortablePrim[A]

func (SortablePrim[_]) Swap

func (self SortablePrim[_]) Swap(one, two int)

type StackTraced

type StackTraced interface{ StackTrace() []uintptr }

Implemented by the `Err` type. Used by `ErrTrace` to retrieve stack traces from arbitrary error types.

type StringReadCloser

type StringReadCloser struct{ strings.Reader }

Variant of `strings.Reader` that also implements nop `io.Closer`.

func NewReadCloser

func NewReadCloser[A Text](val A) *StringReadCloser

Creates a read-closer able to read from the given string or byte slice. Equivalent to `io.NopCloser(strings.NewReader(string(val)))` but marginally more efficient.

func (*StringReadCloser) Close

func (*StringReadCloser) Close() error

Implement `io.Closer`. This is a nop. The error is always nil.

func (*StringReadCloser) Reset

func (self *StringReadCloser) Reset(src string) *StringReadCloser

Calls `(*strings.Reader).Reset`.

type StructFields

type StructFields []r.StructField

func (*StructFields) Init

func (self *StructFields) Init(src r.Type)

type Text

type Text interface{ ~string | ~[]byte }

Describes text types: strings and byte slices.

type Textable

type Textable interface{ Prim | ~[]byte }

Describes built-in or well-known types which don't implement text encoding and decoding intrinsically, but whose text encoding and decoding is supported across the Go library ecosystem extrinsically.

type Trace

type Trace []Caller

Alias of `[]uintptr` with various methods for capturing and printing stack traces.

func AnyTrace

func AnyTrace(val any, skip int) Trace

If the input implements `error`, tries to find its stack trace via `ErrTrace`. If no trace is found, generates a new trace, skipping the given amount of frames. Suitable for use on `any` values returned by `recover`.

func CaptureTrace

func CaptureTrace(skip int) Trace

Shortcut for capturing a trace of the the current call stack, skipping N frames where 1 corresponds to the caller's frame.

func ErrTrace

func ErrTrace(val error) Trace

Returns the stack trace of the given error, unwrapping it as much as necessary.

func ToTrace

func ToTrace(val []uintptr) Trace

Free cast of the given ptr slice to `Trace`.

func (Trace) Append

func (self Trace) Append(buf []byte) []byte

Appends a multi-line text representation of the trace, with no leading indentation. See `.AppendIndent`.

func (Trace) AppendIndent

func (self Trace) AppendIndent(buf []byte, lvl int) []byte

Appends a multi-line text representation of the trace, with the given leading indentation. Used internally by other trace printing methods. Affected by the various "Trace*" variables. If `TraceTable` is true, the trace is formatted as a table, where each frame takes only one line, and names are aligned. Otherwise, the trace is formatted similarly to the default representation used by the Go runtime.

func (Trace) AppendIndentMulti

func (self Trace) AppendIndentMulti(buf []byte, lvl int) []byte

Appends a representation of the trace similar to the default used by the Go runtime. Used internally by `.AppendIndent` if `TraceTable` is false.

func (Trace) AppendIndentTable

func (self Trace) AppendIndentTable(buf []byte, lvl int) []byte

Appends a table-style representation of the trace. Used internally by `.AppendIndent` if `TraceTable` is true.

func (Trace) Capture

func (self Trace) Capture(skip int) Trace

Uses `runtime.Callers` to capture the current call stack into the given `Trace`, which must have enough capacity. The returned slice is truncated.

func (Trace) Frames

func (self Trace) Frames() Frames

Converts to `Frames`, which is used for formatting.

func (Trace) HasLen

func (self Trace) HasLen() bool

True if there are any non-empty frames.

func (Trace) Prim

func (self Trace) Prim() []uintptr

Free cast to the underlying type. Useful for `runtime.Callers` and for implementing `StackTraced` in error types.

func (Trace) String

func (self Trace) String() string

Returns a multi-line text representation of the trace, with no leading indentation. See `.AppendIndent`.

func (Trace) StringIndent

func (self Trace) StringIndent(lvl int) string

Returns a multi-line text representation of the trace with the given leading indentation. See `.AppendIndent`.

func (Trace) Table

func (self Trace) Table() string

Returns a table-style representation of the trace with no leading indentation.

func (Trace) TableIndent

func (self Trace) TableIndent(lvl int) string

Returns a table-style representation of the trace with the given leading indentation.

type TypeCache

type TypeCache[Val any, Ptr Initer1[Val, r.Type]] struct {
	Lock sync.RWMutex
	Map  map[r.Type]Ptr
}

func TypeCacheOf

func TypeCacheOf[Val any, Ptr Initer1[Val, r.Type]]() *TypeCache[Val, Ptr]

func (*TypeCache[Val, Ptr]) Get

func (self *TypeCache[Val, Ptr]) Get(key r.Type) Val

func (*TypeCache[Val, Ptr]) GetPtr

func (self *TypeCache[Val, Ptr]) GetPtr(key r.Type) Ptr

type Uint

type Uint interface {
	~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uint
}

Short for "unsigned integer".

type ValGetter

type ValGetter[A any] interface{ GetVal() A }

Implemented by utility types that wrap arbitrary types, such as `Opt`.

type ValSetter

type ValSetter[A any] interface{ SetVal(A) }

Implemented by utility types that wrap arbitrary types, such as `Opt`.

type Words

type Words []string

Tool for converting between typographic cases such as `camelCase` and `snake_case`.

func ToWords

func ToWords[A Text](val A) Words

Splits arbitrary text into words, Unicode-aware. Suitable for conversion between typographic cases such as `camelCase` and `snake_case`.

func (Words) Camel

func (self Words) Camel() Words

func (Words) Comma

func (self Words) Comma() string

func (Words) Join

func (self Words) Join(val string) string

Same as `strings.Join`.

func (Words) Kebab

func (self Words) Kebab() string

func (Words) Lower

func (self Words) Lower() Words

func (Words) MapHead

func (self Words) MapHead(fun func(string) string) Words

Mutates the receiver by replacing the first element with the result of calling the given function on that element. If the receiver is empty, this is a nop.

func (Words) MapMut

func (self Words) MapMut(fun func(string) string) Words

Mutates the receiver by replacing each element with the result of calling the given function on that element.

func (Words) Sentence

func (self Words) Sentence() Words

func (Words) Snake

func (self Words) Snake() string

func (Words) Solid

func (self Words) Solid() string

func (Words) Spaced

func (self Words) Spaced() string

func (Words) Title

func (self Words) Title() Words

func (Words) Upper

func (self Words) Upper() Words

type Zop

type Zop[A any] struct {
	/**
	The `role:"ref"` annotation, where "ref" is short for "reference", indicates
	that this field is a reference/pointer to the inner type/value.
	Reflection-based code may use this to treat `Zop` like a pointer.
	*/
	Val A `role:"ref"`
}

Short for "zero optional". The zero value is considered empty/null in JSON. Note that "encoding/json" doesn't support ",omitempty" for struct values. This wrapper allows empty structs to become "null". This type doesn't implement any other encoding or decoding methods, and is intended only for non-scalar values such as "models" / "data classes".

func ZopMap

func ZopMap[A, B any](src Zop[A], fun func(A) B) (out Zop[B])

FP-style "mapping". If the original value is zero, or if the function is nil, the output is zero. Otherwise the output is the result of calling the function with the previous value.

func ZopVal

func ZopVal[A any](val A) Zop[A]

Short for "zero optional value". Workaround for the lack of type inference in type literals.

func (*Zop[A]) Clear

func (self *Zop[A]) Clear()

Implement `Clearer`. Zeroes the receiver.

func (Zop[A]) Get

func (self Zop[A]) Get() any

Implement `Getter` for compatibility with 3rd party libraries such as `pgx`. If `.IsNull`, returns nil. Otherwise returns the underlying value, invoking its own `Getter` if possible.

func (*Zop[A]) GetPtr

func (self *Zop[A]) GetPtr() *A

Implement `PtrGetter`, returning a pointer to the underlying value.

func (Zop[A]) GetVal

func (self Zop[A]) GetVal() A

Implement `ValGetter`, returning the underlying value as-is.

func (Zop[A]) IsNonNull

func (self Zop[A]) IsNonNull() bool

Inverse of `.IsNull`.

func (Zop[A]) IsNull

func (self Zop[A]) IsNull() bool

Implement `Nullable`. True if zero value of its type.

func (Zop[A]) MarshalJSON

func (self Zop[A]) MarshalJSON() ([]byte, error)

Implement `json.Marshaler`. If `.IsNull`, returns a representation of JSON null. Otherwise uses `json.Marshal` to encode the underlying value.

func (*Zop[A]) SetVal

func (self *Zop[A]) SetVal(val A)

Implement `ValSetter`, modifying the underlying value.

func (*Zop[A]) UnmarshalJSON

func (self *Zop[A]) UnmarshalJSON(src []byte) error

Implement `json.Unmarshaler`. If the input is empty or represents JSON null, clears the receiver via `.Clear`. Otherwise uses `json.Unmarshaler` to decode into the underlying value.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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