gg

package module
v0.1.22 Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2024 License: Unlicense Imports: 27 Imported by: 2

README

Overview

Essential utilities missing from the Go standard library.

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

Some features:

  • Designed for Go 1.18. Takes massive advantage of generics.
  • Errors with stack traces.
  • Checked math.
  • 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.
  • CLI flag parsing.
  • 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.

Submodules:

  • gtest: testing and assertion tools.
  • grepr: tools for printing Go data structures as Go code.
  • gsql: SQL tools:
    • Support for scanning SQL rows into Go structs.
    • Support for SQL arrays.

Current limitations:

  • Not fully documented.

License

https://unlicense.org

Documentation

Index

Examples

Constants

View Source
const (
	// Standard terminal escape sequence. Same as "\x1b" or "\033".
	TermEsc = string(rune(27))

	// Control Sequence Introducer. Used for other codes.
	TermEscCsi = TermEsc + `[`

	// Update cursor position to first row, first column.
	TermEscCup = TermEscCsi + `1;1H`

	// Supposed to clear the screen without clearing the scrollback, aka soft
	// clear. Seems insufficient on its own, at least in some terminals.
	TermEscErase2 = TermEscCsi + `2J`

	// Supposed to clear the screen and the scrollback, aka hard clear. Seems
	// insufficient on its own, at least in some terminals.
	TermEscErase3 = TermEscCsi + `3J`

	// Supposed to reset the terminal to initial state, aka super hard clear.
	// Seems insufficient on its own, at least in some terminals.
	TermEscReset = TermEsc + `c`

	// Clear screen without clearing scrollback.
	TermEscClearSoft = TermEscCup + TermEscErase2

	// Clear screen AND scrollback.
	TermEscClearHard = TermEscCup + TermEscReset + TermEscErase3
)

https://en.wikipedia.org/wiki/ANSI_escape_code

View Source
const SizeofSlice = u.Sizeof([]byte(nil))

Amount of bytes in any slice header, for example of type `[]byte`. Note that the size of a slice header is constant and does not reflect the size of the underlying data.

View Source
const SizeofSliceHeader = u.Sizeof(SliceHeader{})

Amount of bytes in our own `SliceHeader`. In the official Go implementation (version 1.20 at the time of writing), this is equal to `SizeofSlice`. In case of mismatch, using `SliceHeader` for anything is invalid.

View Source
const SizeofString = u.Sizeof(``)

Amount of bytes in any value of type `~string`. Note that this is the size of the string header, not of the underlying data.

View Source
const SizeofWord = u.Sizeof(uintptr(0))

Amount of bytes in `uintptr`. At the time of writing, in Go 1.20, this is also the amount of bytes in `int` and `uint`.

Variables

View Source
var (
	Indent  = `    `
	Space   = ` `
	Newline = "\n"
)
View Source
var (
	TraceTable     = true
	TraceSkipLang  = true
	TraceShortName = false
	TraceBaseDir   = `` // Set to `Cwd()` for better traces.
)

These variables control how stack traces are printed.

View Source
var DbNameToJsonFieldCache = TypeCacheOf[DbNameToJsonField]()
View Source
var DbNameToJsonNameCache = TypeCacheOf[DbNameToJsonName]()
View Source
var FlagDefCache = TypeCacheOf[FlagDef]()

Stores cached `FlagDef` definitions for struct types.

View Source
var FlagFmtDefault = With((*FlagFmt).Default)

Default help formatter, used by `FlagHelp` and `FlagDef.Help`.

View Source
var JsonNameToDbFieldCache = TypeCacheOf[JsonNameToDbField]()
View Source
var JsonNameToDbNameCache = TypeCacheOf[JsonNameToDbName]()
View Source
var ReWord = NewLazy(func() *regexp.Regexp {
	return regexp.MustCompile(`\p{Lu}+[\p{Ll}\d]*|[\p{Ll}\d]+`)
})

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

View Source
var StructDeepPublicFieldCache = TypeCacheOf[StructDeepPublicFields]()

For any given struct type, returns a slice of its fields including fields of embedded structs. Structs embedded by value (not by pointer) are considered parts of the enclosing struct, rather than fields in their own right, and their fields are included into this function's output. This is NOT equivalent to the fields you would get by iterating over `reflect.Type.NumField`. Not only because it includes the fields of value-embedded structs, but also because it adjusts `reflect.StructField.Index` and `reflect.StructField.Offset` specifically for the given ancestor type. In particular, `reflect.StructField.Offset` of deeply-nested fields is exactly equivalent to the output of `unsafe.Offsetof` for the same parent type and field, which is NOT what you would normally get from the "reflect" package.

For comparison. Normally when using `reflect.Type.FieldByIndex`, the returned fields have both their offset and their index relative to their most immediate parent, rather than the given ancestor. But it's also inconsistent. When using `reflect.Type.FieldByName`, the returned fields have their index relative to the ancestor, but their offset is still relative to their most immediate parent.

This implementation fixes ALL of that. It gives you fields where offsets AND indexes are all relative to the ancestor.

Caches and reuses the resulting slice for all future calls for any given type. The resulting slice, its elements, or any inner slices, must not be mutated.

View Source
var StructFieldCache = TypeCacheOf[StructFields]()
View Source
var StructPublicFieldCache = TypeCacheOf[StructPublicFields]()

Functions

func Add added in v0.1.7

func Add[A Int](one, two A) A

Checked addition. Panics on overflow/underflow. Has overhead.

func AddUncheck added in v0.1.15

func AddUncheck[A Num](one, two A) A

Unchecked addition. Same as Go's `+` operator for numbers, expressed as a generic function. Does not take strings. May overflow. For integers, prefer `Add` whenever possible, which has overflow checks.

func Adjoin added in v0.0.5

func Adjoin[Slice ~[]Elem, Elem comparable](tar Slice, src ...Elem) Slice

Returns a version of the given slice with the given values appended unless they were already present in the slice. This function only appends; it doesn't deduplicate any previously existing values in the slice, nor reorder them.

func AnyAs added in v0.0.14

func AnyAs[A any](src any) A

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

func AnyErr added in v0.1.0

func AnyErr(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`. Does NOT generate a stack trace or modify an underlying `error` in any way. See `AnyErrTraced` for that.

func AnyErrTraced added in v0.0.6

func AnyErrTraced(val any) error

Same as `AnyErrTracedAt(val, 1)`.

func AnyErrTracedAt added in v0.1.0

func AnyErrTracedAt(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 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 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` byt the output type is backed by `[]byte`, or vice versa, this performs a regular Go conversion, which may allocate. Otherwise this doesn't allocate.

func Append

func Append[Slice ~[]Elem, Elem any](ptr *Slice, val ...Elem)

Appends the given elements to the given slice. Similar to built-in `append` but syntactically shorter.

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 AppendIndex added in v0.1.1

func AppendIndex[Slice ~[]Elem, Elem any](ptr *Slice, val Elem) int

If the target pointer is nil, does nothing and returns -1. Otherwise appends the given element to the given slice (like `Append`) and returns the last index of the resulting slice. Also see `AppendPtr`.

func AppendNewlineOpt added in v0.1.4

func AppendNewlineOpt[A Text](val A) A

If the given text is non-empty and does not end with a newline character, appends `Newline` and returns the result. Otherwise returns the text unchanged. If the input type is a typedef of `[]byte` and has enough capacity, it's mutated. In other cases, the text is reallocated. Also see `Buf.AppendNewlineOpt` and `Strln`.

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](ptr *Slice, val Elem) *Elem

Appends the given element to the given slice, returning the pointer to the newly appended position in the slice. If the target pointer is nil, does nothing and returns nil. Also see `AppendIndex`.

func AppendPtrZero

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

Appends a zero element to the given slice, returning the pointer to the newly appended position in the slice. If the target pointer is nil, does nothing and returns nil.

func AppendReflectCatch added in v0.0.13

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

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

func AppendTo

func AppendTo[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 AppenderString

func AppenderString[A AppenderTo](val A) string

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

func AsBytes added in v0.1.7

func AsBytes[A any](tar *A) []byte

Reinterprets existing memory as a byte slice. The resulting byte slice is backed by the given pointer. Mutations of the resulting slice are reflected in the source memory. Length and capacity are equal to the size of the referenced memory. If the pointer is nil, the output is nil.

func Cap

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

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

func CapMissing added in v0.0.4

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

Amount of missing capacity that needs to be allocated to append the given amount of additional elements.

func CapUnused added in v0.0.4

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

Amount of unused capacity in the given slice.

func Cast added in v0.1.8

func Cast[Out, Src any](src Src) Out

Same as `CastUnsafe` but with additional validation: `unsafe.Sizeof` must be the same for both types, otherwise this panics.

func CastSlice added in v0.1.8

func CastSlice[Out, Src any](src []Src) []Out

Similar to `CastUnsafe` between two slice types but with additional validation: `unsafe.Sizeof` must be the same for both element types, otherwise this panics.

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. Compare `Catch10` and `Catch11`.

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. Compare `Catch01` and `Catch11`.

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. Compare `Catch10` and `Catch01`.

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 ChanInit added in v0.0.12

func ChanInit[Tar ~chan Val, Val any](ptr *Tar) Tar

Idempotently initializes the channel. If the pointer is non-nil and the channel is nil, creates a new unbuffered channel and assigns it to the pointer. Returns the resulting channel.

func ChanInitCap added in v0.0.12

func ChanInitCap[Tar ~chan Val, Val any](ptr *Tar, cap int) Tar

Idempotently initializes the channel. If the pointer is non-nil and the channel is nil, creates a new buffered channel with the given capacity and assigns it to the pointer. Returns the resulting channel.

func CharCount added in v0.0.13

func CharCount[A Text](val A) int

Uses `utf8.RuneCountInString` to count chars in arbitrary text.

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 CloneDeep added in v0.0.5

func CloneDeep[A any](val A) A

Returns a deep clone of the given value. Doesn't clone chans and funcs, preserving them as-is. If the given value is "direct" (see `IsIndirect`), this function doesn't allocate and simply returns the input as-is.

func Close

func Close(val io.Closer)

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

func Compact

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

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

func Compacted added in v0.1.18

func Compacted[A any](src ...A) []A

Same as `Compact` but variadic.

func Conc

func Conc(val ...func())

Shortcut for concurrent execution. Runs the given functions via `ConcCatch`. If there is at least one error, panics with the combined error, adding a stack trace pointing to the call site of `Conc`.

func ConcCatch

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

Concurrently runs the given functions. Catches their panics, converts them to `error`, and returns the resulting errors. The error slice always has the same length as the number of given functions.

Ensures that the resulting errors have stack traces, both on the current goroutine, and on any sub-goroutines used for concurrent execution, wrapping errors as necessary.

The error slice can be converted to `error` via `ErrMul` or `Errs.Err`. The slice is returned as `[]error` rather than `Errs` to avoid accidental incorrect conversion of empty `Errs` to non-nil `error`.

func ConcEach

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

Concurrently calls the given function on each element of the given slice. If the function is nil, does nothing. Also see `Conc`.

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. If the function is nil, does nothing and returns nil. Also see `ConcCatch`

Ensures that the resulting errors have stack traces, both on the current goroutine, and on any sub-goroutines used for concurrent execution, wrapping errors as necessary.

The error slice can be converted to `error` via `ErrMul` or `Errs.Err`. The slice is returned as `[]error` rather than `Errs` to avoid accidental incorrect conversion of empty `Errs` to non-nil `error`.

func ConcMap

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

Like `Map` but concurrent. Also see `Conc`.

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. Also see `ConcCatch`.

Ensures that the resulting errors have stack traces, both on the current goroutine, and on any sub-goroutines used for concurrent execution, wrapping errors as necessary.

The error slice can be converted to `error` via `ErrMul` or `Errs.Err`. The slice is returned as `[]error` rather than `Errs` to avoid accidental incorrect conversion of empty `Errs` to non-nil `error`.

func ConcMapFunc

func ConcMapFunc[A, B any](tar *[]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 every input is nil, 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 Counts added in v0.1.16

func Counts[Slice ~[]Val, Key comparable, Val any](src Slice, fun func(Val) Key) map[Key]int

Counts occurrences elements of the given slice, keyed by calling the given function for each element, and returning the resulting map. If the function is nil, returns nil. Compare `Group` which returns `map[Key][]Val` rather than `map[Key]int`, and `Index` which returns `map[Key]Val`.

func CountsInto added in v0.1.16

func CountsInto[Key comparable, Val any](tar map[Key]int, src []Val, fun func(Val) Key)

Counts occurrences elements of the given slice, keyed by calling the given function for each element, modifying the given map, which must be non-nil if the slice is non-empty. If the function is nil, does nothing.

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 Int](val A) A

Same as `Sub(val, 1)`. Panics on underflow.

func Detail added in v0.1.2

func Detail(msg ...any)

Must be deferred. Wraps non-nil panics, prepending the error message and idempotently adding a stack trace. The message is converted to a string via `Str(msg...)`. Usage:

defer gg.Detail(`unable to do X`)
defer gg.Detail(`unable to do A with B `, someEntity.Id)

func DetailOnlyf

func DetailOnlyf(test func(error) bool, pat string, arg ...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, arg ...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`)

The first argument must be a hardcoded pattern string compatible with `fmt.Sprintf` and other similar functions. If the first argument is an expression rather than a hardcoded string, use `Detail` instead.

func DirExists added in v0.1.1

func DirExists(path string) bool

Shortcut for using `os.Stat` to check if there is an existing directory at the given path.

func Drop

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

Returns a subslice excluding N elements from the start.

func DropLastWhile added in v0.1.20

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

Returns a subslice excluding the elements at the end of the slice for which the given function had contiguously returned `true`. If the function is nil, it's considered to always return `false`, thus the source slice is returned as-is. Elements are tested from the end of the slice in reverse order, but the returned subslice has the original element order. Also see `DropWhile`.

func DropWhile

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

Returns a subslice excluding the elements at the start of the slice for which the given function had contiguously returned `true`. If the function is nil, it's considered to always return `false`, thus the source slice is returned as-is. Also see `DropLastWhile`.

func Each

func Each[Slice ~[]Elem, Elem any](val Slice, fun func(Elem))

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[Slice ~[]Elem, Elem any](val Slice, fun func(*Elem))

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 EqNotZero added in v0.1.6

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

True if the inputs are equal via `==`, and neither is a zero value of its type. For non-equality, use `NotEqNotZero`.

func EqType added in v0.1.11

func EqType[A, B any]() bool

True if both type parameters are exactly the same.

func Equal

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

Short for "equal". For types that implement `Equaler`, this simply calls their equality method. Otherwise falls back on `reflect.DeepEqual`. Compared to `reflect.DeepEqual`, this has better type safety, and in many cases this has better performance, even when calling `reflect.DeepEqual` in fallback mode.

func ErrAs added in v0.0.10

func ErrAs[
	Tar any,
	Ptr interface {
		*Tar
		error
	},
](src error) Tar

Similar to `errors.As`. Differences:

  • Instead of taking a pointer and returning a boolean, this returns the unwrapped error value. On success, output is non-zero. On failure, output is zero.
  • Automatically tries non-pointer and pointer versions of the given type. The caller should always specify a non-pointer type. This provides nil-safety for types that implement `error` on the pointer type. The caller doesn't have to remember whether to use pointer or non-pointer.

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 ErrEq added in v0.1.3

func ErrEq(err0, err1 error) bool

Safely compares two error values, avoiding panics due to `==` on incomparable underlying types. Returns true if both errors are nil, or if the underlying types are comparable and the errors are `==`, or if the errors are identical via `Is`.

func ErrFind added in v0.0.10

func ErrFind(err error, fun func(error) bool) error

Somewhat analogous to `errors.Is` and `errors.As`, but instead of comparing an error to another error value or checking its type, uses a predicate function. Uses `errors.Unwrap` to traverse the error chain and returns the outermost error that satisfies the predicate, or nil.

func ErrMul added in v0.1.0

func ErrMul(src ...error) error

Shortcut for combining multiple errors via `Errs.Err`. Does NOT generate a stack trace or modify the errors in any way.

func ErrOk added in v0.0.2

func ErrOk[A Errer](val A)

Shortcut for flushing errors out of error containers such as `context.Context` or `sql.Rows`. If the inner error is non-nil, panics, idempotently adding a stack trace. Otherwise does nothing.

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 ErrSome added in v0.0.10

func ErrSome(err error, fun func(error) bool) bool

Shortcut that returns true if `ErrFind` is non-nil for the given error and predicate function.

func ErrStack added in v0.1.0

func ErrStack(err error) string

Returns a string that includes both the message and the representation of the trace of the given error, if possible. If the error is nil, the output is zero. Does not capture a new trace. Also see `ErrTrace` which returns the `Trace` of the given error, if possible. The name of this function is consistent with the method `Err.Stack`.

func ErrString

func ErrString(val error) string

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

func ErrTraced

func ErrTraced(err error) error

Same as `ErrTracedAt(val, 1)`.

func ErrTracedAt added in v0.1.0

func ErrTracedAt(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 ExcludeFrom added in v0.1.7

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

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

func Fac added in v0.0.10

func Fac[A Uint](src A) A

Checked factorial. Panics on overflow. Compare `FacUncheck` which runs faster, but may overflow.

func FacUncheck added in v0.1.7

func FacUncheck[A Uint](src A) A

Unchecked factorial. May overflow. Counterpart to `Fac` which panics on overflow.

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 Fatal added in v0.1.3

func Fatal()

Must be deferred in your `main` function. If there is a panic, this prints a stack trace and kills the process with exit code 1. This is very similar to the default Go behavior, the only difference being how the resulting panic trace is formatted. This prevents Go from printing the default, very informative but difficult to read panic trace, replacing it with a less informative but much easier to read trace. See our types `Err` and `Trace`. Usage example:

func main() {
	defer gg.Fatal()
	// Perform actions that may panic.
}

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 FileExists added in v0.1.0

func FileExists(path string) bool

Shortcut for using `os.Stat` to check if the file at the given path exists, and is not a directory.

func Filter

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

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

func FilterAppend added in v0.0.4

func FilterAppend[Tar ~[]Elem, Elem any](ptr *Tar, src []Elem, fun func(Elem) bool)

Similar to `Filter` but instead of creating a new slice, appends to an existing slice.

func FilterIndex added in v0.0.5

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

Takes a slice and returns the indexes whose elements satisfy the given function. All indexes are within the bounds of the original slice.

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[Slice ~[]Elem, Elem any](src Slice, fun func(Elem) bool) Elem

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

func FindIndex

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

Returns the index of the first element for which the given function returns `true`. If none match, returns `-1`. Also see `FindLastIndex`.

func FindLast added in v0.1.20

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

Returns the last element for which the given function returns true. If nothing is found, returns a zero value. Also see `Find`.

func FindLastIndex added in v0.1.20

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

Returns the index of the last element for which the given function returns `true`. If none match, returns `-1`. Also see `FindIndex`.

func FlagHelp added in v0.0.13

func FlagHelp[A any]() string

Returns a help string for the given struct type, using `FlagFmtDefault`.

func FlagParse added in v0.0.13

func FlagParse[A any](src []string, out *A)

Parses CLI flags into the given value, which must be a struct. Panics on error. For parsing rules, see `FlagParser`.

func FlagParseCatch added in v0.0.13

func FlagParseCatch[A any](src []string, out *A) (err error)

Parses CLI flags into the given value, which must be a struct. For parsing rules, see `FlagParser`.

func FlagParseReflect added in v0.0.13

func FlagParseReflect(src []string, out r.Value)

Parses CLI flags into the given output, which must be a settable struct value. For parsing rules, see `FlagParser`.

func FlagParseTo added in v0.0.13

func FlagParseTo[A any](src []string) (out A)

Parses CLI flags into an instance of the given type, which must be a struct. For parsing rules, see `FlagParser`.

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

Short for "fold zero". Similar to `Fold` but the accumulator automatically starts as the zero value of its type.

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 ForkReader added in v0.0.10

func ForkReader(src io.Reader) (_, _ io.Reader)

Fully reads the given stream via `io.ReadAll` and returns two "forks". If reading fails, panics. If the input is nil, both outputs are nil.

func Found

func Found[Slice ~[]Elem, Elem any](src Slice, fun func(Elem) bool) (Elem, 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. Also see `FoundLast`.

func FoundLast added in v0.1.20

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

Returns the last 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. Also see `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 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 GetStrict added in v0.1.22

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

Same as `slice[index]`, expressed as a function. Panics if the index is out of bounds. Sometimes useful with higher-order functions. Also see `Get` which returns zero value instead of panicking when the index is out of bounds.

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 Group added in v0.0.8

func Group[Slice ~[]Val, Key comparable, Val any](src Slice, fun func(Val) Key) map[Key][]Val

Groups the elements of the given slice by using keys generated by the given function, returning the resulting map. If the function is nil, returns nil. Compare `Index` which returns `map[Key]Val` rather than `map[Key][]Val`.

func GroupInto added in v0.0.8

func GroupInto[Key comparable, Val any](tar map[Key][]Val, src []Val, fun func(Val) Key)

Groups the elements of the given slice by adding its elements to slices in the given map, keyed by calling the given function for each element. If the function is nil, does nothing.

func GrowCap

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

Missing feature of the language / standard library. Ensures at least this much unused capacity (not total capacity). If there is already enough capacity, returns the slice as-is. Otherwise allocates a new slice, doubling the capacity as many times as needed until it accommodates enough elements. Use this when further growth is expected. When further growth is not expected, use `GrowCapExact` instead. Similar to `(*bytes.Buffer).Grow` but works for all slice types and avoids any wrapping, unwrapping, or spurious escapes to the heap.

func GrowCapExact added in v0.0.4

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

Missing feature of the language / standard library. Ensures at least this much unused capacity (not total capacity). If there is already enough capacity, returns the slice as-is. Otherwise allocates a new slice with EXACTLY enough additional capacity. Use this when further growth is not expected. When further growth is expected, use `GrowCap` instead.

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 sets and maps. Inverse of `NotHas`.

func HasEqual added in v0.1.0

func HasEqual[A any](src []A, val A) bool

Variant of `Has` that uses `Equal` rather than `==` to compare elements. 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 sets and maps.

func HasEvery added in v0.0.5

func HasEvery[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.

func HasNewlineSuffix

func HasNewlineSuffix[A Text](src 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.

func HasSome added in v0.0.5

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

True if the first slice has some elements from the second slice. In other words, true if the sets A and B intersect.

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

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

func HeadPtr

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

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 Int](val A) A

Same as `Add(val, 1)`. Panics on overflow.

func Index added in v0.0.2

func Index[Slice ~[]Val, Key comparable, Val any](src Slice, fun func(Val) Key) map[Key]Val

Takes a slice and "indexes" it by using keys generated by the given function, returning the resulting map. If the function is nil, returns nil. Compare `Group` which returns `map[Key][]Val` rather than `map[Key]Val`.

func IndexInto added in v0.0.5

func IndexInto[Key comparable, Val any](tar map[Key]Val, src []Val, fun func(Val) Key)

"Indexes" the given slice by adding its values to the given map, keyed by calling the given function for each value. If the function is nil, does nothing.

func IndexPair added in v0.0.5

func IndexPair[
	Slice ~[]Elem,
	Elem any,
	Key comparable,
	Val any,
](
	src Slice, fun func(Elem) (Key, Val),
) map[Key]Val

Takes a slice and "indexes" it by converting each element to a key-value pair, returning the resulting map. If the function is nil or the source slice is empty, returns nil.

func IndexPairInto added in v0.0.5

func IndexPairInto[Elem any, Key comparable, Val any](
	tar map[Key]Val,
	src []Elem,
	fun func(Elem) (Key, Val),
)

Takes a slice and "indexes" it by adding key-value pairs to the given map, making key-value pairs by calling the given function for each element. If the function is nil or the source slice is empty, does nothing.

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 Is added in v0.1.0

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

True if the inputs are byte-for-byte identical. This function is not meant for common use. Nearly always, you should use `Eq` or `Equal` instead. This one is sometimes useful for testing purposes, such as asserting that two interface values refer to the same underlying data. This may lead to brittle code that is not portable between different Go implementations. Performance is similar to `==` for small value sizes (up to 2-4 machine words) but is significantly worse for large value sizes.

func IsDivisibleBy added in v0.1.0

func IsDivisibleBy[A Int](dividend, divisor A) bool

True if the remainder of dividing the first argument by the second argument is zero. If the divisor is zero, does not attempt the division and returns false. Note that the result is unaffected by the signs of either the dividend or the divisor.

func IsEmpty

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

True if len <= 0. Inverse of `.IsNotEmpty`.

func IsErrNil

func IsErrNil(val error) bool

Self-explanatory.

func IsErrNotNil added in v0.1.6

func IsErrNotNil(val error) bool

Self-explanatory.

func IsErrTraced

func IsErrTraced(val error) bool

True if the error has a stack trace. Shortcut for `ErrTrace(val).IsNotEmpty()`.

func IsFieldEmbed added in v0.0.7

func IsFieldEmbed(val r.StructField) bool

True if the given field represents an embedded non-pointer struct type. False if not embedded or embedded by pointer.

func IsFieldIndirect added in v0.0.5

func IsFieldIndirect(val r.StructField) bool

Shortcut for testing if the field's type is `IsIndirect`.

func IsFieldPublic added in v0.0.2

func IsFieldPublic(val r.StructField) bool

Self-explanatory. For some reason this is not provided in usable form by the "reflect" package.

func IsFin added in v0.0.2

func IsFin[A Float](val A) bool

Short for "is finite". Missing feature of the standard "math" package. True if the input is neither NaN nor infinity.

func IsIndirect added in v0.0.5

func IsIndirect(typ r.Type) bool

True if the given type may contain any indirections (pointers). For any "direct" type, assigning a value to another variable via `A := B` makes a complete copy. For any "indirect" type, reassignment is insufficient to make a copy.

Special exceptions:

  • Strings are considered to be direct, despite containing a pointer. Generally in Go, strings are considered to be immutable.
  • Chans are ignored / considered to be direct.
  • Funcs are ignored / considered to be direct.
  • For structs, only public fields are checked.

func IsJsonEmpty added in v0.0.14

func IsJsonEmpty[A Text](val A) bool

True if the input is "null" or blank. Ignores whitespace.

func IsKindNilable added in v0.1.7

func IsKindNilable(val r.Kind) bool

True if the given `reflect.Kind` describes a kind whose value can be nil. On any `reflect.Value` matching this, it's safe to call `.IsNil`.

func IsNat added in v0.1.0

func IsNat[A Num](val A) bool

Short for "is natural". True if >= 0. Also see `IsPos`.

func IsNeg

func IsNeg[A Num](val A) bool

Short for "is negative". True if < 0. Also see `IsNat`.

func IsNotEmpty added in v0.1.6

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

True if len > 0. Inverse of `.IsEmpty`.

func IsNotNull added in v0.1.6

func IsNotNull[A Nullable](val A) bool

Inverse of `IsNull`.

func IsNotZero added in v0.1.6

func IsNotZero[A any](val A) bool

Inverse of `IsZero`.

func IsNull

func IsNull[A Nullable](val A) bool

Generic variant of `Nullable.IsNull`.

func IsPos

func IsPos[A Num](val A) bool

Short for "is positive". True if > 0. Also see `IsNat`.

func IsSorted added in v0.1.15

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

Tool for comparing slice elements pairwise. Iterates left-to-right, invoking the given function for each element pair. If the function is nil, returns false. If there are 0 or 1 elements, returns true. If every comparison returned true, returns true. Otherwise returns false.

func IsTextEmpty added in v0.1.6

func IsTextEmpty[A Text](val A) bool

True if len <= 0. Inverse of `IsTextNotEmpty`.

func IsTextNotEmpty added in v0.1.6

func IsTextNotEmpty[A Text](val A) bool

True if len > 0. Inverse of `IsTextEmpty`.

func IsTrueZero added in v0.1.7

func IsTrueZero[A any](val A) bool

True if every byte in the given value is zero. Not equivalent to `IsZero`. Most of the time, you should prefer `IsZero`, which is more performant and more correct.

func IsTypeBytes

func IsTypeBytes(typ r.Type) bool

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

func IsTypeNilable added in v0.1.7

func IsTypeNilable(val r.Type) bool

Shortcut for `IsTypeNilable(TypeKind(val))`.

func IsValueBytes

func IsValueBytes(val r.Value) bool

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

func IsValueNil added in v0.1.7

func IsValueNil(val r.Value) bool

Safer version of `reflect.Value.IsNil`. Doesn't panic if the value is not nilable.

func IsValueNilable added in v0.1.7

func IsValueNilable(val r.Value) bool

Shortcut for `IsKindNilable(val.Kind())`.

func IsZero

func IsZero[A any](val A) bool

Returns true if the input is the zero value of its type. Optionally falls back on `Zeroable.IsZero` if the input implements this interface. Support for `Zeroable` is useful for types such as `time.Time`, where "zero" is determined only by the timestamp, ignoring the timezone.

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 ind := range Iter(size) { ... }

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

func Join added in v0.0.10

func Join[A Text](src []A, sep string) string

Similar to `strings.Join` but works on any input compatible with the `Text` interface. Also see `JoinOpt`, `JoinAny`, `JoinAnyOpt`.

func JoinAny added in v0.0.19

func JoinAny(src []any, sep string) string

Similar to `strings.Join` but takes `[]any`, converting elements to strings. See `StringCatch` for the encoding rules. Also see `Join`, `JoinOpt`, `JoinAnyOpt`.

func JoinAnyOpt added in v0.0.19

func JoinAnyOpt(src []any, sep string) string

Like `JoinAny` but ignores empty strings.

func JoinDense added in v0.0.19

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

Concatenates the given text without any separators.

func JoinLines

func JoinLines[A Text](val ...A) 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](src []A, sep string) string

Similar to `strings.Join` but works for any input compatible with the `Text` interface and ignores empty strings.

func JoinSpaced added in v0.0.19

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

Joins the given strings with a space.

func JoinSpacedOpt added in v0.0.19

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

Joins non-empty strings with a space.

func JsonBytes

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

Shortcut for `JsonEncode` for `[]byte`.

func JsonBytesCatch

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

Shortcut for `JsonEncodeCatch` for `[]byte`.

func JsonBytesIndent

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

Shortcut for `JsonEncodeIndent` for `[]byte`.

func JsonBytesIndentCatch

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

Shortcut for `JsonEncodeIndentCatch` for `[]byte`.

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 JsonDecode added in v0.1.18

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

Shortcut for parsing arbitrary text into the given output, panicking on errors. If the output pointer is nil, does nothing.

func JsonDecodeCatch added in v0.1.18

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

Parses the given text into the given output. Similar to `json.Unmarshal`, but avoids the overhead of byte-string conversion and spurious escapes. If the output pointer is nil, does nothing.

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 JsonDecodeOpt added in v0.1.18

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

Shortcut for parsing the given text into the given output, ignoring errors. If the output pointer is nil, does nothing.

func JsonDecodeOptTo added in v0.1.18

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

Shortcut for parsing the given text into the given output, ignoring errors. If the output pointer is nil, does nothing.

func JsonDecodeTo added in v0.1.18

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

Shortcut for parsing the given text into a value of the given type, panicking on errors.

func JsonEncode added in v0.1.18

func JsonEncode[Out Text, Src any](src Src) Out

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

func JsonEncodeCatch added in v0.1.18

func JsonEncodeCatch[Out Text, Src any](src Src) (Out, error)

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

func JsonEncodeFile added in v0.0.5

func JsonEncodeFile[A any](path string, src A)

Shortcut for writing the JSON encoding of the given value to a file at the given path. Intermediary directories are created automatically. Any existing file is truncated.

func JsonEncodeIndent added in v0.1.18

func JsonEncodeIndent[Out Text, Src any](src Src) Out

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

func JsonEncodeIndentCatch added in v0.1.18

func JsonEncodeIndentCatch[Out Text, Src any](src Src) (Out, 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 JsonString

func JsonString[A any](src A) string

Shortcut for `JsonEncode` for `string`.

func JsonStringCatch added in v0.1.18

func JsonStringCatch[A any](src A) (string, error)

Shortcut for `JsonEncodeCatch` for `string`.

func JsonStringIndent

func JsonStringIndent[A any](src A) string

Shortcut for `JsonEncodeIndent` for `string`.

func JsonStringIndentCatch added in v0.1.18

func JsonStringIndentCatch[A any](src A) (string, error)

Shortcut for `JsonEncodeIndentCatch` for `string`.

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[Slice ~[]Elem, Elem any](val Slice) Elem

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

func LastIndex added in v0.0.5

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

Returns the index of the last element of the given slice. Same as `len(val)-1`. If slice is empty, returns -1.

func LastPtr

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

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

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 Less added in v0.1.15

func Less[A Lesser[A]](src ...A) bool

Variadic version of `<` for non-primitives that implement `Lesser`. Shortcut for `IsSorted` with `Less2`.

func Less2 added in v0.1.15

func Less2[A Lesser[A]](one, two A) bool

Version of `<` for non-primitives that implement `Lesser`.

func LessEq added in v0.1.15

func LessEq[A Lesser[A]](src ...A) bool

Variadic version of `<=` for non-primitives that implement `Lesser`. Shortcut for `IsSorted` with `LessEq2`.

func LessEq2 added in v0.1.15

func LessEq2[A Lesser[A]](one, two A) bool

Version of `<=` for non-primitives that implement `Lesser`.

func LessEqPrim added in v0.1.15

func LessEqPrim[A LesserPrim](src ...A) bool

Variadic version of Go's `<=` operator. Shortcut for `IsSorted` with `LessEqPrim2`.

func LessEqPrim2 added in v0.1.15

func LessEqPrim2[A LesserPrim](one, two A) bool

Same as Go's `<=` operator, expressed as a generic function.

func LessPrim added in v0.1.15

func LessPrim[A LesserPrim](src ...A) bool

Variadic version of `<` for non-primitives that implement `Lesser`. Shortcut for `IsSorted` with `LessPrim2`.

func LessPrim2 added in v0.1.15

func LessPrim2[A LesserPrim](one, two A) bool

Same as Go's `<` operator, expressed as a generic function.

func Lock added in v0.0.12

func Lock[A sync.Locker](val A) A

Shortcut for mutexes. Usage:

defer Lock(someLock).Unlock()

func LockGet added in v0.0.13

func LockGet[Lock sync.Locker, Val any](lock Lock, ptr *Val) (_ Val)

Shortcut for dereferencing a pointer under a lock. Uses `PtrGet`, returning the zero value of the given type if the pointer is nil.

func LockSet added in v0.0.13

func LockSet[Lock sync.Locker, Val any](lock Lock, ptr *Val, val Val)

Shortcut for writing to a pointer under a lock.

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; this is a tradeoff for guaranteeing that output length is always equal to input length.

func Map2 added in v0.0.4

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

Similar to `Map` but iterates two slices pairwise, passing each element pair to the mapping function. If slice lengths don't match, panics.

func MapAppend added in v0.0.4

func MapAppend[
	Src ~[]SrcVal,
	Tar ~[]TarVal,
	SrcVal any,
	TarVal any,
](ptr *Tar, src Src, fun func(SrcVal) TarVal)

Similar to `Map` but instead of creating a new slice, appends to an existing slice.

func MapClear

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

Deletes all entries, returning the resulting map. Passing nil is safe. Note that this involves iterating the map, which is inefficient in Go. In many cases, it's more efficient to make a new map. Also note that Go 1.21 and higher have an equivalent built-in function `clear`.

func MapClone

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

Copies the given map. If the input is nil, the output is nil. Otherwise the output is a shallow copy.

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)

Same as `delete(tar, key)`, expressed as a generic function.

func MapFlat added in v0.0.14

func MapFlat[Out ~[]B, A, B any](src []A, fun func(A) Out) Out

Similar to `Map` but concats the slices returned by the given function.

func MapFlatUniq added in v0.1.16

func MapFlatUniq[Out ~[]B, A any, B comparable](src []A, fun func(A) Out) Out

Similar to `MapFlat` but excludes duplicates.

func MapGet

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

Same as `tar[key]`, expressed as a generic function.

func MapGot

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

Same as `val, ok := tar[key]`, expressed as a generic function.

func MapHas

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

Same as `_, ok := tar[key]`, expressed as a generic function.

func MapInit

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

Idempotent map initialization. If the target pointer is nil, does nothing and returns nil. If the map at the target pointer is non-nil, does nothing and returns that map. Otherwise allocates the map via `make`, stores it at the target pointer, and returns the resulting non-nil map.

func MapKeys

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

Returns the maps's keys as a slice. Order is random.

func MapMake added in v0.1.1

func MapMake[Map ~map[Key]Val, Key comparable, Val any](ptr *Map) Map

Non-idempotent version of `MapInit`. If the target pointer is nil, does nothing and returns nil. If the target pointer is non-nil, allocates the map via `make`, stores it at the target pointer, and returns the resulting non-nil map.

func MapMut added in v0.0.2

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

Similar to `Map`, but instead of creating a new slice, mutates the old one in place by calling the given function on each element.

func MapPtr added in v0.1.3

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

Similar to `Map`, but calls the given function on each element pointer, rather than on each element. Every pointer is non-nil.

func MapSet

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

Same as `tar[key] = val`, expressed as a generic function.

func MapSetOpt added in v0.0.7

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

Same as `MapSet`, but key and value should be be non-zero. If either is zero, this ignores the inputs and does nothing.

func MapUniq added in v0.1.16

func MapUniq[A any, B comparable](src []A, fun func(A) B) []B

Similar to `Map` but excludes duplicates.

func MapVals

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

Returns the maps's values as a slice. Order is random.

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`. For a variadic variant, see `Max`.

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. Same as built-in `max` (Go 1.21+), expressed as a generic function. 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`. For a variadic variant, see `MaxPrim`.

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`. For a variadic variant, see `Min`.

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. Same as built-in `min` (Go 1.21+), expressed as a generic function. 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`. For a variadic variant, see `MinPrim`.

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 MkdirAll added in v0.0.5

func MkdirAll(path string)

Shortcut for `os.MkdirAll` with `os.ModePerm`. Panics on error.

func Mul added in v0.1.7

func Mul[A Int](one, two A) A

Checked multiplication. Panics on overflow/underflow. Has overhead.

func NewElem added in v0.0.5

func NewElem(typ r.Type) r.Value

Shortcut for `reflect.New(typ).Elem()`.

func NewReadCloser

func NewReadCloser[A Text](val A) io.ReadCloser

Creates a read-closer able to read from the given string or byte slice, where the "close" operation does nothing. Similar to combining stdlib functions, but shorter and avoids allocation in case of bytes-to-string or string-to-bytes conversion:

// Longer and marginally less efficient:
io.NopCloser(bytes.NewReader([]byte(`some_data`)))
io.NopCloser(strings.NewReader(string(`some_data`)))

// Equivalent, shorter, marginally more efficient:
gg.NewReadCloser([]byte(`some_data`))
gg.NewReadCloser(string(`some_data`))

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

True if the given function returns false for every element of the given slice, or if the slice is empty, or if the function is nil. Exact 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 NotEqNotZero added in v0.1.6

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

True if the inputs are non-equal via `!=`, and at least one is not a zero value of its type. For equality, use `EqNotZero`.

func NotEqType added in v0.1.11

func NotEqType[A, B any]() bool

True if both type parameters are not exactly the same.

func NotHas added in v0.1.6

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

True if the given slice does not contain 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 sets and maps. Inverse of `Has`. The awkward name is chosen for symmetry with `gtest.NotHas` where it fits more naturally due to conventions for assertion naming.

func NotZeroIndex added in v0.1.6

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

Takes a slice and returns the indexes whose elements are non-zero. All indexes are within the bounds of the original slice.

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 NumBits added in v0.1.7

func NumBits[A Int](src A) string

Returns a representation of the bits in the given machine number, using the traditional big-endian ordering, starting with the most significant bit, which represents the sign in signed integers. The representation is always padded to the full number of bits: 8 for uint8/int8, 16 for uint16/int16, and so on. For unsigned numbers, this is equivalent to using `fmt.Sprintf` with the `%b` flag and appropriate padding. For signed numbers, this is not equivalent.

func NumConv added in v0.1.7

func NumConv[Out, Src Num](src Src) Out

Checked numeric conversion. Same as `Out(src)` but with additional assertions. Panics in case of overflow, underflow, imprecision such as converting large integers to floats that don't support integers in that range, or anything involving NaN. Performance overhead is minimal.

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 a value of the given 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 given 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 ParseReflectCatch added in v0.0.13

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

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

func ParseTo

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

Decodes arbitrary text into a value of the given type, using `ParseCatch`. Panics on errors.

func PathExists added in v0.1.1

func PathExists(path string) bool

Shortcut for using `os.Stat` to check if there is an existing file or directory at the given path.

func Plus

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

Variadic version of Go's `+` operator. Input type may be numeric or ~string. If the input is empty, returns a zero value. Use caution: this has no overflow checks for numbers. Prefer `Add` for integers.

func Plus2

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

Same as Go's `+` operator, expressed as a generic function. Input type may be numeric or ~string. When the input type is numeric, this is unchecked and may overflow. For integers, prefer `Add` whenever possible, which has overflow checks.

func PopHead added in v0.0.13

func PopHead[Slice ~[]Elem, Elem any](ptr *Slice) Elem

func PopLast added in v0.0.13

func PopLast[Slice ~[]Elem, Elem any](ptr *Slice) Elem

func Pow added in v0.0.2

func Pow[Tar, Pow Num](src Tar, pow Pow) Tar

Raises a number to a power. Same as `math.Pow` and calls it under the hood, but accepts arbitrary numeric types and performs checked conversions via `NumConv`. Panics on overflow or precision loss. Has minor overhead over `math.Pow`. Compare `PowUncheck` which runs faster but may overflow.

func PowUncheck added in v0.1.7

func PowUncheck[Tar, Pow Num](src Tar, pow Pow) Tar

Raises a number to a power. Same as `math.Pow` and calls it under the hood, but accepts arbitrary numeric types. Does not check for overflow or precision loss. Counterpart to `Pow` which panics on overflow.

func Procure

func Procure[Out, Src 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[Out, Src 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 a new memory region containing a shallow copy of that value.

func PtrClear added in v0.1.6

func PtrClear[A any](val *A)

Zeroes the memory referenced by the given pointer. If the pointer is nil, does nothing. Also see the interface `Clearer` and method `.Clear` implemented by various types.

Note the difference from built-in `clear` (Go 1.21+): when receiving a pointer to a map or slice, this sets the target to `nil`, erasing the existing capacity, while built-in `clear` would delete all map elements or zero all slice elements (preserving length).

func PtrCleared added in v0.1.6

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

Calls `PtrClear` and returns the same pointer.

func PtrGet added in v0.0.16

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

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

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 PtrLen added in v0.0.7

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

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

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 into thinking that the memory underlying the pointer should not be moved 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 PtrPop added in v0.0.16

func PtrPop[A any](src *A) (out A)

If the pointer is non-nil, returns its value while zeroing the destination. Otherwise returns zero value.

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 PtrSetOpt added in v0.0.4

func PtrSetOpt[A any](tar, src *A)

Takes two pointers and copies the value from source to target if both pointers are non-nil. If either is nil, does nothing.

func Quote added in v0.1.3

func Quote[A any](val A) string

Shortcut for `strconv.Quote(String(val))`. Encodes an arbitrary value to a string and quotes it.

func RandomElem added in v0.1.7

func RandomElem[A any](reader io.Reader, slice []A) A

Picks a random element from the given slice, using the given entropy source (typically `"crypto/rand".Reader`). Panics if the slice is empty or the reader is nil.

func RandomInt added in v0.1.7

func RandomInt[A Int](src io.Reader) (out A)

Generates a random integer of the given type, using the given entropy source (typically `"crypto/rand".Reader`).

func RandomIntBetween added in v0.1.7

func RandomIntBetween[A Int](src io.Reader, min, max A) A

Generates a random integer in the range `[min,max)`, using the given entropy source (typically `"crypto/rand".Reader`). All numbers must be below `math.MaxInt64`.

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)`. If `!(max > min)`, returns nil. Values must be within the range of the Go type `int`.

func RangeIncl added in v0.1.7

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

Returns a slice of numbers from `min` to `max`. The range is inclusive at the start and at the end: `[min,max]`. If `!(max >= min)`, returns nil. Values must be within the range of the Go type `int`.

While the exclusive range `[min,max)` implemented by `Range` is more traditional, this function allows to create a range that includes the maximum representable value of any given integer type, such as 255 for `uint8`, which cannot be done with `Range`.

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 ReadDir added in v0.1.1

func ReadDir(path string) []fs.DirEntry

Shortcut for `os.ReadDir`. Panics on error.

func ReadDirFileNames added in v0.1.18

func ReadDirFileNames(path string) []string

Shortcut for using `os.ReadDir` to return a list of file names in the given directory. Panics on error.

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 RecErr added in v0.1.0

func RecErr(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. Unlike `Rec` and other similar functions, this function does NOT generate a stack trace or modify the error in any way. Most of the time, you should prefer `Rec` and other similar functions. This function is intended for "internal" library code, for example to avoid the stack trace check when the trace is guaranteed, or to avoid generating the trace when the error is meant to be caught before being returned to the caller.

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 Receive added in v0.1.22

func Receive[Src ~chan Val, Val any](src Src) Val

Same as using `<-` to receive a value from a channel, but with a sanity check: the source channel must be non-nil. If the channel is nil, this panics. Note that unlike `ReceiveOpt`, this will block if the channel is non-nil but has nothing in the buffer.

func Reject

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

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

func RejectAppend added in v0.0.5

func RejectAppend[Tar ~[]Elem, Elem any](ptr *Tar, src []Elem, fun func(Elem) bool)

Similar to `Reject` but instead of creating a new slice, appends to an existing slice.

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 Ptrer[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 Send added in v0.1.22

func Send[Tar ~chan Val, Val any](tar Tar, val Val)

Same as using `<-` to send a value over a channel, but with a sanity check: the target channel must be non-nil. If the channel is nil, this panics. Note that unlike `SendOpt`, this will block if the channel is non-nil but has no buffer space.

func SendOpt added in v0.0.12

func SendOpt[Tar ~chan Val, Val any](tar Tar, val Val)

Shortcut for sending a value over a channel in a non-blocking fashion. If the channel is nil or there's no free buffer space, this does nothing.

func SendZeroOpt added in v0.0.12

func SendZeroOpt[Tar ~chan Val, Val any](tar Tar)

Shortcut for sending a zero value over a channel in a non-blocking fashion.

func Size added in v0.0.2

func Size[A any]() uintptr

Returns `unsafe.Sizeof` for the given type. Equivalent to `reflect.Type.Size` for the same type. Due to Go's limitations, the result is not a constant, thus you should prefer direct use of `unsafe.Sizeof` which returns a constant.

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 SliceIs added in v0.0.2

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

True if the given slice headers are byte-for-byte identical. In other words, true if the given slices have the same data pointer, length, capacity. Does not compare individual elements.

func SliceZero

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

Zeroes each element of the given slice. Note that Go 1.21 and higher have an equivalent built-in function `clear`.

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 non-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(src ...any) string

Converts arguments to strings and joins the results with a single space. See `StringCatch` for encoding rules. Also see `JoinSpaced` for a more limited but more efficient version that doesn't involve `any`.

func SpacedOpt

func SpacedOpt(src ...any) string

Converts arguments to strings and joins the results with a single space, ignoring empty strings. See `StringCatch` for the encoding rules. Also see `JoinSpacedOpt` for a more limited but more efficient version that doesn't involve `any`.

func Span

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

Shortcut for creating range `[0,N)`, exclusive at the end.

func Split added in v0.1.18

func Split[A Text](src, sep A) []A

Similar to `strings.Split` and `bytes.Split`. Differences:

  • Supports all text types.
  • Returns nil for empty input.

func Split2 added in v0.1.6

func Split2[A Text](src A, sep string) (A, A)

Similar to `strings.SplitN` for N = 1. More efficient: returns a tuple instead of allocating a slice. Safer: returns zero values if split doesn't succeed.

func SplitLines added in v0.0.13

func SplitLines[A Text](src A) []A

Splits the given text into lines. The resulting strings do not contain any newline characters. If the input is empty, the output is empty. Avoids information loss: preserves empty lines, allowing the caller to transform and join the lines without losing blanks. The following sequences are considered newlines: "\r\n", "\r", "\n".

func SplitLines2 added in v0.1.6

func SplitLines2[A Text](src A) (A, A, int)

Similar to `SplitLines`, but splits only on the first newline occurrence, returning the first line and the remainder, plus the number of bytes in the elided line separator. The following sequences are considered newlines: "\r\n", "\r", "\n".

func Stat added in v0.0.5

func Stat(path string) fs.FileInfo

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

func Str added in v0.0.10

func Str(src ...any) string

Converts arguments to strings and concatenates the results. See `StringCatch` for the encoding rules. Also see `JoinDense` for a simpler version that doesn't involve `any`.

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`, `AppenderTo` or `encoding.TextMarshaler` are encoded by using the corresponding method.
  • As a special case, `time.Time` is encoded in `time.RFC3339` to make encoding and decoding automatically reversible, and generally for better compatibility with machine parsing. This format is already used by `time.Time.MarshalText`, `time.Time.MarshalJSON`, and the corresponding unmarshaling methods. The different format used by `time.Time.String` tends to be an inconvenience, one we rectify here.
  • 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 StringReflectCatch added in v0.0.13

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

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

func Strln added in v0.1.4

func Strln(src ...any) string

Similar to `Str`. Concatenates string representations of the input values. Additionally, if the output is non-empty and doesn't end with a newline character, appends `Newline` at the end.

func Sub added in v0.1.7

func Sub[A Int](one, two A) A

Checked subtraction. Panics on overflow/underflow. Has overhead.

func SubUncheck added in v0.1.15

func SubUncheck[A Num](one, two A) A

Unchecked subtraction. Same as Go's `-` operator, expressed as a generic function. May overflow. For integers, prefer `Sub` whenever possible, which has overflow checks.

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 Swap added in v0.0.2

func Swap[Slice ~[]Elem, Elem any](tar Slice, one, two int)

Swaps the two elements at the given indexes in the given slice.

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 up to N elements from the start. If there are fewer elements total, returns as many as possible.

func TakeLastWhile added in v0.1.20

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

Returns a subslice containing only the elements at the end of the slice for which the given function had contiguously returned `true`. If the function is nil, it's considered to always return `false`, thus the returned slice is empty. Elements are tested from the end of the slice in reverse order, but the returned subslice has the original element order. Also see `TakeWhile`.

func TakeWhile

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

Returns a subslice containing only the elements at the start of the slice for which the given function had contiguously returned `true`. If the function is nil, it's considered to always return `false`, thus the returned slice is empty. Also see `TakeLastWhile`.

func TermClearHard added in v0.0.12

func TermClearHard()

Prints `TermEscClearHard` to `os.Stdout`, clearing the current TTY completely (both screen and scrollback).

func TermClearSoft added in v0.0.12

func TermClearSoft()

Prints `TermEscClearSoft` to `os.Stdout`, causing the current TTY to clear the screen but not the scrollback, pushing existing content out of view.

func TextCut added in v0.1.6

func TextCut[A Text](src A, start, end int) (_ A)

Similar to `src[start:end]`, but instead of slicing text at byte positions, slices text at character positions. Similar to `string([]rune(src)[start:end])`, but slightly more performant and more permissive.

func TextDat added in v0.1.0

func TextDat[A Text](val A) *byte

Similar to `unsafe.StringData`, but takes arbitrary text as input. Returns the pointer to the first byte of the underlying data array for the given string or byte slice. Use caution. Mutating the underlying data may trigger segfaults or cause undefined behavior.

func TextEllipsis added in v0.1.7

func TextEllipsis[A Text](src A, limit uint) A

Shortcut for `TextTruncWith(src, "…")`. Truncates the given text to the given total count of Unicode characters with an ellipsis.

func TextEq added in v0.1.6

func TextEq[A Text](one, two A) bool

True if the inputs would be `==` if compared as strings. When used on typedefs of `[]byte`, this is the same as `bytes.Equal`.

func TextHeadByte added in v0.1.6

func TextHeadByte[A Text](val A) byte

Returns the first byte or 0.

func TextHeadChar added in v0.1.6

func TextHeadChar[A Text](src A) (char rune, size int)

Like `utf8.DecodeRuneInString`, but faster at the time of writing, and without `utf8.RuneError`. On decoding error, the result is `(0, 0)`.

func TextLastByte added in v0.1.6

func TextLastByte[A Text](val A) byte

Returns the last byte or 0.

func TextLen added in v0.1.6

func TextLen[A Text](val A) int

Same as `len`. Sometimes useful for higher-order functions. Note that this does NOT count Unicode characters. For that, use `CharCount`.

func TextPop added in v0.1.6

func TextPop[Src, Sep Text](ptr *Src, sep Sep) Src

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

func TextTrunc added in v0.1.7

func TextTrunc[A Text](src A, limit uint) (_ A)

Truncates text to the given count of Unicode characters (not bytes). The limit can't exceed `math.MaxInt`. Also see `TextTruncWith` which is more general.

func TextTruncWith added in v0.1.7

func TextTruncWith[A Text](src, suf A, limit uint) A

Truncates the given text to the given total count of Unicode characters (not bytes) with a suffix. If the text is under the limit, it's returned unchanged, otherwise it's truncated and the given suffix is appended. The total count includes the character count of the given suffix string. The limit can't exceed `math.MaxInt`. Also see shortcut `TextEllipsis` which uses this with the ellipsis character '…'.

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 TimesAppend added in v0.0.4

func TimesAppend[Slice ~[]Elem, Elem any](ptr *Slice, src int, fun func(int) Elem)

Similar to `Times` but instead of creating a new slice, appends to an existing slice.

func ToAny added in v0.0.19

func ToAny[A any](val A) any

Converts the argument to `any` and returns it. Sometimes useful in higher-order functions.

func ToBytes

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

Allocation-free conversion. Reinterprets arbitrary text as bytes. If the source was a string, the output must NOT be mutated. Mutating memory that belongs to a string may produce segfaults or undefined behavior.

func ToSlice added in v0.0.5

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

Syntactic shortcut for creating a slice out of the given values. Simply returns the slice of arguments as-is. Sometimes allows shorter code. Note that when calling this function with an existing slice, you get the EXACT same slice back, with no allocation. Also see `SliceOf` which returns `Slice[A]` rather than `[]A`.

func ToString

func ToString[A Text](val A) string

Allocation-free conversion. Reinterprets arbitrary text as a string. If the string is used with an API that relies on string immutability, for example as a map key, the source memory must not be mutated afterwards.

func ToText added in v0.0.21

func ToText[Out, Src Text](src Src) Out

Allocation-free conversion between two types conforming to the `Text` constraint, typically variants of `string` and/or `[]byte`.

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 TracedAt added in v0.1.0

func TracedAt(skip int)

Must be deferred. Version of `Traced` that skips the given number of stack frames when generating a stack trace.

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 TransOnly added in v0.0.7

func TransOnly(test func(error) bool, trans func(error) error)

Must be deferred. Similar to `Trans`, but transforms only non-nil errors that satisfy the given predicate. 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 TrimSpacePrefix added in v0.0.13

func TrimSpacePrefix[A Text](src A) A

Missing/private half of `strings.TrimSpace`. Trims only the prefix.

func TrimSpaceSuffix added in v0.0.13

func TrimSpaceSuffix[A Text](src A) A

Missing/private half of `strings.TrimSpace`. Trims only the suffix.

func Trunc added in v0.1.6

func Trunc[Slice ~[]Elem, Elem any](ptr *Slice)

Collapses the slice's length, preserving the capacity. Does not modify any elements. If the pointer is nil, does nothing.

func TruncLen added in v0.0.19

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

Returns a modified slice where length is reduced to the given size. Negative size is equivalent to zero. If the current length is already shorter, it's unaffected.

func Try

func Try(err error)

If the error is nil, returns void. If the error is non-nil, panics with that error, idempotently adding a stack trace.

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, panics with that error, idempotently adding a stack trace.

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, panics with that error, idempotently adding a stack trace.

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, panics with that error, idempotently adding a stack trace.

func TryAny added in v0.1.3

func TryAny(val any)

Shortcut for use with `recover()`. Useful for writing deferrable functions that deal with panics. If the given recovered value is nil, this does nothing. Otherwise converts it to an error, idempotently generating a stack trace, and panics with the resulting traced error. Usage:

gg.TryAny(recover())

func TryAnyAt added in v0.1.3

func TryAnyAt(val any, skip int)

Shortcut for use with `recover()`. Useful for writing deferrable functions that deal with panics. If the given recovered value is nil, this does nothing. Otherwise converts it to an error, idempotently generating a stack trace, skipping the given number of frames, and panics with the resulting traced error. Usage:

gg.TryAnyAt(recover(), 1)

func TryAt added in v0.1.0

func TryAt(err error, skip int)

If the error is nil, returns void. If the error is non-nil, panics with that error, idempotently adding a stack trace and skipping the given number of stack frames.

func TryErr added in v0.1.0

func TryErr(err error)

If the error is nil, returns void. If the error is non-nil, panics with that exact error. Unlike `Try` and other similar functions, this function does NOT generate a stack trace or modify the error in any way. Most of the time, you should prefer `Try` and other similar functions. This function is intended for "internal" library code, for example to avoid the stack trace check when the trace is guaranteed, or to avoid generating the trace when the error is meant to be caught before being returned to the caller.

func TryMul added in v0.1.0

func TryMul(src ...error)

Like `Try`, but for multiple errors. Uses `Errs.Err` to combine the errors. If the resulting error is nil, returns void. If the resulting error is non-nil, panics with that error, idempotently adding a stack trace.

func TryTrans added in v0.1.18

func TryTrans(fun func(error) error, err error)

If the given function and error is non-nil, transforms the error by calling the given function. Then if the resulting error is non-nil, panics with the that error, idempotently adding a stack trace.

func TryWrap added in v0.1.3

func TryWrap(err error, msg ...any)

If the given error is nil, does nothing. Otherwise wraps the error with `Wrap` and the given message, and panics with the resulting error.

func TryWrapf added in v0.1.3

func TryWrapf(err error, pat string, arg ...any)

If the given error is nil, does nothing. Otherwise wraps the error with `Wrapf` and the given message, and panics with the resulting error.

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, rather than the concrete underlying type.

func TypeDeref

func TypeDeref(val r.Type) r.Type

Dereferences the given type, converting `reflect.Pointer` to its element type as many times as necessary. Returns an underlying non-pointer type.

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 TypeString added in v0.1.16

func TypeString(val r.Type) string

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

func Union added in v0.0.14

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

Combines the given slices, deduplicating their elements and preserving the order of first occurrence for each element. Similar to `Uniq` which takes only one slice.

func Uniq added in v0.0.14

func Uniq[Slice ~[]Elem, Elem comparable](src Slice) Slice

Deduplicates the elements of the given slice, preserving the order of initial occurrence for each element. The output is always either nil or a newly allocated slice with at least one element. Compare `UniqBy` which compares elements by keys obtained by calling the given function. Also compare `Union` which takes any number of slices.

func UniqBy added in v0.1.16

func UniqBy[Slice ~[]Elem, Elem any, Key comparable](src Slice, fun func(Elem) Key) Slice

Deduplicates the elements of the given slice on keys obtained by calling the given function for each element, and preserving the order of initial occurrence for each element. If the function is nil, returns nil. The output is always either nil or a newly allocated slice with at least one element. Compare `Uniq` which compares the elements themselves.

func ValidPk

func ValidPk[Key comparable, Val Pker[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 ValidateKind added in v0.0.13

func ValidateKind(tar r.Type, exp r.Kind)

func ValueClone added in v0.0.5

func ValueClone(src r.Value)

Replaces the given value, which must be settable, with a deep clone, if the value is indirect. See `IsIndirect`.

func ValueCloned added in v0.0.5

func ValueCloned(src r.Value) r.Value

Similar to `CloneDeep` but takes and returns `reflect.Value`.

func ValueDeref

func ValueDeref(val r.Value) r.Value

Dereferences the given value until it's no longer a pointer. If the input is a nil pointer, or if any intermediary pointers are nil, returns an empty/invalid value. Also see `ValueDerefAlloc` which allocates intermediary pointers as necessary/possible.

func ValueDerefAlloc added in v0.0.11

func ValueDerefAlloc(val r.Value) r.Value

Dereferences the given value until it's no longer a pointer, allocating intermediary pointers as necessary/possible. Also see `ValueDerefAlloc` which does not allocate intermediaries.

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 ValueSet added in v0.0.5

func ValueSet(tar, src r.Value)

Idempotent set. Calls `reflect.Value.Set` only if the inputs are distinct.

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 ValueType added in v0.1.7

func ValueType(src r.Value) r.Type

Same as `reflect.Value.Type`, but when value is invalid, returns nil instead of panicking.

func With added in v0.0.8

func With[A any](funs ...func(*A)) (out A)

Makes a zero value of the given type, passes it to the given mutator functions by pointer, and returns the modified value. Nil functions are ignored.

func Wrap added in v0.1.2

func Wrap(err error, msg ...any) error

If the error is nil, returns nil. Otherwise wraps the error, prepending the given message and idempotently adding a stack trace. The message is converted to a string via `Str(msg...)`.

func WrapTracedAt added in v0.1.18

func WrapTracedAt(err error, skip int) error

If the error is nil, returns nil. Otherwise wraps the error into an instance of `Err` without a message with a new stack trace, skipping the given number of frames. Unlike other "traced" functions, this one is NOT idempotent: it doesn't check if the existing errors already have traces, and always adds a trace. This is useful when writing tools that internally use goroutines, in order to "connect" the traces between the goroutine and the caller.

func Wrapf

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

If the error is nil, returns nil. Otherwise wraps the error, prepending the given message and idempotently adding a stack trace. The pattern argument must be a hardcoded pattern string compatible with `fmt.Sprintf` and other similar functions. If the pattern argument is an expression rather than a hardcoded string, use `Wrap` instead.

func Write added in v0.0.12

func Write[Out io.Writer, Src Text](out Out, src Src)

Shortcut for writing the given text to the given `io.Writer`. Automatically converts text to bytes and panics on errors.

func WriteFile added in v0.1.3

func WriteFile[A Text](path string, body A)

Shortcut for `os.WriteFile` with default permissions `os.ModePerm`. Panics on error. Takes an arbitrary text type conforming to `Text` and converts it to bytes without an additional allocation.

func Zero

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

Returns a zero value of the given type.

func ZeroIndex added in v0.0.5

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

Takes a slice and returns the indexes whose elements are zero. All indexes are within the bounds of the original slice.

func ZeroValue

func ZeroValue[A any]() r.Value

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

Types

type AnyGetter added in v0.0.10

type AnyGetter Getter[any]

Used by some 3rd party libraries. Implemented by some of our types for compatibility.

type AppenderTo added in v0.1.6

type AppenderTo interface{ AppendTo([]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 Atom added in v0.0.5

type Atom[A any] atomic.Value

Typed version of `atomic.Value`. Currently implemented as a typedef of `atomic.Value` where the value is internally stored as `any`. Converting non-interface values to `any` may automatically create a copy on the heap. Values other than booleans and machine numbers should be stored by pointer to minimize copying. This may change in the future.

func (*Atom[A]) CompareAndSwap added in v0.0.5

func (self *Atom[A]) CompareAndSwap(prev, next A) bool

Typed version of `atomic.Value.CompareAndSwap`.

func (*Atom[A]) Load added in v0.0.5

func (self *Atom[A]) Load() A

Typed version of `atomic.Value.Load`.

func (*Atom[A]) Loaded added in v0.0.5

func (self *Atom[A]) Loaded() (A, bool)

Like `.Load` but returns true if anything was previously stored, and false if nothing was previously stored.

func (*Atom[A]) Store added in v0.0.5

func (self *Atom[A]) Store(val A)

Typed version of `atomic.Value.Store`.

func (*Atom[A]) Swap added in v0.0.5

func (self *Atom[A]) Swap(val A) A

Typed version of `atomic.Value.Swap`.

type Buf

type Buf []byte

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

func (*Buf) AppendAny

func (self *Buf) AppendAny(val any)

Appends the text representation of the input, using the `AppendTo` function. Mutates the receiver.

func (*Buf) AppendAnys added in v0.0.15

func (self *Buf) AppendAnys(val ...any)

Like `(*Buf).AppendAny` but variadic. TODO better name.

func (*Buf) AppendAnysln added in v0.0.15

func (self *Buf) AppendAnysln(val ...any)

Like `(*Buf).AppendAnys` but ensures a trailing newline in the appended content, similarly to `fmt.Println`. As a special case, if the buffer was empty and the appended content is empty, no newline is appended. TODO better name.

func (*Buf) AppendBool

func (self *Buf) AppendBool(val bool)

Appends text representation of the input. Mutates the receiver.

func (*Buf) AppendByte

func (self *Buf) AppendByte(val byte)

Appends the given byte. Mutates the receiver.

func (*Buf) AppendByteHex added in v0.1.7

func (self *Buf) AppendByteHex(val byte)

Appends text representation of the numeric value of the given byte in base 16. Always uses exactly 2 characters, for consistent width, which is the common convention for printing binary data. Mutates the receiver.

func (*Buf) AppendByteN

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

Appends the given byte N times. Mutates the receiver.

func (*Buf) AppendBytes

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

Appends the given bytes. Mutates the receiver.

func (*Buf) AppendError

func (self *Buf) AppendError(val error)

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

func (*Buf) AppendErrorStack added in v0.1.18

func (self *Buf) AppendErrorStack(val error)

Same as `buf.Fprintf("%+v", val)` but marginally more efficient for `gg.Err` or any other error type that implements `StackAppenderTo`.

func (*Buf) AppendFloat32

func (self *Buf) AppendFloat32(val float32)

Appends text representation of the input. Mutates the receiver.

func (*Buf) AppendFloat64

func (self *Buf) AppendFloat64(val float64)

Appends text representation of the input. Mutates the receiver.

func (*Buf) AppendGoString

func (self *Buf) AppendGoString(val any)

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

func (*Buf) AppendIndent

func (self *Buf) AppendIndent()

Appends `Indent`. Mutates the receiver.

func (*Buf) AppendIndents

func (self *Buf) AppendIndents(lvl int)

Appends `Indent` N times. Mutates the receiver.

func (*Buf) AppendInt

func (self *Buf) AppendInt(val int)

Appends text representation of the input. Mutates the receiver.

func (*Buf) AppendInt64

func (self *Buf) AppendInt64(val int64)

Appends text representation of the input. Mutates the receiver.

func (*Buf) AppendNewline

func (self *Buf) AppendNewline()

Appends `Newline`. Mutates the receiver.

func (*Buf) AppendNewlineOpt added in v0.1.3

func (self *Buf) AppendNewlineOpt()

If the buffer is non-empty and doesn't end with a newline, appends a newline. Otherwise does nothing. Uses `HasNewlineSuffix`. Mutates the receiver.

func (*Buf) AppendNewlines

func (self *Buf) AppendNewlines(count int)

Appends `Newline` N times. Mutates the receiver.

func (*Buf) AppendRune

func (self *Buf) AppendRune(val rune)

Appends the given rune. Mutates the receiver.

func (*Buf) AppendRuneN added in v0.0.19

func (self *Buf) AppendRuneN(val rune, count int)

Appends the given rune N times. Mutates the receiver.

func (*Buf) AppendSpace

func (self *Buf) AppendSpace()

Appends a single space. Mutates the receiver.

func (*Buf) AppendSpaces

func (self *Buf) AppendSpaces(count int)

Appends a space N times. Mutates the receiver.

func (*Buf) AppendString

func (self *Buf) AppendString(val string)

Appends the given string. Mutates the receiver.

func (*Buf) AppendStringN

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

Appends the given string N times. Mutates the receiver.

func (Buf) AppendTo added in v0.1.6

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

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

func (*Buf) AppendUint added in v0.0.2

func (self *Buf) AppendUint(val uint)

Appends text representation of the input. Mutates the receiver.

func (*Buf) AppendUint64 added in v0.0.2

func (self *Buf) AppendUint64(val uint64)

Appends text representation of the input. Mutates the receiver.

func (*Buf) AppendUint64Hex added in v0.1.7

func (self *Buf) AppendUint64Hex(val uint64)

Appends text representation of the input in base 16. Mutates the receiver. Also see `.AppendByteHex`.

func (*Buf) Clear

func (self *Buf) Clear()

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

func (*Buf) Fprintf

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

Shortcut for appending a formatted string.

func (*Buf) Fprintlnf

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

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

func (*Buf) GrowCap

func (self *Buf) GrowCap(size int)

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

func (*Buf) GrowLen

func (self *Buf) GrowLen(size int)

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

func (Buf) Len

func (self Buf) Len() int

Same as `len(buf)`.

func (*Buf) Reset added in v0.0.2

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

Replaces the buffer with the given slice.

func (Buf) String

func (self Buf) String() string

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

func (*Buf) TruncLen added in v0.0.19

func (self *Buf) TruncLen(size int)

Reduces the current length to the given size. If the current length is already shorter, it's unaffected.

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 Initer1Ptr[Val, Key],
] struct {
	Map  map[Key]Ptr
	Lock sync.RWMutex
}

Concurrency-safe cache. See the method reference.

func CacheOf

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

Type-inferring shortcut for creating a `Cache` of the given type.

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

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

Deletes the value for the given key.

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

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

Shortcut for using `.Ptr` and dereferencing the result. May be invalid if the resulting value is non-copyable, for example when it contains a mutex.

func (*Cache[Key, Val, Ptr]) Ptr added in v0.0.3

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

Returns the cached value for the given key. If the value did not previously exist, idempotently initializes it by calling `.Init` (by pointer) and caches the result. For any given key, the value is initialized exactly once, even if multiple goroutines are trying to access it simultaneously.

type Caller

type Caller uintptr

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

func (Caller) AppendIndentTo added in v0.1.18

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

func (Caller) AppendNewlineIndentTo added in v0.1.18

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

func (Caller) AppendTo added in v0.1.6

func (self Caller) AppendTo(buf []byte) []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 Chan added in v0.0.12

type Chan[A any] chan A

Alias of `chan` with additional convenience methods.

func (Chan[_]) Close added in v0.0.12

func (self Chan[_]) Close()

Closes the channel unless it's nil.

func (*Chan[A]) Init added in v0.0.12

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

Same as global `ChanInit`.

func (*Chan[A]) InitCap added in v0.0.12

func (self *Chan[A]) InitCap(cap int) Chan[A]

Same as global `ChanInitCap`.

func (Chan[A]) Receive added in v0.1.22

func (self Chan[A]) Receive() A

Same as global `Receive`.

func (Chan[A]) Send added in v0.1.22

func (self Chan[A]) Send(val A)

Same as global `Send`.

func (Chan[A]) SendOpt added in v0.0.12

func (self Chan[A]) SendOpt(val A)

Same as global `SendOpt`.

func (Chan[A]) SendZeroOpt added in v0.0.12

func (self Chan[A]) SendZeroOpt()

Same as global `SendZeroOpt`.

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
	Ptrer[A]
}

Used by some utility functions.

type Coll

type Coll[Key comparable, Val Pker[Key]] OrdMap[Key, Val]

Short for "collection". Represents an ordered map where keys are automatically derived from values. Compare `OrdMap` where keys are provided externally. Keys must be non-zero. Similarly to a map, this ensures value uniqueness by primary key, and allows efficient access by key. Unlike a map, values in this type are ordered and can be iterated cheaply, because they are stored in a publicly-accessible slice. However, as a tradeoff, this type does not support deletion.

func CollFrom added in v0.1.1

func CollFrom[Key comparable, Val Pker[Key], Slice ~[]Val](src ...Slice) Coll[Key, Val]

Syntactic shortcut for making a `Coll` from any number of source slices. When called with exactly one argument, this reuses the given slice as-is with no reallocation.

func CollOf added in v0.1.1

func CollOf[Key comparable, Val Pker[Key]](src ...Val) Coll[Key, Val]

Syntactic shortcut for making a `Coll` of the given arguments. Reuses the given slice as-is with no reallocation.

func (*Coll[Key, Val]) Add

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

Idempotently adds each given value to both the inner slice and the inner index. Every value whose key already exists in the index is replaced at the existing position in the slice.

func (*Coll[Key, Val]) AddUniq added in v0.1.17

func (self *Coll[Key, Val]) AddUniq(src ...Val) *Coll[Key, Val]

Same as `Coll.Add`, but panics if any inputs are redundant, as in, their primary keys are already present in the index.

func (*Coll[Key, Val]) Clear

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

Same as `OrdMap.Clear`.

func (Coll[Key, Val]) Get

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

Same as `OrdMap.Get`.

func (Coll[Key, Val]) GetReq added in v0.1.11

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

Same as `OrdMap.GetReq`.

func (Coll[Key, Val]) Got

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

Same as `OrdMap.Got`.

func (Coll[Key, _]) Has

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

Same as `OrdMap.Has`.

func (Coll[_, _]) IsEmpty added in v0.0.16

func (self Coll[_, _]) IsEmpty() bool

Same as `OrdMap.IsEmpty`.

func (Coll[_, _]) IsNotEmpty added in v0.1.6

func (self Coll[_, _]) IsNotEmpty() bool

Same as `OrdMap.IsNotEmpty`.

func (*Coll[Key, Val]) LazyColl added in v0.1.11

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

Free cast to equivalent `LazyColl`.

func (Coll[_, _]) Len

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

Same as `OrdMap.Len`.

func (Coll[_, _]) MarshalJSON

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

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

func (*Coll[Key, Val]) OrdMap added in v0.1.19

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

Free cast into the equivalent `*OrdMap`. Note that mutating the resulting `OrdMap` via methods such as `OrdMap.Add` may violate guarantees of the `Coll` type, mainly that each value is stored under the key returned by its `.Pk` method.

func (Coll[Key, Val]) Ptr added in v0.0.3

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

Same as `OrdMap.Ptr`.

func (Coll[Key, Val]) PtrReq added in v0.1.11

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

Same as `OrdMap.PtrReq`.

func (*Coll[Key, Val]) Reindex added in v0.1.1

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

Rebuilds the inner index from the inner slice, without checking the validity of the existing index. Can be useful for external code that directly modifies the inner `.Slice`, for example by sorting it. This is NOT used when adding items via `.Add`, which modifies the index incrementally rather than all-at-once.

func (*Coll[Key, Val]) Reset added in v0.1.11

func (self *Coll[Key, Val]) Reset(src ...Val) *Coll[Key, Val]

Replaces `.Slice` with the given slice and rebuilds `.Index`. Uses the slice as-is with no reallocation. Callers must be careful to avoid modifying the source data, which may invalidate the collection's index.

func (Coll[Key, _]) Swap added in v0.1.4

func (self Coll[Key, _]) Swap(ind0, ind1 int)

Swaps two elements both in `.Slice` and in `.Index`. Useful for sorting. `.Index` may be nil, in which case it's unaffected. Slice indices must be either equal or valid.

func (*Coll[_, _]) UnmarshalJSON

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

Implement `json.Unmarshaler`. Decodes the input into the inner slice and rebuilds the index.

type Complex added in v0.1.7

type Complex interface{ ~complex64 | ~complex128 }

Describes all built-in complex number types and their typedefs.

type ConcRaceSlice added in v0.1.0

type ConcRaceSlice []func(context.Context)

Tool for concurrent execution. Similar to `ConcSlice`, but with support for context and cancelation. See `ConcRaceSlice.RunCatch` for details.

func ConcRace added in v0.1.0

func ConcRace(src ...func(context.Context)) ConcRaceSlice

Shortcut for constructing `ConcRaceSlice` in a variadic call with parens rather than braces.

func (*ConcRaceSlice) Add added in v0.1.0

func (self *ConcRaceSlice) Add(fun func(context.Context))

If the given func is non-nil, adds it to the slice for later execution.

func (ConcRaceSlice) Run added in v0.1.0

func (self ConcRaceSlice) Run(ctx context.Context)

Shortcut. Runs the functions via `ConcRaceSlice.RunCatch`. If the resulting error is non-nil, panics with that error, idempotently adding a stack trace.

func (ConcRaceSlice) RunCatch added in v0.1.0

func (self ConcRaceSlice) RunCatch(ctx context.Context) (err error)

Runs the functions concurrently. Blocks until all functions complete successfully, returning nil. If one of the functions panics, cancels the context passed to each function, and immediately returns the resulting error, without waiting for the other functions to terminate. In this case, the panics in other functions, if any, are caught and ignored.

Ensures that the resulting error has a stack trace, both on the current goroutine, and on the sub-goroutine used for concurrent execution, wrapping errors as necessary.

type ConcSlice added in v0.0.20

type ConcSlice []func()

Tiny shortcut for gradually building a list of funcs which are later to be executed concurrently. This type's methods invoke global funcs such as `Conc`. Compare `ConcRaceSlice`.

func (*ConcSlice) Add added in v0.0.20

func (self *ConcSlice) Add(fun func())

If the given func is non-nil, adds it to the slice for later execution.

func (ConcSlice) Run added in v0.0.20

func (self ConcSlice) Run()

Same as calling `Conc` with the given slice of funcs.

func (ConcSlice) RunCatch added in v0.0.20

func (self ConcSlice) RunCatch() []error

Same as calling `ConcCatch` with the given slice of funcs.

func (ConcSlice) RunSeq added in v0.0.20

func (self ConcSlice) RunSeq()

Runs the given funcs sequentially rather than concurrently. Provided for performance debugging.

type DbNameToJsonField added in v0.0.12

type DbNameToJsonField map[string]r.StructField

func (*DbNameToJsonField) Init added in v0.0.12

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

type DbNameToJsonName added in v0.0.7

type DbNameToJsonName map[string]string

func (*DbNameToJsonName) Init added in v0.0.7

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

type Decoder

type Decoder interface {
	Clearer
	Parser
	Scanner
}

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

type Defaulter added in v0.1.0

type Defaulter interface{ Default() }

The method `.Default` must modify the receiver, applying default values to its components, usually to struct fields. The receiver must be mutable, usually a pointer. See `DefaulterPtr` for a more precise type constraint.

type DefaulterPtr added in v0.1.0

type DefaulterPtr[A any] interface {
	*A
	Defaulter
}

Pointer version of `Defaulter`.

type Dict added in v0.0.5

type Dict[Key comparable, Val any] map[Key]Val

Typedef of an arbitrary map with various methods that duplicate global map functions. Useful as a shortcut for creating bound methods that can be passed to higher-order functions.

func ToDict added in v0.0.5

func ToDict[Src ~map[Key]Val, Key comparable, Val any](val Src) Dict[Key, Val]

Shortcut for converting an arbitrary map to `Dict`. Workaround for the limitations of type inference in Go generics. This is a free cast with no reallocation.

func (Dict[_, _]) Clear added in v0.0.5

func (self Dict[_, _]) Clear()

Self as global `MapClear`.

func (Dict[Key, Val]) Clone added in v0.0.5

func (self Dict[Key, Val]) Clone() Dict[Key, Val]

Self as global `MapClone`.

func (Dict[Key, _]) Del added in v0.0.5

func (self Dict[Key, _]) Del(key Key)

Self as global `MapDel`.

func (Dict[Key, Val]) Get added in v0.0.5

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

Self as global `MapGet`.

func (Dict[Key, Val]) Got added in v0.0.5

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

Self as global `MapGot`.

func (Dict[Key, _]) Has added in v0.0.5

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

Self as global `MapHas`.

func (*Dict[Key, Val]) Init added in v0.0.5

func (self *Dict[Key, Val]) Init() Dict[Key, Val]

Self as global `MapInit`.

func (Dict[_, _]) IsEmpty added in v0.1.9

func (self Dict[_, _]) IsEmpty() bool

Same as `len(self) <= 0`. Inverse of `.IsNotEmpty`.

func (Dict[_, _]) IsNotEmpty added in v0.1.9

func (self Dict[_, _]) IsNotEmpty() bool

Same as `len(self) > 0`. Inverse of `.IsEmpty`.

func (Dict[Key, _]) Keys added in v0.0.5

func (self Dict[Key, _]) Keys() []Key

Self as global `MapKeys`.

func (Dict[_, _]) Len added in v0.1.9

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

Same as `len(self)`.

func (Dict[Key, Val]) Set added in v0.0.5

func (self Dict[Key, Val]) Set(key Key, val Val)

Self as global `MapSet`.

func (Dict[Key, Val]) SetOpt added in v0.0.7

func (self Dict[Key, Val]) SetOpt(key Key, val Val)

Self as global `MapSetOpt`.

func (Dict[_, Val]) Vals added in v0.0.5

func (self Dict[_, Val]) Vals() []Val

Self as global `MapVals`.

type DurHour added in v0.0.2

type DurHour struct{}

Implements `Durationer` by returning `time.Hour`. This type is zero-sized, and can be embedded in other types, like a mixin, at no additional cost.

func (DurHour) Duration added in v0.0.2

func (DurHour) Duration() time.Duration

Implement `Durationer` by returning `time.Hour`.

type DurMinute added in v0.0.2

type DurMinute struct{}

Implements `Durationer` by returning `time.Minute`. This type is zero-sized, and can be embedded in other types, like a mixin, at no additional cost.

func (DurMinute) Duration added in v0.0.2

func (DurMinute) Duration() time.Duration

Implement `Durationer` by returning `time.Minute`.

type DurSecond added in v0.0.2

type DurSecond struct{}

Implements `Durationer` by returning `time.Second`. This type is zero-sized, and can be embedded in other types, like a mixin, at no additional cost.

func (DurSecond) Duration added in v0.0.2

func (DurSecond) Duration() time.Duration

Implement `Durationer` by returning `time.Second`.

type Durationer added in v0.1.9

type Durationer interface{ Duration() time.Duration }

Interface for values which are convertible to `time.Duration` or can specify a lifetime for other values. Used by `Mem`.

type Encoder

type Encoder interface {
	fmt.Stringer
	AppenderTo
	Nullable
	driver.Valuer
}

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

type Equaler added in v0.0.5

type Equaler[A any] interface{ Equal(A) bool }

Implemented by some types such as `time.Time`, and invoked automatically by our function `Equal`.

type Err

type Err struct {
	Msg   string
	Cause error
	Trace *Trace // By pointer to allow `==` without panics.
}

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

func AnyToErrTracedAt added in v0.1.3

func AnyToErrTracedAt(val any, skip int) (_ Err)

Similar to `AnyErrTracedAt`, but always returns a value of the concrete type `Err`. If the input is nil, the output is zero. Otherwise the output is always non-zero. The message is derived from the input. The stack trace is reused from the input if possible, otherwise it's generated here, skipping the given amount of stack frames.

func Errf

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

Creates an error where the message is generated by passing the arguments to `fmt.Sprintf`, with a stack trace. Also see `Errv`.

func Errv added in v0.0.19

func Errv(val ...any) Err

Creates an error where the message is generated by passing the arguments to `Str`, with a stack trace. Suffix "v" is short for "vector", alluding to how all arguments are treated equally, as opposed to "f" ("format") where the first argument is a formatting pattern.

func (Err) AppendStackTo added in v0.1.18

func (self Err) AppendStackTo(buf []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) AppendTo added in v0.1.6

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

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

func (Err) Caused

func (self Err) Caused(val error) Err

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

func (Err) Err added in v0.0.2

func (self Err) Err() error

Implement `Errer`. If the receiver is a zero value, returns nil. Otherwise casts the receiver to an 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, arg ...any) Err

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

func (Err) Msgv added in v0.0.19

func (self Err) Msgv(src ...any) Err

Returns a modified version where `.Msg` is set to a concatenation of strings generated from the arguments, via `Str`. See `StringCatch` for the encoding rules.

func (Err) OwnTrace added in v0.1.18

func (self Err) OwnTrace() Trace

Safely dereferences `.Trace`, returning nil if the pointer is nil.

func (Err) Stack

func (self Err) Stack() string

Returns a text representation of the full error message with the stack trace, if any. The method's name is chosen for consistency with the getter `Error.prototype.stack` in JS, which behaves exactly like this method.

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) TracedAt added in v0.1.0

func (self Err) TracedAt(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) TracedOptAt added in v0.1.0

func (self Err) TracedOptAt(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 `AnyErr` and some other error-related functions.

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 ErrFinder added in v0.0.10

type ErrFinder interface{ Find(func(error) bool) error }

Allows to customize/override `ErrFind`, which prioritizes this interface over the default behavior.

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 Errer added in v0.0.2

type Errer interface{ Err() error }

Implemented by various types such as `context.Context`, `sql.Rows`, and our own `Errs`.

type Errs

type Errs []error

Combines multiple errors. Used by `Conc`. Caution: although this implements the `error` interface, avoid casting this to `error`. Even when the slice is nil, the resulting interface value would be non-nil, which is incorrect. Instead, call the method `Errs.Err`, which will correctly return a nil interface value when all errors are nil.

func (Errs) AppendTo added in v0.1.6

func (self Errs) AppendTo(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) Err added in v0.0.2

func (self Errs) Err() error

Implement `Errer`. If there are any non-nil errors, returns a non-nil error, unwrapping if possible. Otherwise returns nil. Does NOT generate a stack trace or modify the errors in any way.

func (Errs) Error

func (self Errs) Error() string

Implement `error`.

func (Errs) Find added in v0.0.10

func (self Errs) Find(fun func(error) bool) error

Returns the first error that satisfies the given test function, by calling `ErrFind` on each element. Order is depth-first rather than breadth-first.

func (Errs) First

func (self Errs) First() error

First non-nil error.

func (Errs) Is

func (self Errs) Is(err error) bool

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

func (Errs) IsEmpty added in v0.0.19

func (self Errs) IsEmpty() bool

True if there are no non-nil errors. Inverse of `.IsNotEmpty`.

func (Errs) IsNotEmpty added in v0.1.6

func (self Errs) IsNotEmpty() bool

True if there are any non-nil errors. Inverse of `.IsEmpty`.

func (Errs) LenNil

func (self Errs) LenNil() int

Counts nil errors.

func (Errs) LenNotNil added in v0.1.6

func (self Errs) LenNotNil() int

Counts non-nil errors.

func (Errs) Some added in v0.0.10

func (self Errs) Some(fun func(error) bool) bool

Shortcut for `.Find(fun) != nil`. Returns true if at least one error satisfies the given predicate function, using `ErrFind` to unwrap.

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, panics with a stack trace.

func (Errs) Unwrap

func (self Errs) Unwrap() error

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

func (Errs) WrapTracedAt added in v0.1.18

func (self Errs) WrapTracedAt(skip int)

Adds a stack trace to each non-nil error via `WrapTracedAt`. Useful when writing tools that internally use goroutines.

type FlagDef added in v0.0.13

type FlagDef struct {
	Type  r.Type
	Args  FlagDefField
	Flags []FlagDefField
	Index map[string]int
}

Struct type definition suitable for flag parsing. Used internally by `FlagParser`. User code shouldn't have to use this type, but it's exported for customization purposes.

func (*FlagDef) AddField added in v0.0.13

func (self *FlagDef) AddField(src r.StructField)

For internal use.

func (FlagDef) Get added in v0.0.13

func (self FlagDef) Get(key string) FlagDefField

For internal use.

func (FlagDef) Got added in v0.0.13

func (self FlagDef) Got(key string) (FlagDefField, bool)

For internal use.

func (FlagDef) Help added in v0.0.13

func (self FlagDef) Help() string

Creates a help string listing the available flags, using `FlagFmtDefault`.

func (*FlagDef) Init added in v0.0.13

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

For internal use.

type FlagDefField added in v0.0.13

type FlagDefField struct {
	r.StructField
	Flag    string
	FlagHas bool
	FlagLen int
	Init    string
	InitHas bool
	InitLen int
	Desc    string
	DescHas bool
	DescLen int
}

Used internally by `FlagDef`.

func (FlagDefField) GetDescHas added in v0.0.13

func (self FlagDefField) GetDescHas() bool

func (FlagDefField) GetDescLen added in v0.0.13

func (self FlagDefField) GetDescLen() int

func (FlagDefField) GetFlagHas added in v0.0.13

func (self FlagDefField) GetFlagHas() bool

func (FlagDefField) GetFlagLen added in v0.0.13

func (self FlagDefField) GetFlagLen() int

func (FlagDefField) GetInitHas added in v0.0.13

func (self FlagDefField) GetInitHas() bool

func (FlagDefField) GetInitLen added in v0.0.13

func (self FlagDefField) GetInitLen() int

func (FlagDefField) IsValid added in v0.1.0

func (self FlagDefField) IsValid() bool

func (*FlagDefField) Set added in v0.0.13

func (self *FlagDefField) Set(src r.StructField)

type FlagFmt added in v0.0.13

type FlagFmt struct {
	Prefix    string // Prepended before each line.
	Infix     string // Inserted between columns.
	Head      bool   // If true, print table header.
	FlagHead  string // Title for header cell "flag".
	InitHead  string // Title for header cell "init".
	DescHead  string // Title for header cell "desc".
	HeadUnder string // Separator between table header and body.
}

Table-like formatter for listing available flags, initial values, and descriptions. Used via `FlagFmtDefault`, `FlagHelp`, `FlagDef.Help`. To customize printing, mutate `FlagFmtDefault`.

func (FlagFmt) AppendTo added in v0.1.6

func (self FlagFmt) AppendTo(src []byte, def FlagDef) []byte

Appends table-like help for the given definition. Known limitation: assumes monospace, doesn't support wider characters such as kanji or emoji.

func (*FlagFmt) Default added in v0.0.13

func (self *FlagFmt) Default()

Sets default values.

func (FlagFmt) String added in v0.0.13

func (self FlagFmt) String(def FlagDef) string

Returns a table-like help string for the given definition.

type FlagParser added in v0.0.13

type FlagParser struct {
	Tar r.Value
	Def FlagDef
	Got Set[string]
}

Tool for parsing lists of CLI flags into structs. Partial replacement for the standard library package "flag". Example:

type Opt struct {
	Args []string `flag:""`
	Help bool     `flag:"-h"          desc:"Print help and exit."`
	Verb bool     `flag:"-v"          desc:"Verbose logging."`
	Src  string   `flag:"-s" init:"." desc:"Source path."`
	Out  string   `flag:"-o"          desc:"Destination path."`
}

func (self *Opt) Init() {
	gg.FlagParse(os.Args[1:], self)

	if self.Help {
		log.Println(gg.FlagHelp[Opt]())
		os.Exit(0)
	}

	if gg.IsZero(self.Out) {
		log.Println(`missing output path: "-o"`)
		os.Exit(1)
	}
}

Supported struct tags:

  • `flag`: must be "" or a valid flag like "-v" or "--verbose". Fields without the `flag` tag are ignored. Flags must be unique.
  • Field with `flag:""` is used for remaining non-flag args. It must have a type convertible to `[]string`.
  • `init`: initial value. Used if the flag was not provided.
  • `desc`: description. Used for help printing.

Parsing rules:

  • Supports all primitive types.
  • Supports slices of arbitrary types.
  • Supports `gg.Parser`.
  • Supports `encoding.TextUnmarshaler`.
  • Supports `flag.Value`.
  • Each flag may be listed multiple times.
  • If the target is a parser, invoke its parsing method.
  • If the target is a scalar, replace the old value with the new value.
  • If the target is a slice, append the new value.

func (FlagParser) Args added in v0.0.13

func (self FlagParser) Args(src []string)

Parses the given CLI args into the destination. May be called multiple times. Must be called after `(*FlagParser).Init`, and before `FlagParser.Default`.

func (FlagParser) Default added in v0.1.0

func (self FlagParser) Default()

Applies defaults to all flags which have not been found during parsing. Explicitly providing an empty value suppresses a default, although an empty string may not be a viable input to some types.

func (FlagParser) FieldParse added in v0.0.13

func (self FlagParser) FieldParse(src string, out r.Value)

For internal use.

func (FlagParser) Flag added in v0.0.13

func (self FlagParser) Flag(key, src string)

For internal use.

func (FlagParser) FlagField added in v0.0.13

func (self FlagParser) FlagField(key string) r.Value

For internal use.

func (*FlagParser) Init added in v0.0.13

func (self *FlagParser) Init(tar r.Value)

Initializes the parser for the given destination, which must be a settable struct value.

func (FlagParser) SetArgs added in v0.0.13

func (self FlagParser) SetArgs(src []string)

For internal use.

func (FlagParser) TrailingBool added in v0.0.13

func (self FlagParser) TrailingBool(key string) bool

For internal use.

func (FlagParser) TrailingFlag added in v0.0.13

func (self FlagParser) TrailingFlag(key string)

For internal use.

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) AppendIndentTo added in v0.1.18

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

func (Frame) AppendNewlineIndentTo added in v0.1.18

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

func (Frame) AppendRowIndentTo added in v0.1.18

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

func (Frame) AppendTo added in v0.1.6

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

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

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

Used for stack trace formatting.

func (Frames) AppendIndentTableTo added in v0.1.18

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

func (Frames) NameWidth

func (self Frames) NameWidth() int

type Getter

type Getter[A any] interface{ Get() A }

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

type GraphDir added in v0.1.1

type GraphDir struct {
	Path  string
	Files Coll[string, GraphFile]
}

Represents a directory where the files form a graph by "importing" each other, by using special annotations understood by this tool. Supports reading files from the filesystem, validating the dependency graph, and calculating valid execution order for the resulting graph. Mostly designed and suited for emulating a module system for SQL files. May be useful in other similar cases.

The import annotation is currently not customizable and must look like the following example. Each entry must be placed at the beginning of a line. In files that contain code, do this within multi-line comments without any prefix.

@import some_file_name_0
@import some_file_name_1

Current limitations:

  • The import annotation is non-customizable.
  • No support for file filtering.
  • No support for relative paths. Imports must refer to files by base names.
  • No support for `fs.FS` or other ways to customize reading. Always uses the OS filesystem.

func GraphDirInit added in v0.1.2

func GraphDirInit(path string) GraphDir

Shortcut for making `GraphDir` with the given path and fully initializing it via `.Init`.

func (GraphDir) File added in v0.1.1

func (self GraphDir) File(key string) GraphFile

Returns the `GraphFile` indexed by the given key. Panics if the file is not found.

func (*GraphDir) Init added in v0.1.1

func (self *GraphDir) Init()

Reads the files in the directory specified by `.Path`, then builds and validates the dependency graph. After calling this method, the files in `.Files.Slice` represent valid execution order.

func (GraphDir) Names added in v0.1.1

func (self GraphDir) Names() []string

Returns the names of `.Files`, in the same order.

type GraphFile added in v0.1.1

type GraphFile struct {
	Path string   // Valid FS path. Directory must match parent `GraphDir`.
	Body string   // Read from disk by `.Init`.
	Deps []string // Parsed from `.Body` by `.Init`.
}

Represents a file in a graph of files that import each other by using special import annotations understood by this tool. See `GraphDir` for explanation.

func (*GraphFile) Init added in v0.1.1

func (self *GraphFile) Init(dir, name string)

Sets `.Path` to the combination of the given directory and base name, reads the file from FS into `.Body`, and parses the import annotations into `.Deps`. Called automatically by `GraphDir.Init`.

func (GraphFile) Pk added in v0.1.1

func (self GraphFile) Pk() string

Implement `Pker` for compatibility with `Coll`. See `GraphDir.Files`.

type Initer added in v0.1.0

type Initer interface{ Init() }

The method `.Init` must modify the receiver, initializing any components that need initialization, for example using `make` to create inner maps or chans. The receiver must be mutable, usually a pointer. See `IniterPtr` for a more precise type constraint. Also see `Initer1` which is more commonly used in this library.

type Initer1

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

The method `.Init` must modify the receiver, initializing any components that need initialization, for example using `make` to create inner maps or chans. The receiver must be mutable, usually a pointer. See `Initer1Ptr` for a more precise type constraint. Also see nullary `Initer`.

type Initer1Ptr added in v0.1.0

type Initer1Ptr[A, B any] interface {
	*A
	Initer1[B]
}

Pointer version of `Initer1`.

type IniterPtr added in v0.1.0

type IniterPtr[A any] interface {
	*A
	Initer
}

Pointer version of `Initer`.

type Int

type Int interface{ Sint | Uint }

Describes all built-in integer types and their typedefs.

type JsonNameToDbField added in v0.0.12

type JsonNameToDbField map[string]r.StructField

func (*JsonNameToDbField) Init added in v0.0.12

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

type JsonNameToDbName added in v0.0.7

type JsonNameToDbName map[string]string

func (*JsonNameToDbName) Init added in v0.0.7

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

type Lazy

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

Similar to `sync.Once`, but specialized for creating and caching one value, instead of relying on nullary functions and side effects. Created via `NewLazy`. Calling `.Get` on the resulting object will idempotently call the given function and cache the result, and discard the function. Uses `sync.Once` internally for synchronization.

func NewLazy added in v0.1.0

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

Creates `Lazy` with the given function. See the type's description for details.

func (*Lazy[A]) Get added in v0.1.0

func (self *Lazy[A]) Get() A

Returns the inner value after idempotently creating it. This method is synchronized and safe for concurrent use.

type LazyColl added in v0.1.11

type LazyColl[Key comparable, Val Pker[Key]] Coll[Key, Val]

Short for "lazy collection". Variant of `Coll` where the index is built lazily rather than immediately. This is not the default behavior in `Coll` because it requires various access methods such as `.Has` and `.Get` to be defined on the pointer type rather than value type, and more importantly, it's more error prone: the caller is responsible for making sure that the collection is always accessed by pointer, never by value, to avoid redundant reindexing.

func LazyCollFrom added in v0.1.11

func LazyCollFrom[Key comparable, Val Pker[Key], Slice ~[]Val](src ...Slice) LazyColl[Key, Val]

Same as `CollFrom` but for `LazyColl`. Note that while the return type is a non-pointer for easy assignment, callers must always access `LazyColl` by pointer to avoid redundant reindexing.

func LazyCollOf added in v0.1.11

func LazyCollOf[Key comparable, Val Pker[Key]](src ...Val) LazyColl[Key, Val]

Same as `CollOf` but for `LazyColl`. Note that while the return type is a non-pointer for easy assignment, callers must always access `LazyColl` by pointer to avoid redundant reindexing.

func (*LazyColl[Key, Val]) Add added in v0.1.11

func (self *LazyColl[Key, Val]) Add(src ...Val) *LazyColl[Key, Val]

Similar to `Coll.Add`, but does not add new entries to the index.

func (*LazyColl[Key, Val]) AddUniq added in v0.1.17

func (self *LazyColl[Key, Val]) AddUniq(src ...Val) *LazyColl[Key, Val]

Same as `Coll.AddUniq`. Lazily rebuilds the index.

func (*LazyColl[Key, Val]) Clear added in v0.1.11

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

Same as `Coll.Clear`.

func (*LazyColl[Key, Val]) Coll added in v0.1.11

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

Converts to equivalent `Coll`. Lazily rebuilds the index if necessary.

func (*LazyColl[Key, Val]) Get added in v0.1.11

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

Same as `Coll.Get`. Lazily rebuilds the index if necessary.

func (*LazyColl[Key, Val]) GetReq added in v0.1.11

func (self *LazyColl[Key, Val]) GetReq(key Key) Val

Same as `Coll.GetReq`. Lazily rebuilds the index if necessary.

func (*LazyColl[Key, Val]) Got added in v0.1.11

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

Same as `Coll.Got`. Lazily rebuilds the index if necessary.

func (*LazyColl[Key, _]) Has added in v0.1.11

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

Same as `Coll.Has`. Lazily rebuilds the index if necessary.

func (LazyColl[_, _]) IsEmpty added in v0.1.11

func (self LazyColl[_, _]) IsEmpty() bool

Same as `Coll.IsEmpty`.

func (LazyColl[_, _]) IsNotEmpty added in v0.1.11

func (self LazyColl[_, _]) IsNotEmpty() bool

Same as `Coll.IsNotEmpty`.

func (LazyColl[_, _]) Len added in v0.1.11

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

Same as `Coll.Len`.

func (LazyColl[_, _]) MarshalJSON added in v0.1.11

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

Implement `json.Marshaler`. Same as `Coll.MarshalJSON`. Encodes the inner slice, ignoring the index.

func (*LazyColl[Key, Val]) Ptr added in v0.1.11

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

Same as `Coll.Ptr`. Lazily rebuilds the index if necessary.

func (*LazyColl[Key, Val]) PtrReq added in v0.1.11

func (self *LazyColl[Key, Val]) PtrReq(key Key) *Val

Same as `Coll.PtrReq`. Lazily rebuilds the index if necessary.

func (*LazyColl[Key, Val]) Reindex added in v0.1.11

func (self *LazyColl[Key, Val]) Reindex() *LazyColl[Key, Val]

Same as `Coll.Reindex`.

func (*LazyColl[Key, _]) ReindexOpt added in v0.1.11

func (self *LazyColl[Key, _]) ReindexOpt()

Rebuilds the index if the length of inner slice and index doesn't match. This is used internally by all "read" methods on this type.

func (*LazyColl[Key, Val]) Reset added in v0.1.11

func (self *LazyColl[Key, Val]) Reset(src ...Val) *LazyColl[Key, Val]

Same as `Coll.Reset` but deletes the index instead of rebuilding it.

func (*LazyColl[Key, _]) Swap added in v0.1.11

func (self *LazyColl[Key, _]) Swap(ind0, ind1 int)

Same as `Coll.Swap` but deletes the index instead of modifying it.

func (*LazyColl[_, _]) UnmarshalJSON added in v0.1.11

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

Implement `json.Unmarshaler`. Similar to `Coll.UnmarshalJSON`, but after decoding the input into the inner slice, deletes the index instead of rebuilding it.

type LazyIniter added in v0.1.7

type LazyIniter[Val any, Ptr IniterPtr[Val]] struct {
	// contains filtered or unexported fields
}

Encapsulates a lazily-initializable value. The first call to `.Get` or `.Ptr` initializes the underlying value by calling its `.Init` method. Initialization is performed exactly once. Access is synchronized. All methods are concurrency-safe. Designed to be embeddable. A zero value is ready to use. When using this as a struct field, you don't need to explicitly initialize the field. Contains a mutex and must not be copied.

func NewLazyIniter added in v0.1.7

func NewLazyIniter[Val any, Ptr IniterPtr[Val]]() *LazyIniter[Val, Ptr]

Shortcut for type inference. The following is equivalent:

NewLazyIniter[Val]()
new(LazyIniter[Val, Ptr])

func (*LazyIniter[_, _]) Clear added in v0.1.21

func (self *LazyIniter[_, _]) Clear()

Clears the underlying value. After this call, the next call to `LazyIniter.Get` or `LazyIniter.Ptr` will reinitialize by invoking the `.Init` method of the underlying value.

func (*LazyIniter[Val, _]) Get added in v0.1.7

func (self *LazyIniter[Val, _]) Get() Val

Returns the underlying value, lazily initializing it on the first call.

func (*LazyIniter[Val, _]) Reset added in v0.1.21

func (self *LazyIniter[Val, _]) Reset(src Val)

Resets the underlying value to the given input. After this call, the underlying value is considered to be initialized. Further calls to `LazyIniter.Get` or `LazyIniter.Ptr` will NOT reinitialize until `.Clear` is called.

type Lener added in v0.1.9

type Lener interface{ Len() int }

Must return the length of a collection, such as a slice, map, text, etc. Implemented by various collection types in this package.

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 LogTime added in v0.1.4

type LogTime struct {
	Start time.Time
	Msg   string
}

Shortcut for logging execution timing to stderr. Usage examples:

defer gg.LogTimeNow(`some_activity`).LogStart().LogEnd()
// perform some activity

defer gg.LogTimeNow(`some_activity`).LogEnd()
// perform some activity

timer := gg.LogTimeNow(`some_activity`).LogStart()
// perform some activity
timer.LogEnd()

timer := gg.LogTimeNow(`some_activity`)
// perform some activity
timer.LogEnd()

func LogTimeNow added in v0.1.4

func LogTimeNow(msg ...any) LogTime

Shortcut for creating `LogTime` with the current time and with a message generated from the inputs via `Str`.

func (LogTime) LogEnd added in v0.1.4

func (self LogTime) LogEnd() LogTime

Prints the end of the activity denoted by `.Msg`, with time elapsed since the beginning:

[some_activity] done in <duration>

If deferred, this will detect the current panic, if any, and print the following instead:

[some_activity] failed in <duration>

func (LogTime) LogStart added in v0.1.4

func (self LogTime) LogStart() LogTime

Logs the beginning of the activity denoted by `.Msg`:

[some_activity] starting

type Maybe

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

Contains a value or an error. The JSON tags "value" and "error" are chosen due to their existing popularity in HTTP API.

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[A]) Get added in v0.0.3

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

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

func (Maybe[_]) GetErr

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

Returns the underlying error as-is.

func (Maybe[_]) HasErr

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

True if error is non-nil.

func (Maybe[_]) MarshalJSON

func (self Maybe[_]) 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]) Set added in v0.0.3

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

Implement `Setter`. Sets the underlying value and clears 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[_]) UnmarshalJSON

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

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

type Mem added in v0.0.2

type Mem[Dur Durationer, Tar any, Ptr IniterPtr[Tar]] struct {
	// contains filtered or unexported fields
}

Tool for deduplicating and caching expensive work. All methods are safe for concurrent use. The first type parameter is used to determine expiration duration, and should typically be a zero-sized stateless type, such as `DurSecond`, `DurMinute`, `DurHour` provided by this package. The given type `Tar` must implement `Initer` on its pointer type: `(*Tar).Init`. The init method is used to populate data whenever it's missing or expired. See methods `Mem.Get` and `Mem.Peek`. A zero value of `Mem` is ready for use. Contains a synchronization primitive and must not be copied.

Usage example:

type Model struct { Id string }

type DatModels []Model

// Pretend that this is expensive.
func (self *DatModels) Init() { *self = DatModels{{10}, {20}, {30}} }

type Dat struct {
	Models gg.Mem[gg.DurHour, DatModels, *DatModels]
	// ... other caches
}

var dat Dat

func init() { fmt.Println(dat.Models.Get()) }

func (*Mem[_, _, _]) Clear added in v0.0.2

func (self *Mem[_, _, _]) Clear()

Clears the inner value and timestamp.

func (*Mem[Dur, _, _]) Duration added in v0.1.9

func (*Mem[Dur, _, _]) Duration() time.Duration

Implement `Durationer`. Shortcut for `Zero[Dur]().Duration()` using the first type parameter provided to this type. For internal use.

func (*Mem[_, Tar, _]) Get added in v0.0.3

func (self *Mem[_, Tar, _]) Get() Tar

Returns the inner value after ensuring it's initialized and not expired. If the data is missing or expired, it's initialized by calling `(*Tar).Init`. Otherwise the data is returned as-is.

This method avoids redundant concurrent work. When called concurrently by multiple goroutines, only 1 goroutine performs work, while the others simply wait for it.

Expiration is determined by consulting the `Dur` type provided to `Mem` as its first type parameter, calling `Dur.Duration` on a zero value.

Method `(*Tar).Init` is always called on a new pointer to a zero value, for multiple reasons. If `(*Tar).Init` appends data to the target instead of replacing it, this avoids accumulating redundant data and leaking memory. Additionally, this avoids the possibility of concurrent modification (between `Mem` and its callers) that could lead to observing an inconsistent state of the data.

Compare `Mem.Peek` which does not perform initialization.

func (*Mem[_, _, _]) MarshalJSON added in v0.1.4

func (self *Mem[_, _, _]) MarshalJSON() ([]byte, error)

Implement `json.Marshaler` by proxying to `Timed.MarshalJSON` on the inner instance of `.Timed`. Like other methods, this is safe for concurrent use.

func (*Mem[_, Tar, _]) Peek added in v0.1.9

func (self *Mem[_, Tar, _]) Peek() Tar

Similar to `Mem.Get` but returns the inner value as-is, without performing initialization.

func (*Mem[_, Tar, _]) PeekTimed added in v0.1.9

func (self *Mem[_, Tar, _]) PeekTimed() Timed[Tar]

Similar to `Mem.Timed` but returns inner `Timed` as-is, without performing initialization. The result contains the current state of the data, and the timestamp at which the value was last set. If the data has not been initialized or set, the timestamp is zero.

func (*Mem[_, Tar, Ptr]) Timed added in v0.1.4

func (self *Mem[_, Tar, Ptr]) Timed() Timed[Tar]

Same as `Mem.Get` but returns `Timed` which contains both the inner value and the timestamp at which it was generated or set.

func (*Mem[_, _, _]) UnmarshalJSON added in v0.1.4

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

Implement `json.Unmarshaler` by proxying to `Timed.UnmarshalJSON` on the inner instance of `.Timed`. Like other methods, this is safe for concurrent use.

type Nexter added in v0.0.2

type Nexter interface{ Next() bool }

Used by various "iterator" types such as `sql.Rows`.

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
	Getter[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]) AppendTo added in v0.1.6

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

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

func (*Opt[_]) Clear

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

Implement `Clearer`. Zeroes the receiver.

func (Opt[A]) Get

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

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

func (Opt[_]) IsNotNull added in v0.1.6

func (self Opt[_]) IsNotNull() bool

Inverse of `.IsNull`.

func (Opt[_]) IsNull

func (self Opt[_]) 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]) Ptr added in v0.0.3

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

Implement `Ptrer`, returning a pointer to 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`, delegates to that implementation. Otherwise input must be nil or text-like (see `Text`). Text decoding uses the same logic as `.Parse`.

func (*Opt[A]) Set added in v0.0.3

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

Implement `Setter`. Modifies the underlying value and sets `.Ok = true`. The resulting state 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 `JsonDecodeCatch` 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 as-is.

type OrdMap added in v0.1.19

type OrdMap[Key comparable, Val any] struct {
	Slice []Val `role:"ref"`
	Index map[Key]int
}

Represents an ordered map. Compare `OrdSet` which has only values, not key-value pairs. Compare `Coll` which is an ordered map where each value determines its own key.

This implementation is specialized for easy and efficient appending, iteration, and membership testing, but as a tradeoff, it does not support deletion. For "proper" ordered sets that support deletion, see the library https://github.com/mitranim/gord.

Known limitations:

  • Lack of support for JSON encoding and decoding. An implementation using Go maps would be easy but incorrect: element positions would be randomized.

func (*OrdMap[Key, Val]) Add added in v0.1.19

func (self *OrdMap[Key, Val]) Add(key Key, val Val) *OrdMap[Key, Val]

Same as `OrdMap.Set`, but panics if the key was already present in the index.

func (*OrdMap[Key, Val]) Clear added in v0.1.19

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

Nullifies both the slice and the index. Does not preserve their capacity.

func (OrdMap[Key, Val]) Get added in v0.1.19

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

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

func (OrdMap[Key, Val]) GetReq added in v0.1.19

func (self OrdMap[Key, Val]) GetReq(key Key) Val

Short for "get required". Returns the value indexed on the given key. Panics if the value is missing.

func (OrdMap[Key, Val]) Got added in v0.1.19

func (self OrdMap[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 (OrdMap[Key, _]) Has added in v0.1.19

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

True if the index has the given key.

func (OrdMap[_, _]) IsEmpty added in v0.1.19

func (self OrdMap[_, _]) IsEmpty() bool

True if `.Len` <= 0. Inverse of `.IsNotEmpty`.

func (OrdMap[_, _]) IsNotEmpty added in v0.1.19

func (self OrdMap[_, _]) IsNotEmpty() bool

True if `.Len` > 0. Inverse of `.IsEmpty`.

func (OrdMap[_, _]) Len added in v0.1.19

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

Same as `len(self.Slice)`.

func (OrdMap[Key, Val]) Ptr added in v0.1.19

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

Short for "pointer". Returns a pointer to the value indexed on the given key, or nil if the value is missing. Because this type does not support deletion, the correspondence of positions in `.Slice` and indexes in `.Index` does not change when adding or replacing values. The pointer should remain valid for the lifetime of the ordered map, unless `.Slice` is directly mutated by external means.

func (OrdMap[Key, Val]) PtrReq added in v0.1.19

func (self OrdMap[Key, Val]) PtrReq(key Key) *Val

Short for "pointer required". Returns a non-nil pointer to the value indexed on the given key, or panics if the value is missing.

func (*OrdMap[Key, Val]) Set added in v0.1.19

func (self *OrdMap[Key, Val]) Set(key Key, val Val) *OrdMap[Key, Val]

Idempotently adds or replaces the given value, updating both the inner slice and the inner index. If the key was already registered in the map, the new value replaces the old value at the same position in the inner slice.

type OrdSet added in v0.1.1

type OrdSet[Val comparable] struct {
	Slice []Val `role:"ref"`
	Index Set[Val]
}

Represents an ordered set. Compare `OrdMap` which represents an ordered map. This implementation is specialized for easy and efficient appending, iteration, and membership testing, but as a tradeoff, it does not support deletion. For "proper" ordered sets that support deletion, see the library https://github.com/mitranim/gord.

func OrdSetFrom added in v0.1.1

func OrdSetFrom[Slice ~[]Val, Val comparable](src ...Slice) OrdSet[Val]

Syntactic shortcut for making an `OrdSet` from any number of source slices, with type inference.

func OrdSetOf added in v0.1.1

func OrdSetOf[Val comparable](src ...Val) OrdSet[Val]

Syntactic shortcut for making an `OrdSet` of the given arguments, with type inference.

func (*OrdSet[Val]) Add added in v0.1.1

func (self *OrdSet[Val]) Add(src ...Val) *OrdSet[Val]

Idempotently adds each given value to both the inner slice and the inner index, skipping duplicates.

func (*OrdSet[Val]) Clear added in v0.1.1

func (self *OrdSet[Val]) Clear() *OrdSet[Val]

Nullifies both the slice and the index. Does not preserve their capacity.

func (OrdSet[Val]) Has added in v0.1.1

func (self OrdSet[Val]) Has(val Val) bool

True if the index has the given value. Ignores the inner slice.

func (OrdSet[_]) IsEmpty added in v0.1.1

func (self OrdSet[_]) IsEmpty() bool

True if `.Len` <= 0. Inverse of `.IsNotEmpty`.

func (OrdSet[_]) IsNotEmpty added in v0.1.6

func (self OrdSet[_]) IsNotEmpty() bool

True if `.Len` > 0. Inverse of `.IsEmpty`.

func (OrdSet[_]) Len added in v0.1.1

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

Same as `len(self.Slice)`.

func (OrdSet[_]) MarshalJSON added in v0.1.1

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

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

func (*OrdSet[Val]) Reindex added in v0.1.1

func (self *OrdSet[Val]) Reindex()

Rebuilds the inner index from the inner slice, without checking the validity of the existing index. Can be useful for external code that directly modifies the inner `.Slice`, for example by sorting it. This is NOT used when adding items via `.Add`, which modifies the index incrementally rather than all-at-once.

func (*OrdSet[Val]) Reset added in v0.1.18

func (self *OrdSet[Val]) Reset(src ...Val) *OrdSet[Val]

Replaces `.Slice` with the given slice and rebuilds `.Index`. Uses the slice as-is with no reallocation. Callers must be careful to avoid modifying the source data, which may invalidate the collection's index.

func (*OrdSet[_]) UnmarshalJSON added in v0.1.1

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

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

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 ParserPtr added in v0.0.15

type ParserPtr[A any] interface {
	*A
	Parser
}

type Peeker added in v0.1.9

type Peeker[A any] interface{ Peek() A }

Similar to `Getter`, but for types that may perform work in `.Get`, this must avoid that work and be very cheap to call. Used by `Mem`.

type Pker added in v0.1.3

type Pker[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 Ptrer added in v0.0.3

type Ptrer[A any] interface{ Ptr() *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. If the wrapper is nil, this should return nil.

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. Always returns non-nil, even if the input is empty.

func SetMapped

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

Creates a set by "mapping" the elements of a given slice via the provided function. Always returns non-nil, even if the input is empty.

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. Always returns non-nil, even if the input is empty.

func (Set[A]) Add

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

Idempotently adds the given values to the receiver, which must be non-nil.

func (Set[A]) AddFrom

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

Set union. Idempotently adds all values from the given source sets to the receiver, which must be non-nil.

func (Set[A]) Clear

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

Clears and returns the receiver, which may be nil. Note that this type is implemented as a map, and this method involves iterating the map, which is inefficient in Go. In many cases, it's more efficient to make a new set.

func (Set[A]) Del

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

Deletes the given values from the receiver, which may be nil.

func (Set[A]) DelFrom

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

Deletes all values present in the given source sets from the receiver, which may be nil.

func (Set[A]) Filter added in v0.0.7

func (self Set[A]) Filter(fun func(A) bool) []A

Returns the subset of values for which the given function returns true. Order is random. If function is nil, output is nil.

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

True if the set includes the given value. Nil-safe.

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[_]) IsEmpty added in v0.1.20

func (self Set[_]) IsEmpty() bool

Same as `len(self) <= 0`. Inverse of `.IsNotEmpty`.

func (Set[_]) IsNotEmpty added in v0.1.20

func (self Set[_]) IsNotEmpty() bool

Same as `len(self) > 0`. Inverse of `.IsEmpty`.

func (Set[_]) Len added in v0.0.19

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

Same as `len(set)`. Nil-safe.

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]

Combination of `Set.Clear` and `Set.Add`.

func (Set[A]) Slice

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

Converts the map to a slice of its values. 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 Setter added in v0.0.3

type Setter[A any] interface{ Set(A) }

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

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 Slice added in v0.0.5

type Slice[A any] []A

Typedef of an arbitrary slice with various methods that duplicate global slice functions such as `Get` or `Filter`. Useful as a shortcut for creating bound methods that can be passed to higher-order functions. Example:

values := []string{`one`, `two`, `three`}
indexes := []int{0, 2}
result := Map(indexes, SliceOf(values...).Get)
fmt.Println(grepr.String(result))
// []string{`one`, `three`}
Example
package main

import (
	"fmt"

	"github.com/mitranim/gg"
)

func main() {
	values := []string{`one`, `two`, `three`}
	indexes := []int{0, 2}
	result := gg.Map(indexes, gg.SliceOf(values...).Get)

	fmt.Println(gg.GoString(result))

}
Output:

[]string{"one", "three"}

func SliceFrom added in v0.1.6

func SliceFrom[Src ~[]Elem, Elem any](src ...Src) Slice[Elem]

Shortcut for converting an arbitrary number of slices to `Slice[Elem]`. When called with exactly one argument, this performs a free type conversion without an allocation. When called with 2 or more arguments, this concatenates the inputs, allocating a new slice.

func SliceOf

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

Syntactic shortcut for making `Slice[A]` out of the given values. Can also be used to perform a free type conversion from an existing slice, with no allocation. Also see `ToSlice` which returns `[]A` rather than `Slice[A]`.

func (*Slice[A]) Append added in v0.1.6

func (self *Slice[A]) Append(val ...A)

Same as global `Append`.

func (*Slice[A]) AppendIndex added in v0.1.1

func (self *Slice[A]) AppendIndex(val A) int

Same as global `AppendIndex`.

func (*Slice[A]) AppendPtr added in v0.0.5

func (self *Slice[A]) AppendPtr(val A) *A

Same as global `AppendPtr`.

func (*Slice[A]) AppendPtrZero added in v0.0.5

func (self *Slice[A]) AppendPtrZero() *A

Same as global `AppendPtrZero`.

func (Slice[_]) Cap added in v0.0.5

func (self Slice[_]) Cap() int

Same as global `Cap`.

func (Slice[_]) CapMissing added in v0.0.5

func (self Slice[_]) CapMissing(size int) int

Same as global `CapMissing`.

func (Slice[_]) CapUnused added in v0.0.5

func (self Slice[_]) CapUnused() int

Same as global `CapUnused`.

func (Slice[A]) Clone added in v0.0.5

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

Same as global `Clone`.

func (Slice[A]) CloneAppend added in v0.0.5

func (self Slice[A]) CloneAppend(val ...A) Slice[A]

Same as global `CloneAppend`.

func (Slice[A]) Compact added in v0.0.5

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

Same as global `Compact`.

func (Slice[A]) Count added in v0.0.5

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

Same as global `Count`.

func (Slice[A]) Drop added in v0.0.5

func (self Slice[A]) Drop(size int) Slice[A]

Same as global `Drop`.

func (Slice[A]) DropLastWhile added in v0.1.20

func (self Slice[A]) DropLastWhile(fun func(A) bool) Slice[A]

Same as global `DropLastWhile`.

func (Slice[A]) DropWhile added in v0.0.5

func (self Slice[A]) DropWhile(fun func(A) bool) Slice[A]

Same as global `DropWhile`.

func (Slice[A]) Each added in v0.0.5

func (self Slice[A]) Each(val Slice[A], fun func(A))

Same as global `Each`.

func (Slice[A]) EachPtr added in v0.0.5

func (self Slice[A]) EachPtr(fun func(*A))

Same as global `EachPtr`.

func (Slice[A]) Every added in v0.0.5

func (self Slice[A]) Every(fun func(A) bool) bool

Same as global `Every`.

func (Slice[A]) Filter added in v0.0.5

func (self Slice[A]) Filter(fun func(A) bool) Slice[A]

Same as global `Filter`.

func (*Slice[A]) FilterAppend added in v0.0.5

func (self *Slice[A]) FilterAppend(src []A, fun func(A) bool)

Same as global `FilterAppend`.

func (Slice[A]) FilterIndex added in v0.0.5

func (self Slice[A]) FilterIndex(fun func(A) bool) []int

Same as global `FilterIndex`.

func (Slice[A]) Find added in v0.0.5

func (self Slice[A]) Find(fun func(A) bool) A

Same as global `Find`.

func (Slice[A]) FindIndex added in v0.0.5

func (self Slice[A]) FindIndex(fun func(A) bool) int

Same as global `FindIndex`.

func (Slice[A]) FindLast added in v0.1.20

func (self Slice[A]) FindLast(fun func(A) bool) A

Same as global `FindLast`.

func (Slice[A]) FindLastIndex added in v0.1.20

func (self Slice[A]) FindLastIndex(fun func(A) bool) int

Same as global `FindLastIndex`.

func (Slice[A]) Found added in v0.0.5

func (self Slice[A]) Found(fun func(A) bool) (A, bool)

Same as global `Found`.

func (Slice[A]) FoundLast added in v0.1.20

func (self Slice[A]) FoundLast(fun func(A) bool) (A, bool)

Same as global `FoundLast`.

func (Slice[A]) Get added in v0.0.5

func (self Slice[A]) Get(ind int) A

Same as global `Get`.

func (Slice[A]) GetPtr added in v0.0.5

func (self Slice[A]) GetPtr(ind int) *A

Same as global `GetPtr`.

func (Slice[A]) GetStrict added in v0.1.22

func (self Slice[A]) GetStrict(ind int) A

Same as global `GetStrict`.

func (Slice[A]) Got added in v0.0.5

func (self Slice[A]) Got(ind int) (A, bool)

Same as global `Got`.

func (Slice[A]) GrowCap added in v0.0.5

func (self Slice[A]) GrowCap(size int) Slice[A]

Same as global `GrowCap`.

func (Slice[A]) GrowCapExact added in v0.0.5

func (self Slice[A]) GrowCapExact(size int) Slice[A]

Same as global `GrowCapExact`.

func (Slice[A]) GrowLen added in v0.0.5

func (self Slice[A]) GrowLen(size int) Slice[A]

Same as global `GrowLen`.

func (Slice[A]) HasEqual added in v0.1.1

func (self Slice[A]) HasEqual(val A) bool

Same as global `HasEqual`.

func (Slice[A]) Head added in v0.0.5

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

Same as global `Head`.

func (Slice[A]) HeadPtr added in v0.0.5

func (self Slice[A]) HeadPtr() *A

Same as global `HeadPtr`.

func (Slice[A]) Init added in v0.0.5

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

Same as global `Init`.

func (Slice[_]) IsEmpty added in v0.0.5

func (self Slice[_]) IsEmpty() bool

Same as global `IsEmpty`.

func (Slice[_]) IsNotEmpty added in v0.1.6

func (self Slice[_]) IsNotEmpty() bool

Same as global `IsNotEmpty`.

func (Slice[A]) Last added in v0.0.5

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

Same as global `Last`.

func (Slice[A]) LastIndex added in v0.0.5

func (self Slice[A]) LastIndex() int

Same as global `LastIndex`.

func (Slice[A]) LastPtr added in v0.0.5

func (self Slice[A]) LastPtr() *A

Same as global `LastPtr`.

func (Slice[_]) Len added in v0.0.5

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

Same as global `Len`.

func (Slice[A]) MapMut added in v0.0.5

func (self Slice[A]) MapMut(fun func(A) A) Slice[A]

Same as global `MapMut`.

func (Slice[A]) None added in v0.0.5

func (self Slice[A]) None(fun func(A) bool) bool

Same as global `None`.

func (Slice[A]) NotZeroIndex added in v0.1.6

func (self Slice[A]) NotZeroIndex() []int

Same as global `NotZeroIndex`.

func (Slice[A]) Plain added in v0.1.22

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

Free cast from a typedef to a plain slice.

func (*Slice[A]) PopHead added in v0.0.13

func (self *Slice[A]) PopHead() A

Same as global `PopHead`.

func (*Slice[A]) PopLast added in v0.0.13

func (self *Slice[A]) PopLast() A

Same as global `PopLast`.

func (*Slice[_]) PtrLen added in v0.0.7

func (self *Slice[_]) PtrLen() int

Same as global `PtrLen`.

func (Slice[A]) Reject added in v0.0.5

func (self Slice[A]) Reject(fun func(A) bool) Slice[A]

Same as global `Reject`.

func (*Slice[A]) RejectAppend added in v0.0.5

func (self *Slice[A]) RejectAppend(src []A, fun func(A) bool)

Same as global `RejectAppend`.

func (Slice[_]) Reverse added in v0.0.5

func (self Slice[_]) Reverse()

Same as global `Reverse`.

func (Slice[A]) Reversed added in v0.0.5

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

Same as global `Reversed`.

func (Slice[A]) Set added in v0.0.5

func (self Slice[A]) Set(ind int, val A)

Sets a value at an index, same as by using the built-in square bracket syntax. Useful as a shortcut for inline bound functions.

func (Slice[A]) Some added in v0.0.5

func (self Slice[A]) Some(fun func(A) bool) bool

Same as global `Some`.

func (Slice[A]) Swap added in v0.1.1

func (self Slice[A]) Swap(one, two int)

Same as global `Swap`.

func (Slice[A]) Tail added in v0.0.5

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

Same as global `Tail`.

func (Slice[A]) Take added in v0.0.5

func (self Slice[A]) Take(size int) Slice[A]

Same as global `Take`.

func (Slice[A]) TakeLastWhile added in v0.1.20

func (self Slice[A]) TakeLastWhile(fun func(A) bool) Slice[A]

Same as global `TakeLastWhile`.

func (Slice[A]) TakeWhile added in v0.0.5

func (self Slice[A]) TakeWhile(fun func(A) bool) Slice[A]

Same as global `TakeWhile`.

func (*Slice[A]) TimesAppend added in v0.0.5

func (self *Slice[A]) TimesAppend(src int, fun func(int) A)

Same as global `TimesAppend`.

func (*Slice[_]) Trunc added in v0.0.5

func (self *Slice[_]) Trunc()

Same as global `Trunc`.

func (Slice[A]) TruncLen added in v0.0.19

func (self Slice[A]) TruncLen(size int) Slice[A]

Same as global `TruncLen`.

func (Slice[_]) Zero added in v0.0.5

func (self Slice[_]) Zero()

Same as global `SliceZero`.

func (Slice[A]) ZeroIndex added in v0.0.5

func (self Slice[A]) ZeroIndex() []int

Same as global `ZeroIndex`.

type SliceHeader

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

Memory representation of an arbitrary Go slice. Same as `reflect.SliceHeader` but with `unsafe.Pointer` instead of `uintptr`.

func SliceHeaderOf added in v0.1.6

func SliceHeaderOf[A any](src []A) SliceHeader

Takes a regular slice header and converts it to its underlying representation `SliceHeader`.

type SliceSnapshot added in v0.0.13

type SliceSnapshot[Slice ~[]Elem, Elem any] struct {
	Ptr *Slice
	Len int
}

Analogous to `Snapshot`, but instead of storing a value, stores a length. When done, reverts the referenced slice to the given length.

func SnapSlice added in v0.0.7

func SnapSlice[Slice ~[]Elem, Elem any](ptr *Slice) SliceSnapshot[Slice, Elem]

Snapshots the length of the given slice and returns a snapshot that can restore the previous length. Usage:

defer SnapSlice(&somePtr).Done()

func (SliceSnapshot[_, _]) Done added in v0.0.13

func (self SliceSnapshot[_, _]) Done()

Analogous to `Snapshot.Done`. Reverts the referenced slice to `self.Len` while keeping the capacity.

type Snapshot added in v0.0.13

type Snapshot[A any] struct {
	Ptr *A
	Val A
}

Short for "snapshot". Used by `SnapSwap`.

func Snap added in v0.0.2

func Snap[A any](ptr *A) Snapshot[A]

Snapshots the current value at the given pointer and returns a snapshot that can restore this value. Usage:

defer Snap(&somePtr).Done()
somePtr.SomeField = someValue

func SnapSwap added in v0.1.15

func SnapSwap[A any](ptr *A, next A) Snapshot[A]

Snapshots the previous value, sets the next value, and returns a snapshot that can restore the previous value. Usage:

defer SnapSwap(&somePtr, someVal).Done()

func (Snapshot[_]) Done added in v0.0.13

func (self Snapshot[_]) Done()

If the pointer is non-nil, writes the value to it. See `SnapSwap`.

type Sortable

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

Slice of non-primitives that implements `sort.Interface`.

func (Sortable[_]) Len

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

Implement `sort.Interface`.

func (Sortable[_]) Less

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

Implement `sort.Interface`.

func (Sortable[_]) Sort

func (self Sortable[_]) Sort()

Sorts the receiver, mutating it.

func (Sortable[A]) Sorted

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

Sorts the receiver, mutating and returning it.

func (Sortable[_]) Swap

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

Implement `sort.Interface`.

type SortablePrim

type SortablePrim[A LesserPrim] []A

Slice of primitives that implements `sort.Interface`.

func (SortablePrim[_]) Len

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

Implement `sort.Interface`.

func (SortablePrim[_]) Less

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

Implement `sort.Interface`.

func (SortablePrim[_]) Sort

func (self SortablePrim[_]) Sort()

Sorts the receiver, mutating it.

func (SortablePrim[A]) Sorted

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

Sorts the receiver, mutating and returning it.

func (SortablePrim[_]) Swap

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

Implement `sort.Interface`.

type StackAppenderTo added in v0.1.18

type StackAppenderTo interface{ AppendStackTo([]byte) []byte }

Appends a text representation of a stack trace to the given buffer, returning the modified buffer. Implemented by `Err` and used internally in error formatting.

type StackTraced

type StackTraced interface{ StackTrace() []uintptr }

Implemented by the `Err` type. Used by `ErrTrace` to retrieve stack traces from arbitrary error types. This interface is also implemented by trace-enabled errors in "github.com/pkg/errors".

type StringReadCloser

type StringReadCloser struct{ strings.Reader }

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

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 StructDeepPublicFields added in v0.0.7

type StructDeepPublicFields []r.StructField

Used by `StructDeepPublicFieldCache`.

func (*StructDeepPublicFields) Init added in v0.0.7

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

Implement an interface used by `TypeCache`.

type StructFields

type StructFields []r.StructField

func (*StructFields) Init

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

type StructPublicFields added in v0.0.2

type StructPublicFields []r.StructField

func (*StructPublicFields) Init added in v0.0.2

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

type SyncMap added in v0.0.5

type SyncMap[Key comparable, Val any] sync.Map

Typed version of `sync.Map`. Currently implemented as a typedef of `sync.Map` where both keys and valus are internally stored as `any`. Converting non-interface values to `any` may automatically create a copy on the heap. Values other than booleans and machine numbers should be stored by pointer to minimize copying. This may change in the future.

func (*SyncMap[Key, Val]) Delete added in v0.0.5

func (self *SyncMap[Key, Val]) Delete(key Key)

Typed version of `sync.Map.Delete`.

func (*SyncMap[Key, Val]) Load added in v0.0.5

func (self *SyncMap[Key, Val]) Load(key Key) (Val, bool)

Typed version of `sync.Map.Load`.

func (*SyncMap[Key, Val]) LoadAndDelete added in v0.0.5

func (self *SyncMap[Key, Val]) LoadAndDelete(key Key) (Val, bool)

Typed version of `sync.Map.LoadAndDelete`.

func (*SyncMap[Key, Val]) LoadOrStore added in v0.0.5

func (self *SyncMap[Key, Val]) LoadOrStore(key Key, val Val) (Val, bool)

Typed version of `sync.Map.LoadOrStore`.

func (*SyncMap[Key, Val]) Range added in v0.0.5

func (self *SyncMap[Key, Val]) Range(fun func(Key, Val) bool)

Typed version of `sync.Map.Range`.

func (*SyncMap[Key, Val]) Store added in v0.0.5

func (self *SyncMap[Key, Val]) Store(key Key, val Val) Val

Typed version of `sync.Map.Store`.

type Text

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

Describes text types: strings and byte slices. All types compatible with this interface can be freely cast to `[]byte` via `ToBytes` and to `string` via `ToString`, subject to safety gotchas described in those functions' comments.

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 TimeMicro added in v0.0.10

type TimeMicro int64

Represents a Unix timestamp in microseconds. In text and JSON, this type supports parsing numeric timestamps and RFC3339 timestamps, but always encodes as a number. In SQL, this type is represented in the RFC3339 format. This type is "zero-optional" or "zero-nullable". The zero value is considered empty in text and null in JSON/SQL. Conversion to `time.Time` doesn't specify a timezone, which means it uses `time.Local` by default. If you prefer UTC, enforce it across the app by updating `time.Local`.

Caution: corresponding DB columns MUST be restricted to microsecond precision. Without this restriction, encoding and decoding is not reversible. After losing precision to an encoding-decoding roundtrip, you might be unable to find a corresponding value in a database, if timestamp precision is higher than a microsecond.

Also see `TimeMilli`, which uses milliseconds.

func TimeMicroNow added in v0.0.10

func TimeMicroNow() TimeMicro

Calls `time.Now` and converts to `TimeMicro`, truncating precision.

func TimeMicroParse added in v0.0.10

func TimeMicroParse[A Text](src A) TimeMicro

Shortcut for parsing text into `TimeMicro`. Panics on error.

func (TimeMicro) AppendTo added in v0.1.6

func (self TimeMicro) AppendTo(buf []byte) []byte

Implement `AppenderTo`, using the same representation as `.String`.

func (*TimeMicro) Clear added in v0.0.10

func (self *TimeMicro) Clear()

Implement `Clearer`, zeroing the receiver.

func (TimeMicro) Get added in v0.0.10

func (self TimeMicro) Get() any

Implement `AnyGetter` for compatibility with some 3rd party libraries. If zero, returns `nil`, otherwise creates `time.Time` by calling `TimeMicro.Time`.

func (TimeMicro) IsNull added in v0.0.10

func (self TimeMicro) IsNull() bool

Implement `Nullable`. True if zero.

func (TimeMicro) MarshalJSON added in v0.0.10

func (self TimeMicro) MarshalJSON() ([]byte, error)

Implement `json.Marshaler`. If zero, returns bytes representing `null`. Otherwise encodes as a JSON number.

func (TimeMicro) MarshalText added in v0.0.10

func (self TimeMicro) MarshalText() ([]byte, error)

Implement `encoding.TextMarhaler`. If zero, returns nil. Otherwise returns the same representation as `.String`.

func (*TimeMicro) Parse added in v0.0.10

func (self *TimeMicro) Parse(src string) error

Implement `Parser`. The input must be either an integer in base 10, representing a Unix millisecond timestamp, or an RFC3339 timestamp. RFC3339 is the default time encoding/decoding format in Go and some other languages.

func (*TimeMicro) Scan added in v0.0.10

func (self *TimeMicro) Scan(src any) error

Implement `sql.Scanner`, converting an arbitrary input to `TimeMicro` and modifying the receiver. Acceptable inputs:

  • `nil` -> use `.Clear`
  • integer -> assign, assuming milliseconds
  • text -> use `.Parse`
  • `time.Time` -> use `.SetTime`
  • `*time.Time` -> use `.Clear` or `.SetTime`
  • `AnyGetter` -> scan underlying value

func (*TimeMicro) SetInt64 added in v0.0.10

func (self *TimeMicro) SetInt64(val int64)

Sets the receiver to the given input.

func (*TimeMicro) SetTime added in v0.0.10

func (self *TimeMicro) SetTime(val time.Time)

Sets the receiver to the result of `time.Time.UnixMicro`.

func (TimeMicro) String added in v0.0.10

func (self TimeMicro) String() string

Implement `fmt.Stringer`. If zero, returns an empty string. Otherwise returns the base 10 representation of the underlying number.

func (TimeMicro) Time added in v0.0.10

func (self TimeMicro) Time() time.Time

Convert to `time.Time` by calling `time.UnixMicro`. The resulting timestamp has the timezone `time.Local`. To enforce UTC, modify `time.Local` at app startup, or call `.In(time.UTC)`.

func (*TimeMicro) UnmarshalJSON added in v0.0.10

func (self *TimeMicro) UnmarshalJSON(src []byte) error

Implement `json.Unmarshaler`. If the input is empty or represents JSON `null`, zeroes the receiver. If the input is a JSON number, parses it in accordance with `.Parse`. Otherwise uses the default `json.Unmarshal` behavior for `*time.Time` and stores the resulting timestamp in milliseconds.

func (*TimeMicro) UnmarshalText added in v0.0.10

func (self *TimeMicro) UnmarshalText(src []byte) error

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

func (TimeMicro) Value added in v0.0.10

func (self TimeMicro) Value() (driver.Value, error)

Implement `driver.Valuer`, using `.Get`.

type TimeMilli added in v0.0.10

type TimeMilli int64

Represents a Unix timestamp in milliseconds. In text and JSON, this type supports parsing numeric timestamps and RFC3339 timestamps, but always encodes as a number. In SQL, this type is represented in the RFC3339 format. This type is "zero-optional" or "zero-nullable". The zero value is considered empty in text and null in JSON/SQL. Conversion to `time.Time` doesn't specify a timezone, which means it uses `time.Local` by default. If you prefer UTC, enforce it across the app by updating `time.Local`.

Caution: corresponding DB columns MUST be restricted to millisecond precision. Without this restriction, encoding and decoding might not be reversible. After losing precision to an encoding-decoding roundtrip, you might be unable to find a corresponding value in a database, if timestamp precision is higher than a millisecond.

Also see `TimeMicro`, which uses microseconds.

func TimeMilliNow added in v0.0.10

func TimeMilliNow() TimeMilli

Calls `time.Now` and converts to `TimeMilli`, truncating precision.

func TimeMilliParse added in v0.0.10

func TimeMilliParse[A Text](src A) TimeMilli

Shortcut for parsing text into `TimeMilli`. Panics on error.

func (TimeMilli) AppendTo added in v0.1.6

func (self TimeMilli) AppendTo(buf []byte) []byte

Implement `AppenderTo`, using the same representation as `.String`.

func (*TimeMilli) Clear added in v0.0.10

func (self *TimeMilli) Clear()

Implement `Clearer`, zeroing the receiver.

func (TimeMilli) Get added in v0.0.10

func (self TimeMilli) Get() any

Implement `AnyGetter` for compatibility with some 3rd party libraries. If zero, returns `nil`, otherwise creates `time.Time` by calling `TimeMilli.Time`.

func (TimeMilli) IsNull added in v0.0.10

func (self TimeMilli) IsNull() bool

Implement `Nullable`. True if zero.

func (TimeMilli) MarshalJSON added in v0.0.10

func (self TimeMilli) MarshalJSON() ([]byte, error)

Implement `json.Marshaler`. If zero, returns bytes representing `null`. Otherwise encodes as a JSON number.

func (TimeMilli) MarshalText added in v0.0.10

func (self TimeMilli) MarshalText() ([]byte, error)

Implement `encoding.TextMarhaler`. If zero, returns nil. Otherwise returns the same representation as `.String`.

func (*TimeMilli) Parse added in v0.0.10

func (self *TimeMilli) Parse(src string) error

Implement `Parser`. The input must be either an integer in base 10, representing a Unix millisecond timestamp, or an RFC3339 timestamp. RFC3339 is the default time encoding/decoding format in Go and some other languages.

func (*TimeMilli) Scan added in v0.0.10

func (self *TimeMilli) Scan(src any) error

Implement `sql.Scanner`, converting an arbitrary input to `TimeMilli` and modifying the receiver. Acceptable inputs:

  • `nil` -> use `.Clear`
  • integer -> assign, assuming milliseconds
  • text -> use `.Parse`
  • `time.Time` -> use `.SetTime`
  • `*time.Time` -> use `.Clear` or `.SetTime`
  • `AnyGetter` -> scan underlying value

func (*TimeMilli) SetInt64 added in v0.0.10

func (self *TimeMilli) SetInt64(val int64)

Sets the receiver to the given input.

func (*TimeMilli) SetTime added in v0.0.10

func (self *TimeMilli) SetTime(val time.Time)

Sets the receiver to the result of `time.Time.UnixMilli`.

func (TimeMilli) String added in v0.0.10

func (self TimeMilli) String() string

Implement `fmt.Stringer`. If zero, returns an empty string. Otherwise returns the base 10 representation of the underlying number.

func (TimeMilli) Time added in v0.0.10

func (self TimeMilli) Time() time.Time

Convert to `time.Time` by calling `time.UnixMilli`. The resulting timestamp has the timezone `time.Local`. To enforce UTC, modify `time.Local` at app startup, or call `.In(time.UTC)`.

func (*TimeMilli) UnmarshalJSON added in v0.0.10

func (self *TimeMilli) UnmarshalJSON(src []byte) error

Implement `json.Unmarshaler`. If the input is empty or represents JSON `null`, zeroes the receiver. If the input is a JSON number, parses it in accordance with `.Parse`. Otherwise uses the default `json.Unmarshal` behavior for `*time.Time` and stores the resulting timestamp in milliseconds.

func (*TimeMilli) UnmarshalText added in v0.0.10

func (self *TimeMilli) UnmarshalText(src []byte) error

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

func (TimeMilli) Value added in v0.0.10

func (self TimeMilli) Value() (driver.Value, error)

Implement `driver.Valuer`, using `.Get`.

type Timed added in v0.0.2

type Timed[A any] struct {
	Val  A `role:"ref"`
	Inst time.Time
}

Describes an arbitrary value with a timestamp. The timestamp indicates when the value was obtained. In JSON encoding and decoding, acts as a transparent proxy/reference/pointer to the inner value.

func TimedVal added in v0.0.2

func TimedVal[A any](val A) (out Timed[A])

Shortcut for creating a `Timed` with the given value, using the current timestamp.

func (*Timed[_]) Clear added in v0.0.2

func (self *Timed[_]) Clear()

Implement `Clearer`. Zeroes the receiver.

func (Timed[A]) Get added in v0.0.2

func (self Timed[A]) Get() A

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

func (Timed[_]) IsExpired added in v0.0.2

func (self Timed[_]) IsExpired(dur time.Duration) bool

True if the timestamp is unset, or if timestamp + duration > now.

func (Timed[_]) IsLive added in v0.0.2

func (self Timed[_]) IsLive(dur time.Duration) bool

Inverse of `.IsExpired`.

func (Timed[_]) IsNotNull added in v0.1.6

func (self Timed[_]) IsNotNull() bool

Inverse of `.IsNull`.

func (Timed[_]) IsNull added in v0.0.2

func (self Timed[_]) IsNull() bool

True if timestamp is unset.

func (Timed[A]) MarshalJSON added in v0.0.2

func (self Timed[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 (*Timed[A]) Ptr added in v0.0.3

func (self *Timed[A]) Ptr() *A

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

func (*Timed[A]) Set added in v0.0.3

func (self *Timed[A]) Set(val A)

Implement `Setter`. Modifies the underlying value and sets the current timestamp. The resulting state is considered non-null even if the value is "zero".

func (*Timed[_]) UnmarshalJSON added in v0.0.2

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

Implement `json.Unmarshaler`. If the input is empty or represents JSON null, clears the receiver via `.Clear`. Otherwise uses `JsonDecodeCatch` to decode into the underlying value, and sets the current timestamp on success.

type Trace

type Trace []Caller

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

func AnyTrace

func AnyTrace(val any) Trace

Same as `AnyTraceAt(val, 1)`.

func AnyTraceAt added in v0.1.0

func AnyTraceAt(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 `any` values returned by `recover`. The given value is used only as a possible trace carrier, and its other properties are ignored. Also see `ErrTrace` which is similar but does not capture a new trace.

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. Uses the `StackTraced` interface to detect the trace; the interface is implemented by the type `Err` provided by this library, and by trace-enabled errors in "github.com/pkg/errors". Does NOT generate a new trace. Also see `ErrStack` which returns a string that includes both the error message and the trace's representation, and `AnyTraceAt` which is suitable for use with `recover` and idempotently adds a trace if one is missing.

func ToTrace

func ToTrace[Slice ~[]Val, Val ~uintptr](src Slice) Trace

Free cast of `~[]~uintptr` to `Trace`.

func (Trace) AppendIndentMultiTo added in v0.1.18

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

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

func (Trace) AppendIndentTableTo added in v0.1.18

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

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

func (Trace) AppendIndentTo added in v0.1.18

func (self Trace) AppendIndentTo(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) AppendTo added in v0.1.6

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

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

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) IsEmpty added in v0.1.18

func (self Trace) IsEmpty() bool

True if there are no non-zero frames. Inverse of `Trace.IsNotEmpty`.

func (Trace) IsNotEmpty added in v0.1.6

func (self Trace) IsNotEmpty() bool

True if there are some non-zero frames. Inverse of `Trace.IsEmpty`.

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 `.AppendIndentTo`.

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 `.AppendIndentTo`.

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 Tup2 added in v0.0.5

type Tup2[A, B any] struct {
	A A
	B B
}

Represents a pseudo-tuple with two elements.

func Tuple2 added in v0.0.5

func Tuple2[A, B any](valA A, valB B) Tup2[A, B]

Shortcut for making a pseudo-tuple with two elements.

func (Tup2[A, B]) Get added in v0.0.5

func (self Tup2[A, B]) Get() (A, B)

Converts the pseudo-tuple to a proper Go tuple.

type Tup3 added in v0.0.5

type Tup3[A, B, C any] struct {
	A A
	B B
	C C
}

Represents a pseudo-tuple with three elements.

func Tuple3 added in v0.0.5

func Tuple3[A, B, C any](valA A, valB B, valC C) Tup3[A, B, C]

Shortcut for making a pseudo-tuple with three elements.

func (Tup3[A, B, C]) Get added in v0.0.5

func (self Tup3[A, B, C]) Get() (A, B, C)

Converts the pseudo-tuple to a proper Go tuple.

type TypeCache

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

Tool for storing information derived from `reflect.Type` that can be generated once and then cached. Used internally. All methods are concurrency-safe.

func TypeCacheOf

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

Type-inferring shortcut for creating a `TypeCache` of the given type.

func (*TypeCache[Val, Ptr]) Get

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

Shortcut for using `.Ptr` and dereferencing the result. May be invalid if the resulting value is non-copyable, for example when it contains a mutex.

func (*TypeCache[Val, Ptr]) Ptr added in v0.0.3

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

Returns the cached value for the given key. If the value did not previously exist, idempotently initializes it by calling `.Init` (by pointer) and caches the result. For any given key, the value is initialized exactly once, even if multiple goroutines are trying to access it simultaneously.

type Uint

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

Short for "unsigned integer".

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

Converts the first word to lowercase and each other word to Titlecase. Mutates and returns the receiver.

func (Words) Comma

func (self Words) Comma() string

Combines the words via ",".

func (Words) Dense added in v0.0.19

func (self Words) Dense() string

Combines the words via "".

func (Words) Join

func (self Words) Join(val string) string

Same as `strings.Join`.

func (Words) Kebab

func (self Words) Kebab() string

Combines the words via "-".

func (Words) Lower

func (self Words) Lower() Words

Converts each word to lowercase. Mutates and returns the receiver.

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) MapTail added in v0.0.21

func (self Words) MapTail(fun func(string) string) Words

Mutates the receiver by replacing elements, other than the first, with the results of the given function.

func (Words) Piped added in v0.1.15

func (self Words) Piped() string

Combines the words via "|".

func (Words) Sentence

func (self Words) Sentence() Words

Converts the first word to Titlecase and each other word to lowercase. Mutates and returns the receiver.

func (Words) Snake

func (self Words) Snake() string

Combines the words via "_".

func (Words) Spaced

func (self Words) Spaced() string

Combines the words via " ".

func (Words) Title

func (self Words) Title() Words

Converts each word to Titlecase. Mutates and returns the receiver.

func (Words) Upper

func (self Words) Upper() Words

Converts each word to UPPERCASE. Mutates and returns the receiver.

type Zeroable added in v0.0.3

type Zeroable interface{ IsZero() bool }

Implemented by some standard library types such as `time.Time` and `reflect.IsZero`. Our generic function `IsZero` automatically invokes this method on inputs that implement it.

type Zop

type Zop[A any] struct {
	/**
	Annotation `role:"ref"` indicates that this field is a reference/pointer to
	the inner type/value. Reflection-based code may use this to treat this type
	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 structs. This wrapper allows empty structs to become "null". This type doesn't implement any encoding or decoding methods other than for JSON, and is intended only for non-scalar values such as "models" / "data classes". Scalars tend to be compatible with ",omitempty" in JSON, and don't require such wrappers.

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". Syntactic shortcut for creating `Zop` with the given value. Workaround for the lack of type inference in struct literals.

func (*Zop[_]) Clear

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

Implement `Clearer`. Zeroes the receiver.

func (Zop[A]) Get

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

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

func (Zop[_]) IsNotNull added in v0.1.6

func (self Zop[_]) IsNotNull() bool

Inverse of `.IsNull`.

func (Zop[_]) IsNull

func (self Zop[_]) 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]) Ptr added in v0.0.3

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

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

func (*Zop[A]) Set added in v0.0.3

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

Implement `Setter`, modifying the underlying value.

func (*Zop[_]) UnmarshalJSON

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

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

Directories

Path Synopsis
Missing feature of the standard library: printing arbitrary inputs as Go code, with proper spacing and support for multi-line output with indentation.
Missing feature of the standard library: printing arbitrary inputs as Go code, with proper spacing and support for multi-line output with indentation.
Missing feature of the standard library: terse, expressive test assertions.
Missing feature of the standard library: terse, expressive test assertions.

Jump to

Keyboard shortcuts

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