Documentation ¶
Index ¶
- Constants
- Variables
- func Adjoin[Slice ~[]Elem, Elem comparable](tar Slice, src ...Elem) Slice
- func AnyAs[A any](src any) A
- func AnyErrTraced(val any) error
- func AnyIs[A any](src any) bool
- func AnyNoEscUnsafe(src any) any
- func AnyToString(src any) (string, bool)
- func AnyToText[A Text](src any) (A, bool)
- func Append[A ~[]byte, B any](buf A, src B) A
- func AppendCatch[A ~[]byte, B any](buf A, src B) (A, error)
- func AppendGoString[A any](inout []byte, val A) []byte
- func AppendNull[A any, B NullableValGetter[A]](buf []byte, src B) []byte
- func AppendPtr[Slice ~[]Elem, Elem any](tar *Slice, val Elem) *Elem
- func AppendPtrZero[Slice ~[]Elem, Elem any](tar *Slice) *Elem
- func AppendReflectCatch[A ~[]byte](buf A, val r.Value) (A, error)
- func AppendVals[Slice ~[]Elem, Elem any](tar *Slice, val ...Elem)
- func AppenderString[A Appender](val A) string
- func Cap[Slice ~[]Elem, Elem any](val Slice) int
- func CapMissing[Slice ~[]Elem, Elem any](src Slice, size int) int
- func CapUnused[Slice ~[]Elem, Elem any](src Slice) int
- func CastUnsafe[Out, Src any](val Src) Out
- func Catch(fun func()) (err error)
- func Catch01[A any](fun func() A) (val A, err error)
- func Catch10[A any](fun func(A), val A) (err error)
- func Catch11[A, B any](fun func(A) B, val0 A) (val1 B, err error)
- func CatchOnly(test func(error) bool, fun func()) (err error)
- func Caught(fun func()) bool
- func CaughtOnly(test func(error) bool, fun func()) bool
- func ChanInit[Tar ~chan Val, Val any](ptr *Tar) Tar
- func ChanInitCap[Tar ~chan Val, Val any](ptr *Tar, cap int) Tar
- func CharCount[A Text](val A) int
- func Clear[A any](val *A)
- func Cleared[A any](val *A) *A
- func Clone[Slice ~[]Elem, Elem any](src Slice) Slice
- func CloneAppend[Slice ~[]Elem, Elem any](src Slice, val ...Elem) Slice
- func CloneDeep[A any](src A) A
- func Close(val io.Closer)
- func Compact[Slice ~[]Elem, Elem any](src Slice) Slice
- func Conc(val ...func())
- func ConcCatch(val ...func()) []error
- func ConcEach[A any](src []A, fun func(A))
- func ConcEachCatch[A any](src []A, fun func(A)) []error
- func ConcMap[A, B any](src []A, fun func(A) B) []B
- func ConcMapCatch[A, B any](src []A, fun func(A) B) ([]B, []error)
- func ConcMapFunc[A, B any](out *[]B, src []A, fun func(A) B) func()
- func Concat[Slice ~[]Elem, Elem any](val ...Slice) Slice
- func Count[A any](src []A, fun func(A) bool) int
- func CtxGet[A any](ctx context.Context) A
- func CtxGot[A any](ctx context.Context) (A, bool)
- func CtxHas[A any](ctx context.Context) bool
- func CtxSet[A any](ctx context.Context, val A) context.Context
- func Cwd() string
- func Dec[A Num](val A) A
- func DetailOnlyf(test func(error) bool, pat string, val ...any)
- func Detailf(pat string, val ...any)
- func Drop[Slice ~[]Elem, Elem any](src Slice, size int) Slice
- func DropWhile[Slice ~[]Elem, Elem any](src Slice, fun func(Elem) bool) Slice
- func Each[Slice ~[]Elem, Elem any](val Slice, fun func(Elem))
- func Each2[A, B any](one []A, two []B, fun func(A, B))
- func EachPtr[Slice ~[]Elem, Elem any](val Slice, fun func(*Elem))
- func Eq[A comparable](one, two A) bool
- func EqNonZero[A comparable](one, two A) bool
- func Equal[A any](one, two A) bool
- func ErrAs[Tar any, Ptr interface{ ... }](src error) Tar
- func ErrConv(src any, typ r.Type) error
- func ErrFind(err error, fun func(error) bool) error
- func ErrOk[A Errer](val A)
- func ErrParse[A Text](err error, src A, typ r.Type) error
- func ErrSome(err error, fun func(error) bool) bool
- func ErrString(val error) string
- func ErrTraced(err error, skip int) error
- func Every[A any](src []A, fun func(A) bool) bool
- func EveryPair[A any](one, two []A, fun func(A, A) bool) bool
- func Exclude[Slice ~[]Elem, Elem comparable](base Slice, sub ...Elem) Slice
- func Fac[A Uint](src A) A
- func Fail(fun func(error))
- func Fellback[A any](tar *A, fallback A) bool
- func FieldDbName(val r.StructField) string
- func FieldJsonName(val r.StructField) string
- func Filter[Slice ~[]Elem, Elem any](src Slice, fun func(Elem) bool) (out Slice)
- func FilterAppend[Tar ~[]Elem, Elem any](tar *Tar, src []Elem, fun func(Elem) bool)
- func FilterIndex[Slice ~[]Elem, Elem any](src Slice, fun func(Elem) bool) []int
- func Finally(fun func(error))
- func Find[Slice ~[]Elem, Elem any](src Slice, fun func(Elem) bool) Elem
- func FindIndex[Slice ~[]Elem, Elem any](src Slice, fun func(Elem) bool) int
- func FlagHelp[A any]() string
- func FlagParse[A any](src []string, out *A)
- func FlagParseCatch[A any](src []string, out *A) (err error)
- func FlagParseReflect(src []string, out r.Value)
- func FlagParseTo[A any](src []string) (out A)
- func Fold[Acc, Val any](src []Val, acc Acc, fun func(Acc, Val) Acc) Acc
- func Fold1[A any](src []A, fun func(A, A) A) A
- func Foldz[Acc, Val any](src []Val, fun func(Acc, Val) Acc) Acc
- func ForkReadCloser(src io.ReadCloser) (_, _ io.ReadCloser)
- func ForkReader(src io.Reader) (_, _ io.Reader)
- func Found[Slice ~[]Elem, Elem any](src Slice, fun func(Elem) bool) (Elem, bool)
- func FuncName(val any) string
- func FuncNameBase(fun *rt.Func) string
- func FuncNameShort(name string) string
- func Get[A any](src []A, ind int) A
- func GetPtr[A any](src []A, ind int) *A
- func GoString[A any](val A) string
- func Got[A any](src []A, ind int) (A, bool)
- func Group[Slice ~[]Val, Key comparable, Val any](src Slice, fun func(Val) Key) map[Key][]Val
- func GroupInto[Key comparable, Val any](tar map[Key][]Val, src []Val, fun func(Val) Key)
- func GrowCap[Slice ~[]Elem, Elem any](src Slice, size int) Slice
- func GrowCapExact[Slice ~[]Elem, Elem any](src Slice, size int) Slice
- func GrowLen[Slice ~[]Elem, Elem any](src Slice, size int) Slice
- func Has[A comparable](src []A, val A) bool
- func HasEvery[A comparable](src, exp []A) bool
- func HasLen[Slice ~[]Elem, Elem any](val Slice) bool
- func HasNewlineSuffix[A Text](val A) bool
- func HasNone[A comparable](src, exp []A) bool
- func HasSome[A comparable](src, exp []A) bool
- func Head[Slice ~[]Elem, Elem any](val Slice) Elem
- func HeadPtr[Slice ~[]Elem, Elem any](val Slice) *Elem
- func Id1[A any](val A) A
- func Id2[A, B any](val0 A, val1 B) (A, B)
- func Id3[A, B, C any](val0 A, val1 B, val2 C) (A, B, C)
- func Inc[A Num](val A) A
- func Index[Slice ~[]Val, Key comparable, Val any](src Slice, fun func(Val) Key) map[Key]Val
- func IndexInto[Key comparable, Val any](tar map[Key]Val, src []Val, fun func(Val) Key)
- func IndexPair[Slice ~[]Elem, Elem any, Key comparable, Val any](src Slice, fun func(Elem) (Key, Val)) map[Key]Val
- func IndexPairInto[Elem any, Key comparable, Val any](tar map[Key]Val, src []Elem, fun func(Elem) (Key, Val))
- func Init[Slice ~[]Elem, Elem any](val Slice) Slice
- func Intersect[Slice ~[]Elem, Elem comparable](one, two Slice) Slice
- func IsEmpty[Slice ~[]Elem, Elem any](val Slice) bool
- func IsErrNil(val error) bool
- func IsErrNonNil(val error) bool
- func IsErrTraced(val error) bool
- func IsFieldEmbed(val r.StructField) bool
- func IsFieldIndirect(val r.StructField) bool
- func IsFieldPublic(val r.StructField) bool
- func IsFin[A Float](val A) bool
- func IsIndirect(typ r.Type) bool
- func IsJsonEmpty[A Text](val A) bool
- func IsNeg[A Signed](val A) bool
- func IsNonNull[A Nullable](val A) bool
- func IsNonZero[A any](val A) bool
- func IsNull[A Nullable](val A) bool
- func IsPos[A Signed](val A) bool
- func IsStrEmpty[A Text](val A) bool
- func IsStrNonEmpty[A Text](val A) bool
- func IsTypeBytes(typ r.Type) bool
- func IsValueBytes(val r.Value) bool
- func IsZero[A any](val A) bool
- func Iter(size int) []struct{}
- func Join[A Text](src []A, sep string) string
- func JoinAny(src []any, sep string) string
- func JoinAnyOpt(src []any, sep string) string
- func JoinDense[A Text](val ...A) string
- func JoinLines[A Text](val ...A) string
- func JoinLinesOpt[A Text](val ...A) string
- func JoinOpt[A Text](src []A, sep string) string
- func JoinSpaced[A Text](val ...A) string
- func JoinSpacedOpt[A Text](val ...A) string
- func JsonBytes[A any](val A) []byte
- func JsonBytesCatch[A any](val A) ([]byte, error)
- func JsonBytesIndent[A any](val A) []byte
- func JsonBytesIndentCatch[A any](val A) ([]byte, error)
- func JsonBytesNullCatch[A any, B NullableValGetter[A]](val B) ([]byte, error)
- func JsonDecodeClose[A any](src io.ReadCloser, out *A)
- func JsonDecodeFile[A any](path string, out *A)
- func JsonDecodeFileTo[A any](path string) (out A)
- func JsonEncodeFile[A any](path string, src A)
- func JsonParse[Out any, Src Text](src Src, out *Out)
- func JsonParseCatch[Out any, Src Text](src Src, out *Out) error
- func JsonParseTo[Out any, Src Text](src Src) (out Out)
- func JsonString[A any](val A) string
- func JsonStringIndent[A any](val A) string
- func Kind[A any]() r.Kind
- func KindOf[A any](A) r.Kind
- func KindOfAny(val any) r.Kind
- func Last[Slice ~[]Elem, Elem any](val Slice) Elem
- func LastIndex[Slice ~[]Elem, Elem any](val Slice) int
- func LastPtr[Slice ~[]Elem, Elem any](val Slice) *Elem
- func Lazy[A any](fun func() A) func() A
- func Lazy1[A, B any](fun func(B) A, val B) func() A
- func Lazy2[A, B, C any](fun func(B, C) A, val0 B, val1 C) func() A
- func Lazy3[A, B, C, D any](fun func(B, C, D) A, val0 B, val1 C, val2 D) func() A
- func Len[Slice ~[]Elem, Elem any](val Slice) int
- func Lens[Slice ~[]Elem, Elem any](val ...Slice) int
- func Lock(val sync.Locker) sync.Locker
- func LockGet[A any](lock sync.Locker, ptr *A) A
- func LockSet[A any](lock sync.Locker, ptr *A, val A)
- func Map[A, B any](src []A, fun func(A) B) []B
- func Map2[A, B, C any](one []A, two []B, fun func(A, B) C) []C
- func MapAppend[Src ~[]SrcVal, Tar ~[]TarVal, SrcVal any, TarVal any](tar *Tar, src Src, fun func(SrcVal) TarVal)
- func MapClear[Map ~map[Key]Val, Key comparable, Val any](tar Map)
- func MapClone[Map ~map[Key]Val, Key comparable, Val any](src Map) Map
- func MapCompact[A, B any](src []A, fun func(A) B) []B
- func MapDel[Map ~map[Key]Val, Key comparable, Val any](tar Map, key Key)
- func MapDict[Key comparable, A, B any](src map[Key]A, fun func(A) B) map[Key]B
- func MapFlat[A, B any](src []A, fun func(A) []B) []B
- func MapGet[Map ~map[Key]Val, Key comparable, Val any](tar Map, key Key) Val
- func MapGot[Map ~map[Key]Val, Key comparable, Val any](tar Map, key Key) (Val, bool)
- func MapHas[Map ~map[Key]Val, Key comparable, Val any](tar Map, key Key) bool
- func MapInit[Map ~map[Key]Val, Key comparable, Val any](val *Map) Map
- func MapKeys[Key comparable, Val any](src map[Key]Val) []Key
- func MapMut[Slice ~[]Elem, Elem any](src Slice, fun func(Elem) Elem) Slice
- func MapSet[Map ~map[Key]Val, Key comparable, Val any](tar Map, key Key, val Val)
- func MapSetOpt[Map ~map[Key]Val, Key comparable, Val any](tar Map, key Key, val Val)
- func MapVals[Key comparable, Val any](src map[Key]Val) []Val
- func Marshal(val any) ([]byte, error)
- func MarshalNullCatch[A any, B NullableValGetter[A]](val B) ([]byte, error)
- func Max[A Lesser[A]](val ...A) A
- func Max2[A Lesser[A]](one, two A) A
- func MaxBy[Src any, Out Lesser[Out]](src []Src, fun func(Src) Out) Out
- func MaxPrim[A LesserPrim](val ...A) A
- func MaxPrim2[A LesserPrim](one, two A) A
- func MaxPrimBy[Src any, Out LesserPrim](src []Src, fun func(Src) Out) Out
- func Min[A Lesser[A]](val ...A) A
- func Min2[A Lesser[A]](one, two A) A
- func MinBy[Src any, Out Lesser[Out]](src []Src, fun func(Src) Out) Out
- func MinPrim[A LesserPrim](val ...A) A
- func MinPrim2[A LesserPrim](one, two A) A
- func MinPrimBy[Src any, Out LesserPrim](src []Src, fun func(Src) Out) Out
- func Minus2[A Num](one, two A) A
- func MkdirAll(path string)
- func NewElem(typ r.Type) r.Value
- func NewReadCloser[A Text](val A) io.ReadCloser
- func NoEscUnsafe[A any](val A) A
- func NonZeroIndex[Slice ~[]Elem, Elem any](src Slice) []int
- func None[A any](src []A, fun func(A) bool) bool
- func Nop()
- func Nop1[A any](A)
- func Nop2[A, B any](A, B)
- func Nop3[A, B, C any](A, B, C)
- func NotEqNonZero[A comparable](one, two A) bool
- func NullOr[A Nullable](val ...A) A
- func Ok(fun func())
- func Or[A any](val ...A) A
- func Parse[Out any, Src Text](src Src, out *Out)
- func ParseCatch[Out any, Src Text](src Src, out *Out) error
- func ParseClearCatch[Out any, Tar ClearerPtrGetter[Out], Src Text](src Src, tar Tar) error
- func ParseReflectCatch[A Text](src A, out r.Value) error
- func ParseTo[Out any, Src Text](src Src) (out Out)
- func Plus[A Plusable](val ...A) A
- func Plus2[A Plusable](one, two A) A
- func PopHead[Slice ~[]Elem, Elem any](ptr *Slice) Elem
- func PopLast[Slice ~[]Elem, Elem any](ptr *Slice) Elem
- func Pow[A Num](base A, pow int) A
- func Procure[Out, Src any](src []Src, fun func(Src) Out) Out
- func Procured[Out, Src any](src []Src, fun func(Src) (Out, bool)) (Out, bool)
- func Ptr[A any](val A) *A
- func PtrGet[A any](val *A) A
- func PtrInit[A any](val **A) *A
- func PtrInited[A any](val *A) *A
- func PtrLen[Slice ~[]Elem, Elem any](val *Slice) int
- func PtrNoEscUnsafe[A any](val *A) u.Pointer
- func PtrPop[A any](src *A) (out A)
- func PtrSet[A any](tar *A, val A)
- func PtrSetOpt[A any](tar, src *A)
- func Range[A Int](min, max A) []A
- func ReadAll(src io.Reader) []byte
- func ReadCloseAll(src io.ReadCloser) []byte
- func ReadFile[A Text](path string) A
- func Rec(out *error)
- func RecN(out *error, skip int)
- func RecOnly(ptr *error, test func(error) bool)
- func RecWith(fun func(error))
- func Reject[Slice ~[]Elem, Elem any](src Slice, fun func(Elem) bool) (out Slice)
- func RejectAppend[Tar ~[]Elem, Elem any](tar *Tar, src []Elem, fun func(Elem) bool)
- func Reverse[A any](val []A)
- func Reversed[Slice ~[]Elem, Elem any](val Slice) Slice
- func RuntimeFunc(val any) *rt.Func
- func ScanCatch[Inner any, Outer Ptrer[Inner]](src any, tar Outer) error
- func SendOpt[Tar ~chan Val, Val any](tar Tar, val Val)
- func SendZeroOpt[Tar ~chan Val, Val any](tar Tar)
- func Size[A any]() uintptr
- func Skip()
- func SkipOnly(test func(error) bool)
- func Skipping(fun func())
- func SkippingOnly(test func(error) bool, fun func())
- func SliceDat[Slice ~[]Elem, Elem any](src Slice) *Elem
- func SliceIs[A any](one, two []A) bool
- func SliceOf[A any](val ...A) []A
- func SliceTrunc[Slice ~[]Elem, Elem any](tar *Slice)
- func SliceZero[A any](val []A)
- func Some[A any](src []A, fun func(A) bool) bool
- func SomePair[A any](one, two []A, fun func(A, A) bool) bool
- func Sort[A Lesser[A]](val []A)
- func SortPrim[A LesserPrim](val []A)
- func Sorted[Slice ~[]Elem, Elem Lesser[Elem]](val Slice) Slice
- func SortedPrim[Slice ~[]Elem, Elem LesserPrim](val Slice) Slice
- func Spaced(src ...any) string
- func SpacedOpt(src ...any) string
- func Span[A Int](val A) []A
- func SplitLines[A Text](src A) []string
- func Stat(path string) fs.FileInfo
- func Str(src ...any) string
- func StrDat[A Text](src A) *byte
- func StrEq[A Text](one, two A) bool
- func StrHead[A Text](val A) byte
- func StrLast[A Text](val A) byte
- func StrLen[A Text](val A) int
- func StrPop[A, B ~string](ptr *A, sep B) A
- func String[A any](val A) string
- func StringAny[A any](val A) string
- func StringCatch[A any](val A) (string, error)
- func StringNull[A any, B NullableValGetter[A]](val B) string
- func StringReflectCatch(val r.Value) (string, error)
- func Subtract[Slice ~[]Elem, Elem comparable](base Slice, sub ...Slice) Slice
- func Sum[Src any, Out Plusable](src []Src, fun func(Src) Out) Out
- func TagIdent(val string) string
- func Tail[Slice ~[]Elem, Elem any](val Slice) Slice
- func Take[Slice ~[]Elem, Elem any](src Slice, size int) Slice
- func TakeWhile[Slice ~[]Elem, Elem any](src Slice, fun func(Elem) bool) Slice
- func TermClearHard()
- func TermClearScrollback()
- func TermClearSoft()
- func Times[A any](src int, fun func(int) A) []A
- func TimesAppend[Slice ~[]Elem, Elem any](tar *Slice, src int, fun func(int) Elem)
- func ToAny[A any](val A) any
- func ToBytes[A Text](val A) []byte
- func ToErrAny(val any) error
- func ToErrTraced(val any, skip int) error
- func ToString[A Text](val A) string
- func Traced()
- func Trans(fun func(error) error)
- func TransOnly(test func(error) bool, trans func(error) error)
- func Transing(trans func(error) error, fun func())
- func TrimSpacePrefix[A Text](src A) A
- func TrimSpaceSuffix[A Text](src A) A
- func TruncLen[Slice ~[]Elem, Elem any](src Slice, size int) Slice
- func Try(err error)
- func Try1[A any](val A, err error) A
- func Try2[A, B any](one A, two B, err error) (A, B)
- func Try3[A, B, C any](one A, two B, three C, err error) (A, B, C)
- func Type[A any]() r.Type
- func TypeDeref(val r.Type) r.Type
- func TypeKind(val r.Type) r.Kind
- func TypeOf[A any](A) r.Type
- func Union[Slice ~[]Elem, Elem comparable](val ...Slice) Slice
- func Uniq[Slice ~[]Elem, Elem comparable](src Slice) Slice
- func ValidPk[Key comparable, Val Pked[Key]](val Val) Key
- func ValidateKind(tar r.Type, exp r.Kind)
- func ValueClone(src r.Value)
- func ValueCloned(src r.Value) r.Value
- func ValueDeref(val r.Value) r.Value
- func ValueDerefAlloc(val r.Value) r.Value
- func ValueNull[A any, B NullableValGetter[A]](src B) (driver.Value, error)
- func ValueSet(tar, src r.Value)
- func ValueToString(val r.Value) (string, bool)
- func ValueToStringCatch(val r.Value) (string, error)
- func ValueToText[A Text](val r.Value) (A, bool)
- func With[A any](funs ...func(*A)) (out A)
- func Wrapf(err error, pat string, val ...any) error
- func Write[Out io.Writer, Src Text](out Out, src Src)
- func Zero[A any]() (_ A)
- func ZeroIndex[Slice ~[]Elem, Elem any](src Slice) []int
- func ZeroValue[A any]() r.Value
- type AnyGetter
- type Appender
- type Atom
- type Buf
- func (self Buf) Append(val []byte) []byte
- func (self *Buf) AppendAny(val any)
- func (self *Buf) AppendAnys(val ...any)
- func (self *Buf) AppendAnysln(val ...any)
- func (self *Buf) AppendBool(val bool)
- func (self *Buf) AppendByte(val byte)
- func (self *Buf) AppendByteN(val byte, count int)
- func (self *Buf) AppendBytes(val []byte)
- func (self *Buf) AppendError(val error)
- func (self *Buf) AppendFloat32(val float32)
- func (self *Buf) AppendFloat64(val float64)
- func (self *Buf) AppendGoString(val any)
- func (self *Buf) AppendIndent()
- func (self *Buf) AppendIndents(lvl int)
- func (self *Buf) AppendInt(val int)
- func (self *Buf) AppendInt64(val int64)
- func (self *Buf) AppendNewline()
- func (self *Buf) AppendNewlines(count int)
- func (self *Buf) AppendRune(val rune)
- func (self *Buf) AppendRuneN(val rune, count int)
- func (self *Buf) AppendSpace()
- func (self *Buf) AppendSpaces(count int)
- func (self *Buf) AppendString(val string)
- func (self *Buf) AppendStringN(val string, count int)
- func (self *Buf) AppendUint(val int)
- func (self *Buf) AppendUint64(val uint64)
- func (self *Buf) Clear()
- func (self *Buf) Fprintf(pat string, val ...any)
- func (self *Buf) Fprintlnf(pat string, val ...any)
- func (self *Buf) GrowCap(size int)
- func (self *Buf) GrowLen(size int)
- func (self Buf) Len() int
- func (self *Buf) Reset(src []byte)
- func (self Buf) String() string
- func (self *Buf) TruncLen(size int)
- func (self *Buf) Write(val []byte) (int, error)
- func (self *Buf) WriteString(val string) (int, error)
- type BytesReadCloser
- type Cache
- type Caller
- func (self Caller) Append(buf []byte) []byte
- func (self Caller) AppendIndent(buf []byte, lvl int) []byte
- func (self Caller) AppendNewlineIndent(buf []byte, lvl int) []byte
- func (self Caller) Frame() (out Frame)
- func (self Caller) Func() *rt.Func
- func (self Caller) Pc() uintptr
- func (self Caller) String() string
- type Chan
- type Clearer
- type ClearerPtrGetter
- type Coll
- func (self *Coll[Key, Val]) Add(val ...Val) *Coll[Key, Val]
- func (self *Coll[Key, Val]) Calc()
- func (self *Coll[Key, Val]) Clear() *Coll[Key, Val]
- func (self Coll[Key, Val]) Get(key Key) Val
- func (self Coll[Key, Val]) Got(key Key) (Val, bool)
- func (self Coll[Key, _]) Has(key Key) bool
- func (self Coll[_, _]) HasLen() bool
- func (self Coll[_, _]) IsEmpty() bool
- func (self Coll[_, _]) Len() int
- func (self Coll[_, _]) MarshalJSON() ([]byte, error)
- func (self Coll[Key, Val]) Ptr(key Key) *Val
- func (self *Coll[_, _]) UnmarshalJSON(src []byte) error
- type ConcSlice
- type DbNameToJsonField
- type DbNameToJsonName
- type Decoder
- type Dict
- func (self Dict[_, _]) Clear()
- func (self Dict[Key, Val]) Clone() Dict[Key, Val]
- func (self Dict[Key, _]) Del(key Key)
- func (self Dict[Key, Val]) Get(key Key) Val
- func (self Dict[Key, Val]) Got(key Key) (Val, bool)
- func (self Dict[Key, _]) Has(key Key) bool
- func (self *Dict[Key, Val]) Init() Dict[Key, Val]
- func (self Dict[Key, _]) Keys() []Key
- func (self Dict[Key, Val]) Set(key Key, val Val)
- func (self Dict[Key, Val]) SetOpt(key Key, val Val)
- func (self Dict[_, Val]) Vals() []Val
- type Dur
- type DurHour
- type DurMaker
- type DurMinute
- type DurSecond
- type Encoder
- type Equaler
- type Err
- func (self Err) Append(inout []byte) []byte
- func (self Err) AppendStack(inout []byte) []byte
- func (self Err) Caused(val error) Err
- func (self Err) Err() error
- func (self Err) Error() string
- func (self Err) Format(out fmt.State, verb rune)
- func (self Err) Is(err error) bool
- func (self Err) IsTraced() bool
- func (self Err) Msgd(val string) Err
- func (self Err) Msgf(pat string, val ...any) Err
- func (self Err) Msgv(src ...any) Err
- func (self Err) Stack() string
- func (self Err) StackTrace() []uintptr
- func (self Err) String() string
- func (self Err) Traced(skip int) Err
- func (self Err) TracedOpt(skip int) Err
- func (self Err) Unwrap() error
- type ErrAny
- type ErrFinder
- type ErrStr
- type Errer
- type Errs
- func (self Errs) Append(buf []byte) []byte
- func (self Errs) As(out any) bool
- func (self Errs) Err() error
- func (self Errs) Error() string
- func (self Errs) Find(fun func(error) bool) error
- func (self Errs) First() error
- func (self Errs) HasLen() bool
- func (self Errs) Is(err error) bool
- func (self Errs) IsEmpty() bool
- func (self Errs) LenNil() int
- func (self Errs) LenNonNil() int
- func (self Errs) Some(fun func(error) bool) bool
- func (self Errs) String() string
- func (self Errs) Try()
- func (self Errs) Unwrap() error
- type FlagDef
- type FlagDefField
- func (self FlagDefField) GetDescHas() bool
- func (self FlagDefField) GetDescLen() int
- func (self FlagDefField) GetFlagHas() bool
- func (self FlagDefField) GetFlagLen() int
- func (self FlagDefField) GetInitHas() bool
- func (self FlagDefField) GetInitLen() int
- func (self *FlagDefField) Set(src r.StructField)
- type FlagFmt
- type FlagParser
- func (self FlagParser) Args(src []string)
- func (self FlagParser) Defaults()
- func (self FlagParser) FieldParse(src string, out r.Value)
- func (self FlagParser) Flag(key, src string)
- func (self FlagParser) FlagField(key string) r.Value
- func (self *FlagParser) Init(tar r.Value)
- func (self FlagParser) SetArgs(src []string)
- func (self FlagParser) TrailingBool(key string) bool
- func (self FlagParser) TrailingFlag(key string)
- type Float
- type Frame
- func (self Frame) Append(inout []byte) []byte
- func (self Frame) AppendIndent(inout []byte, lvl int) []byte
- func (self Frame) AppendNewlineIndent(inout []byte, lvl int) []byte
- func (self Frame) AppendRowIndent(inout []byte, lvl, wid int) []byte
- func (self *Frame) Init(val Caller)
- func (self *Frame) IsLang() bool
- func (self Frame) IsValid() bool
- func (self *Frame) NameShort() string
- func (self *Frame) Path() string
- func (self *Frame) Pkg() string
- func (self *Frame) Skip() bool
- func (self Frame) String() string
- type Frames
- type Getter
- type Initer1
- type Int
- type JsonNameToDbField
- type JsonNameToDbName
- type Lesser
- type LesserPrim
- type Maker
- type Maybe
- func (self Maybe[A]) Get() A
- func (self Maybe[_]) GetErr() error
- func (self Maybe[_]) HasErr() bool
- func (self Maybe[_]) MarshalJSON() ([]byte, error)
- func (self Maybe[A]) Ok() A
- func (self *Maybe[A]) Set(val A)
- func (self *Maybe[A]) SetErr(err error)
- func (self *Maybe[_]) UnmarshalJSON(src []byte) error
- type Mem
- type MemHour
- type MemMinute
- type MemSecond
- type Nexter
- type Nullable
- type NullableValGetter
- type Num
- type Opt
- func (self Opt[A]) Append(buf []byte) []byte
- func (self *Opt[_]) Clear()
- func (self Opt[A]) Get() A
- func (self Opt[_]) IsNonNull() bool
- func (self Opt[_]) IsNull() bool
- func (self Opt[A]) MarshalJSON() ([]byte, error)
- func (self Opt[A]) MarshalText() ([]byte, error)
- func (self *Opt[A]) Parse(src string) error
- func (self *Opt[A]) Ptr() *A
- func (self *Opt[A]) Scan(src any) error
- func (self *Opt[A]) Set(val A)
- func (self Opt[A]) String() string
- func (self *Opt[A]) UnmarshalJSON(src []byte) error
- func (self *Opt[A]) UnmarshalText(src []byte) error
- func (self Opt[A]) Value() (driver.Value, error)
- type Parser
- type ParserPtr
- type Pked
- type Plusable
- type Prim
- type Ptrer
- type Runner
- type Scanner
- type Set
- func (self Set[A]) Add(val ...A) Set[A]
- func (self Set[A]) AddFrom(val ...Set[A]) Set[A]
- func (self Set[A]) Clear() Set[A]
- func (self Set[A]) Del(val ...A) Set[A]
- func (self Set[A]) DelFrom(val ...Set[A]) Set[A]
- func (self Set[A]) Filter(fun func(A) bool) []A
- func (self Set[A]) GoString() string
- func (self Set[A]) Has(val A) bool
- func (self *Set[A]) Init() Set[A]
- func (self Set[_]) Len() int
- func (self Set[A]) MarshalJSON() ([]byte, error)
- func (self Set[A]) Reset(val ...A) Set[A]
- func (self Set[A]) Slice() []A
- func (self *Set[A]) UnmarshalJSON(src []byte) error
- type Setter
- type Signed
- type Sint
- type Slice
- func (self *Slice[A]) AppendPtr(val A) *A
- func (self *Slice[A]) AppendPtrZero() *A
- func (self *Slice[A]) AppendVals(val ...A)
- func (self Slice[_]) Cap() int
- func (self Slice[_]) CapMissing(size int) int
- func (self Slice[_]) CapUnused() int
- func (self Slice[A]) Clone() Slice[A]
- func (self Slice[A]) CloneAppend(val ...A) Slice[A]
- func (self Slice[A]) Compact() Slice[A]
- func (self Slice[A]) Count(src []A, fun func(A) bool) int
- func (self Slice[A]) Dat() *A
- func (self Slice[A]) Drop(size int) Slice[A]
- func (self Slice[A]) DropWhile(fun func(A) bool) Slice[A]
- func (self Slice[A]) Each(val Slice[A], fun func(A))
- func (self Slice[A]) EachPtr(fun func(*A))
- func (self Slice[A]) Every(fun func(A) bool) bool
- func (self Slice[A]) Filter(fun func(A) bool) Slice[A]
- func (self *Slice[A]) FilterAppend(src []A, fun func(A) bool)
- func (self Slice[A]) FilterIndex(fun func(A) bool) []int
- func (self Slice[A]) Find(fun func(A) bool) A
- func (self Slice[A]) FindIndex(fun func(A) bool) int
- func (self Slice[A]) Found(fun func(A) bool) (A, bool)
- func (self Slice[A]) Get(ind int) A
- func (self Slice[A]) GetPtr(ind int) *A
- func (self Slice[A]) Got(ind int) (A, bool)
- func (self Slice[A]) GrowCap(size int) Slice[A]
- func (self Slice[A]) GrowCapExact(size int) Slice[A]
- func (self Slice[A]) GrowLen(size int) Slice[A]
- func (self Slice[_]) HasLen() bool
- func (self Slice[A]) Head() A
- func (self Slice[A]) HeadPtr() *A
- func (self Slice[A]) Init() Slice[A]
- func (self Slice[_]) IsEmpty() bool
- func (self Slice[A]) Last() A
- func (self Slice[A]) LastIndex() int
- func (self Slice[A]) LastPtr() *A
- func (self Slice[_]) Len() int
- func (self Slice[A]) MapMut(fun func(A) A) Slice[A]
- func (self Slice[A]) NonZeroIndex() []int
- func (self Slice[A]) None(fun func(A) bool) bool
- func (self *Slice[A]) PopHead() A
- func (self *Slice[A]) PopLast() A
- func (self *Slice[_]) PtrLen() int
- func (self Slice[A]) Reject(fun func(A) bool) Slice[A]
- func (self *Slice[A]) RejectAppend(src []A, fun func(A) bool)
- func (self Slice[_]) Reverse()
- func (self Slice[A]) Reversed() Slice[A]
- func (self Slice[A]) Set(ind int, val A)
- func (self Slice[A]) Some(fun func(A) bool) bool
- func (self Slice[A]) Tail() Slice[A]
- func (self Slice[A]) Take(size int) Slice[A]
- func (self Slice[A]) TakeWhile(fun func(A) bool) Slice[A]
- func (self *Slice[A]) TimesAppend(src int, fun func(int) A)
- func (self *Slice[_]) Trunc()
- func (self Slice[A]) TruncLen(size int) Slice[A]
- func (self Slice[_]) Zero()
- func (self Slice[A]) ZeroIndex() []int
- type SliceHeader
- type SliceSnapshot
- type Snapshot
- type Sortable
- type SortablePrim
- type StackTraced
- type StringReadCloser
- type StructDeepPublicFields
- type StructFields
- type StructPublicFields
- type SyncMap
- func (self *SyncMap[Key, Val]) Delete(key Key)
- func (self *SyncMap[Key, Val]) Load(key Key) (Val, bool)
- func (self *SyncMap[Key, Val]) LoadAndDelete(key Key) (Val, bool)
- func (self *SyncMap[Key, Val]) LoadOrStore(key Key, val Val) (Val, bool)
- func (self *SyncMap[Key, Val]) Range(fun func(Key, Val) bool)
- func (self *SyncMap[Key, Val]) Store(key Key, val Val) Val
- type Text
- type Textable
- type TimeMicro
- func (self TimeMicro) Append(buf []byte) []byte
- func (self *TimeMicro) Clear()
- func (self TimeMicro) Get() any
- func (self TimeMicro) IsNull() bool
- func (self TimeMicro) MarshalJSON() ([]byte, error)
- func (self TimeMicro) MarshalText() ([]byte, error)
- func (self *TimeMicro) Parse(src string) error
- func (self *TimeMicro) Scan(src any) error
- func (self *TimeMicro) SetInt64(val int64)
- func (self *TimeMicro) SetTime(val time.Time)
- func (self TimeMicro) String() string
- func (self TimeMicro) Time() time.Time
- func (self *TimeMicro) UnmarshalJSON(src []byte) error
- func (self *TimeMicro) UnmarshalText(src []byte) error
- func (self TimeMicro) Value() (driver.Value, error)
- type TimeMilli
- func (self TimeMilli) Append(buf []byte) []byte
- func (self *TimeMilli) Clear()
- func (self TimeMilli) Get() any
- func (self TimeMilli) IsNull() bool
- func (self TimeMilli) MarshalJSON() ([]byte, error)
- func (self TimeMilli) MarshalText() ([]byte, error)
- func (self *TimeMilli) Parse(src string) error
- func (self *TimeMilli) Scan(src any) error
- func (self *TimeMilli) SetInt64(val int64)
- func (self *TimeMilli) SetTime(val time.Time)
- func (self TimeMilli) String() string
- func (self TimeMilli) Time() time.Time
- func (self *TimeMilli) UnmarshalJSON(src []byte) error
- func (self *TimeMilli) UnmarshalText(src []byte) error
- func (self TimeMilli) Value() (driver.Value, error)
- type Timed
- func (self *Timed[A]) Clear()
- func (self Timed[A]) Get() A
- func (self Timed[_]) IsExpired(dur time.Duration) bool
- func (self Timed[_]) IsLive(dur time.Duration) bool
- func (self Timed[_]) IsNonNull() bool
- func (self Timed[_]) IsNull() bool
- func (self Timed[A]) MarshalJSON() ([]byte, error)
- func (self *Timed[A]) Ptr() *A
- func (self *Timed[A]) Set(val A)
- func (self *Timed[A]) UnmarshalJSON(src []byte) error
- type Trace
- func (self Trace) Append(buf []byte) []byte
- func (self Trace) AppendIndent(buf []byte, lvl int) []byte
- func (self Trace) AppendIndentMulti(buf []byte, lvl int) []byte
- func (self Trace) AppendIndentTable(buf []byte, lvl int) []byte
- func (self Trace) Capture(skip int) Trace
- func (self Trace) Frames() Frames
- func (self Trace) HasLen() bool
- func (self Trace) Prim() []uintptr
- func (self Trace) String() string
- func (self Trace) StringIndent(lvl int) string
- func (self Trace) Table() string
- func (self Trace) TableIndent(lvl int) string
- type Tup2
- type Tup3
- type TypeCache
- type Uint
- type Words
- func (self Words) Camel() Words
- func (self Words) Comma() string
- func (self Words) Dense() string
- func (self Words) Join(val string) string
- func (self Words) Kebab() string
- func (self Words) Lower() Words
- func (self Words) MapHead(fun func(string) string) Words
- func (self Words) Sentence() Words
- func (self Words) Snake() string
- func (self Words) Spaced() string
- func (self Words) Title() Words
- func (self Words) Upper() Words
- type Zeroable
- type Zop
Examples ¶
Constants ¶
const ( // Standard terminal escape sequence. TermEsc = "\x1b" /** Escape sequence recognized by many terminals. When printed, should cause the terminal to scroll down as much as needed to create an appearance of clearing the window. Scrolling up should reveal previous content. */ TermEscClearSoft = TermEsc + `c` /** Escape sequence recognized by many terminals. When printed, should cause the terminal to clear the scrollback buffer without clearing the currently visible content. */ TermEscClearScrollback = TermEsc + `[3J` /** Escape sequence recognized by many terminals. When printed, should cause the terminal to clear both the scrollback buffer and the currently visible content. */ TermEscClearHard = TermEscClearSoft + TermEscClearScrollback )
Variables ¶
var ( Indent = ` ` Space = ` ` Newline = "\n" )
var ( TraceTable = true TraceSkipLang = true TraceShortName = true TraceBaseDir = `` // Set to `Cwd()` for better traces. )
These variables control how stack traces are printed.
var DbNameToJsonFieldCache = TypeCacheOf[DbNameToJsonField]()
var DbNameToJsonNameCache = TypeCacheOf[DbNameToJsonName]()
var FlagDefCache = TypeCacheOf[FlagDef]()
Stores cached `FlagDef` definitions for struct types.
var FlagFmtDefault = With((*FlagFmt).Default)
Default help formatter, used by `FlagHelp` and `FlagDef.Help`.
var JsonNameToDbFieldCache = TypeCacheOf[JsonNameToDbField]()
var JsonNameToDbNameCache = TypeCacheOf[JsonNameToDbName]()
var RE_NEWLINE = Lazy1(regexp.MustCompile, `(?:\r\n|\r|\n)`)
Matches any newline. Supports Windows, Unix, and old MacOS styles.
var ReWord = Lazy1( regexp.MustCompile, `\p{Lu}\p{Ll}+\d*|\p{Lu}+\d*|\p{Ll}+\d*`, )
Regexp for splitting arbitrary text into words, Unicode-aware. Used by `ToWords`.
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.
var StructFieldCache = TypeCacheOf[StructFields]()
var StructPublicFieldCache = TypeCacheOf[StructPublicFields]()
Functions ¶
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
Non-asserting interface conversion. Safely converts the given `any` into the given type, returning zero value on failure.
func AnyIs ¶
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 AnyToString ¶
If the underlying type is compatible with `Text`, unwraps and converts it to a string. Otherwise returns zero value. Boolean indicates success.
func AnyToText ¶
If the underlying type is compatible with `Text`, unwraps and converts it to the given text type. Otherwise returns zero value. Boolean indicates success. If the given value is backed by `string` but the output type is backed by `[]byte`, or vice versa, this performs a copy. Otherwise this doesn't allocate.
func Append ¶
Appends text representation of the input to the given buffer, using `AppendCatch`. Panics on errors.
func AppendCatch ¶
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 ¶
Appends the `fmt.GoStringer` representation of the given input to the given buffer. Also see the function `GoString`.
func AppendNull ¶
func AppendNull[A any, B NullableValGetter[A]](buf []byte, src B) []byte
Shortcut for implementing string encoding of `Nullable` types. Mostly for internal use.
func AppendPtr ¶
func AppendPtr[Slice ~[]Elem, Elem any](tar *Slice, val Elem) *Elem
Appends the given element to the given slice, returning the pointer to the newly appended position in the slice.
func AppendPtrZero ¶
func AppendPtrZero[Slice ~[]Elem, Elem any](tar *Slice) *Elem
Appends a zero element to the given slice, returning the pointer to the newly appended position in the slice.
func AppendReflectCatch ¶ added in v0.0.13
Reflection-based component of `AppendCatch`. Mostly for internal use.
func AppendVals ¶ added in v0.0.5
func AppendVals[Slice ~[]Elem, Elem any](tar *Slice, val ...Elem)
Appends the given elements to the given slice. Similar to built-in `append` but syntactically easier because the destination is not repeated.
func AppenderString ¶
Shortcut for stringifying a type that implements `Appender`. Mostly for internal use.
func CapMissing ¶ added in v0.0.4
Amount of missing capacity that needs to be allocated to append the given amount of additional elements.
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 ¶
Runs the given function, returning the function's result along with its panic converted to an error. Idempotently adds a stack trace.
func Catch10 ¶
Runs the given function with the given input, converting a panic to an error. Idempotently adds a stack trace.
func Catch11 ¶
Runs the given function with the given input, returning the function's result along with its panic converted to an error. Idempotently adds a stack trace.
func CatchOnly ¶
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 ¶
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
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 Clear ¶
func Clear[A any](val *A)
Zeroes the memory referenced by the given pointer. If the pointer is nil, this is a nop.
func Cleared ¶ added in v0.0.17
func Cleared[A any](val *A) *A
Calls `Clear` and returns the same pointer.
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](src 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 Compact ¶
func Compact[Slice ~[]Elem, Elem any](src Slice) Slice
Returns a version of the given slice without any zero values.
func ConcCatch ¶
func ConcCatch(val ...func()) []error
Concurrently runs the given functions, returning their panics.
func ConcEach ¶
func ConcEach[A any](src []A, fun func(A))
Concurrently calls the given function on each element of the given slice.
func ConcEachCatch ¶
Concurrently calls the given function on each element of the given slice, returning the resulting panics if any.
func ConcMapCatch ¶
Like `Map` but concurrent. Returns the resulting values along with the caught panics, if any.
func ConcMapFunc ¶
func ConcMapFunc[A, B any](out *[]B, src []A, fun func(A) B) func()
Partial application / thunk of `ConcMap`, suitable for `Conc`.
func Concat ¶
func Concat[Slice ~[]Elem, Elem any](val ...Slice) Slice
Concatenates the inputs. If every input is nil, output is nil.
func CtxGet ¶
Same as `CtxGot` but returns only the resulting value. If value was not found, output is zero.
func CtxGot ¶
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 CtxSet ¶
Uses `context.WithValue` to create a context with the given value, using the type's nil pointer "(*A)(nil)" as the key.
func DetailOnlyf ¶
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 ¶
Must be deferred. Wraps non-nil panics, prepending the error message and idempotently adding a stack trace. Usage:
defer gg.Detailf(`unable to %v`, `do X`)
func DropWhile ¶
Returns a subslice excluding elements at the start of the slice for which the given function contiguously returned `true`.
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 EqNonZero ¶
func EqNonZero[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 `NotEqNonZero`.
func Equal ¶
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 performance, even when calling it in fallback mode.
func ErrAs ¶ added in v0.0.10
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 ¶
Returns an error that describes a failure to convert the given input to the given output type. Used internally in various conversions.
func ErrFind ¶ added in v0.0.10
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. If the error
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 ¶
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
Shortcut that returns true if `ErrFind` is non-nil for the given error and predicate function.
func Every ¶
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 ¶
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 Fac ¶ added in v0.0.10
func Fac[A Uint](src A) A
Factorial without overflow checks. May 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 Fellback ¶
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 FilterAppend ¶ added in v0.0.4
Similar to `Filter` but instead of creating a new slice, appends to an existing slice.
func FilterIndex ¶ added in v0.0.5
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 ¶
Returns the first element for which the given function returns true. If nothing is found, returns a zero value.
func FindIndex ¶
Tests each element by calling the given function and returns the first element for which it returns `true`. If none match, returns `-1`.
func FlagHelp ¶ added in v0.0.13
Returns a help string for the given struct type, using `FlagFmtDefault`.
func FlagParse ¶ added in v0.0.13
* 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
* Parses CLI flags into the given value, which must be a struct. For parsing rules, see `FlagParser`.
func FlagParseReflect ¶ added in v0.0.13
* 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
* 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
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 ¶
Returns the first element for which the given function returns `true`. If nothing is found, returns a zero value. The additional boolean indicates whether something was actually found.
func FuncNameBase ¶
Returns the given function's name without the package path prefix.
func FuncNameShort ¶
Returns the name of the given function stripped of various namespaces: package path prefix, package name, type name.
func Get ¶
If the index is within bounds, returns the value at that index. Otherwise returns zero value.
func GetPtr ¶
If the index is within bounds, returns a pointer to the value at that index. Otherwise returns nil.
func GoString ¶
Returns the `fmt.GoStringer` representation of the given input. Equivalent to `fmt.Sprintf("%#v", val)` but marginally more efficient.
func Got ¶
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.
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 ¶
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
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 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.
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 ¶
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 ¶
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 Id3 ¶
func Id3[A, B, C any](val0 A, val1 B, val2 C) (A, B, C)
Identity function. Returns input as-is.
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.
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.
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), )
"Indexes" the given slice 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, 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 IsErrTraced ¶
True if the error has a stack trace. Relies on a hidden interface implemented by `Err`.
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
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
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
True if the input is "null" or blank. Ignores whitespace.
func IsValueBytes ¶
True if the value's underlying type is convertible to `[]byte`.
func IsZero ¶
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. The example loops should compile to approximately the same instructions as "normal" counted loops.
func Join ¶ added in v0.0.10
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
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
Like `JoinAny` but ignores empty strings.
func JoinLinesOpt ¶
Joins non-empty strings with newlines.
func JoinOpt ¶
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
Joins the given strings with a space.
func JoinSpacedOpt ¶ added in v0.0.19
Joins non-empty strings with a space.
func JsonBytesCatch ¶
Same as `json.Marshal` but sometimes marginally more efficient. Avoids spurious heap escape of the input.
func JsonBytesIndent ¶
Uses `json.MarshalIndent` to encode the given value as JSON with indentation controlled by the `Indent` variable, panicking on error.
func JsonBytesIndentCatch ¶
Same as `json.MarshalIndent`, but uses the default indentation controlled by the `Indent` variable. Also sometimes marginally more efficient. Avoids spurious heap escape of the input.
func JsonBytesNullCatch ¶
func JsonBytesNullCatch[A any, B NullableValGetter[A]](val B) ([]byte, error)
Shortcut for implementing JSON encoding of `Nullable` types. Mostly for internal use.
func JsonDecodeClose ¶
func JsonDecodeClose[A any](src io.ReadCloser, out *A)
Uses `json.Decoder` to decode one JSON entry/line from the reader, writing to the given output. Always closes the reader. Panics on errors.
func JsonDecodeFile ¶
Shortcut for decoding the content of the given file into a pointer of the given type. Panics on error.
func JsonDecodeFileTo ¶
Shortcut for decoding the content of the given file into a value of the given type. Panics on error.
func JsonEncodeFile ¶ added in v0.0.5
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 JsonParse ¶
Shortcut for parsing the given string or byte slice into a pointer of the given type. Panics on errors.
func JsonParseCatch ¶
Parses the given string or byte slice into a pointer of the given type. Similar to `json.Unmarshal`, but avoids the overhead of byte-string conversion and spurious escapes.
func JsonParseTo ¶
Shortcut for parsing the given string or byte slice into a value of the given type. Panics on errors.
func JsonString ¶
Encodes the input as a JSON string, panicking on error.
func JsonStringIndent ¶
Encodes the input as a JSON string, using default indentation controlled by the `Indent` variable.
func 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 ¶
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 ¶
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
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 Lazy ¶
func Lazy[A any](fun func() A) func() A
Takes a function that ought to be called no more than once. Returns a function that caches and reuses the result of the original function. Uses `sync.Once` internally.
func Lazy1 ¶
func Lazy1[A, B any](fun func(B) A, val B) func() A
Variant of `Lazy` that takes an additional argument and passes it to the given function when it's executed, which happens no more than once.
func Lazy2 ¶
func Lazy2[A, B, C any](fun func(B, C) A, val0 B, val1 C) func() A
Variant of `Lazy` that takes additional arguments and passes them to the given function when it's executed, which happens no more than once.
func Lazy3 ¶
func Lazy3[A, B, C, D any](fun func(B, C, D) A, val0 B, val1 C, val2 D) func() A
Variant of `Lazy` that takes additional arguments and passes them to the given function when it's executed, which happens no more than once.
func LockGet ¶ added in v0.0.13
Shortcut for dereferencing a pointer under a lock. Uses `PtrGet`, returning the zero value of the given type if the pointer is nil.
func Map ¶
func Map[A, B any](src []A, fun func(A) B) []B
Maps one slice to another. The resulting slice has exactly the same length as the original. Each element is created by calling the given function on the corresponding element of the original slice. The name refers to a well-known functional programming abstraction which doesn't have anything in common with the Go `map` types. Unlike many other higher-order slice functions, this one requires a non-nil function.
func 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, ](tar *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.
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 MapDict ¶ added in v0.0.8
func MapDict[Key comparable, A, B any](src map[Key]A, fun func(A) B) map[Key]B
Needs a better name. Can't be defined on `Dict` because Go doesn't support type parameters in method.
func MapFlat ¶ added in v0.0.14
func MapFlat[A, B any](src []A, fun func(A) []B) []B
Similar to `Map` but concats the slices returned by the given function.
func MapGet ¶
func MapGet[Map ~map[Key]Val, Key comparable, Val any](tar Map, key Key) Val
Same as `val := 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](val *Map) Map
Idempotently initializes the map at the given pointer via `make`, returning the result. Pointer must be non-nil. If map was non-nil, it's unchanged. Output is always non-nil.
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 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 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 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 ¶
Shortcut for implementing `encoding.TextMarshaler` on arbitrary types. Mostly for internal use. Uses `StringCatch` internally. The resulting bytes may be backed by constant storage and must not be mutated.
func MarshalNullCatch ¶
func MarshalNullCatch[A any, B NullableValGetter[A]](val B) ([]byte, error)
Shortcut for implementing `encoding.TextMarshaler` on `Nullable` types. Mostly for internal use. Uses `StringCatch` internally. The resulting bytes may be backed by constant storage and must not be mutated.
func Max ¶
func Max[A Lesser[A]](val ...A) A
Returns the largest value from among the inputs. For primitive types that don't implement `Lesser`, see `MaxPrim`.
func Max2 ¶
func Max2[A Lesser[A]](one, two A) A
Returns the larger of the two inputs. For primitive types that don't implement `Lesser`, see `MaxPrim2`.
func MaxBy ¶
Calls the given function for each element of the given slice and returns the largest value from among the results. For primitive types that don't implement `Lesser`, see `MaxPrimBy`.
func MaxPrim ¶
func MaxPrim[A LesserPrim](val ...A) A
Returns the largest value from among the inputs, which must be comparable primitives. For non-primitives, see `Max`.
func MaxPrim2 ¶
func MaxPrim2[A LesserPrim](one, two A) A
Returns the larger of the two inputs, which must be comparable primitives. For non-primitives, see `Max2`.
func MaxPrimBy ¶
func MaxPrimBy[Src any, Out LesserPrim](src []Src, fun func(Src) Out) Out
Calls the given function for each element of the given slice and returns the largest value from among the results, which must be comparable primitives. For non-primitives, see `MaxBy`.
func Min ¶
func Min[A Lesser[A]](val ...A) A
Returns the smallest value from among the inputs. For primitive types that don't implement `Lesser`, see `MinPrim`.
func Min2 ¶
func Min2[A Lesser[A]](one, two A) A
Returns the lesser of the two inputs. For primitive types that don't implement `Lesser`, see `MinPrim2`.
func MinBy ¶
Calls the given function for each element of the given slice and returns the smallest value from among the results. For primitive types that don't implement `Lesser`, see `MinPrimBy`.
func MinPrim ¶
func MinPrim[A LesserPrim](val ...A) A
Returns the smallest value from among the inputs, which must be comparable primitives. For non-primitives, see `Min`.
func MinPrim2 ¶
func MinPrim2[A LesserPrim](one, two A) A
Returns the lesser of the two inputs, which must be comparable primitives. For non-primitives, see `Min2`.
func MinPrimBy ¶
func MinPrimBy[Src any, Out LesserPrim](src []Src, fun func(Src) Out) Out
Calls the given function for each element of the given slice and returns the smallest value from among the results, which must be comparable primitives. For non-primitives, see `MinBy`.
func MkdirAll ¶ added in v0.0.5
func MkdirAll(path string)
Shortcut for `os.MkdirAll` with `os.ModePerm`.
func NewReadCloser ¶
func NewReadCloser[A Text](val A) io.ReadCloser
Creates a read-closer able to read from the given string or byte slice. Similar to the following, but shorter and avoids allocation in case of bytes-to-string or string-to-bytes conversion:
io.NopCloser(strings.NewReader(string(val))) io.NopCloser(bytes.NewReader([]byte(val)))
func NonZeroIndex ¶ added in v0.0.5
Takes a slice and returns the indexes whose elements are non-zero. All indexes are within the bounds of the original slice.
func NotEqNonZero ¶ added in v0.0.20
func NotEqNonZero[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 `EqNonZero`.
func NullOr ¶
func NullOr[A Nullable](val ...A) A
Variant of `Or` compatible with `Nullable`. Returns the first non-"null" value from among the inputs.
func Ok ¶
func Ok(fun func())
Must be deferred. Runs the function only if there's no panic. Idempotently adds a stack trace.
func Parse ¶
Decodes arbitrary text into a value of the given type, using `ParseCatch`. Panics on errors.
func ParseCatch ¶
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
Reflection-based component of `ParseCatch`. Mostly for internal use.
func ParseTo ¶
Decodes arbitrary text into a value of the given type, using `ParseCatch`. Panics on errors.
func Plus ¶
func Plus[A Plusable](val ...A) A
Combines all inputs via "+". If the input is empty, returns the zero value.
func Plus2 ¶
func Plus2[A Plusable](one, two A) A
Combines two inputs via "+". Also see variadic `Plus`.
func Pow ¶ added in v0.0.2
Short for "power". Missing feature of the standard "math" package. Raises the input, which may be an arbitrary number, to the given power. Current limitations: power must be a natural number; no overflow check.
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 ¶
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 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
Same as `len(PtrGet(val))` but can be passed to higher-order functions.
func PtrNoEscUnsafe ¶
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 Range ¶
func Range[A Int](min, max A) []A
Returns a slice of numbers from "min" to "max". The range is inclusive at the start but exclusive at the end: "[min,max)".
func ReadAll ¶
Same as `io.ReadAll` but with different error handling. If reader is nil, returns nil. Panics on errors.
func ReadCloseAll ¶
func ReadCloseAll(src io.ReadCloser) []byte
Variant of `ReadAll` that closes the provided reader when done. If reader is nil, returns nil. Panics on errors.
func ReadFile ¶
Shortcut for `os.ReadFile`. Panics on error. Converts the content to the requested text type without an additional allocation.
func Rec ¶
func Rec(out *error)
Must be deferred. Recovers from panics, writing the resulting error, if any, to the given pointer. Should be used together with "try"-style functions. Idempotently adds a stack trace.
func RecN ¶
Must be deferred. Same as `Rec`, but skips the given amount of stack frames when capturing a trace.
func RecOnly ¶
Must be deferred. Filtered version of `Rec`. Recovers from panics that satisfy the provided test. Re-panics on non-nil errors that don't satisfy the test. Does NOT check errors that are returned normally, without a panic. Idempotently adds a stack trace.
func RecWith ¶
func RecWith(fun func(error))
Must be deferred. Recovery for background goroutines which are not allowed to crash. Calls the provided function ONLY if the error is non-nil.
func Reject ¶
Inverse of `Filter`. Returns only the elements for which the given function returned `false`.
func RejectAppend ¶ added in v0.0.5
Similar to `Reject` but instead of creating a new slice, appends to an existing slice.
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 ¶
Takes an arbitrary function and returns its `runtime.Func`.
func ScanCatch ¶
Shortcut for implementing `sql.Scanner` on types that wrap other types, such as `Opt`. Mostly for internal use.
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.
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 SkipOnly ¶
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 SkippingOnly ¶
Runs a function, catching and ignoring only the panics that satisfy the provided test. Idempotently adds a stack trace.
func SliceDat ¶
func SliceDat[Slice ~[]Elem, Elem any](src Slice) *Elem
Returns the underlying data pointer of the given slice.
func SliceIs ¶ added in v0.0.2
True if the given slices have the same data pointer, length, capacity. Does not compare individual elements.
func SliceOf ¶
func SliceOf[A any](val ...A) []A
Shortcut for making a slice out of the given values. Workaround for the lack of type inference in type literals.
func SliceTrunc ¶
func SliceTrunc[Slice ~[]Elem, Elem any](tar *Slice)
Collapses the slice's length, preserving the capacity. Does not modify any elements.
func Some ¶
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 ¶
Utility for comparing slices pairwise. Returns true if the slices have the same length and the function returns true for at least one pair.
func Sort ¶
func Sort[A Lesser[A]](val []A)
Sorts a slice of comparable primitives. For primitives, see `SortPrim`.
func SortPrim ¶
func SortPrim[A LesserPrim](val []A)
Sorts a slice of comparable primitives. For non-primitives, see `Sort`.
func Sorted ¶
func Sorted[Slice ~[]Elem, Elem Lesser[Elem]](val Slice) Slice
Sorts a slice of comparable values, mutating and returning that slice. For primitives, see `SortedPrim`.
func SortedPrim ¶
func SortedPrim[Slice ~[]Elem, Elem LesserPrim](val Slice) Slice
Sorts a slice of comparable primitives, mutating and returning that slice. For non-primitives, see `Sort`.
func Spaced ¶
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 ¶
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 SplitLines ¶ added in v0.0.13
Self-explanatory. Splits the given text into lines.
func Str ¶ added in v0.0.10
Converts arguments to strings and concatenates the results. See `StringCatch` for the encoding rules. Also see `JoinDense` for a more limited but more efficient version that doesn't involve `any`.
func StrDat ¶
Returns the underlying data pointer of the given string or byte slice. Mutations may trigger segfaults or cause undefined behavior.
func StrPop ¶
func StrPop[A, B ~string](ptr *A, sep B) A
Searches for the given separator and returns the part of the string before the separator, removing that prefix from the original string referenced by the pointer. The separator is excluded from both chunks. As a special case, if the separator is empty, pops the entire given string.
func StringAny ¶
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 ¶
Missing feature of the standard library. Converts an arbitrary value to a string, allowing only INTENTIONALLY stringable values. Rules:
Nil is considered "".
A string is returned as-is.
A byte slice is cast to a string.
Any other primitive value (see constraint `Prim`) is encoded via `strconv`.
Types that support `fmt.Stringer`, `Appender` or `encoding.TextMarshaler` are encoded by using the corresponding method.
Any other type causes an error.
func StringNull ¶
func StringNull[A any, B NullableValGetter[A]](val B) string
Shortcut for implementing string encoding of `Nullable` types. Mostly for internal use.
func StringReflectCatch ¶ added in v0.0.13
Reflection-based component of `StringCatch`. Mostly for internal use.
func Subtract ¶
func Subtract[Slice ~[]Elem, Elem comparable](base Slice, sub ...Slice) Slice
Returns a version of the given slice excluding any additionally supplied values.
func Sum ¶
Calls the given function on each element of the given slice and returns the sum of all results, combined via "+".
func TagIdent ¶
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 TakeWhile ¶
Returns a subslice containing only elements at the start of the slice for which the given function contiguously returned `true`.
func TermClearHard ¶ added in v0.0.12
func TermClearHard()
Prints `TermEscClearScrollback` to `os.Stdout`, clearing the current TTY.
func TermClearScrollback ¶ added in v0.0.12
func TermClearScrollback()
Prints `TermEscClearScrollback` to `os.Stdout`, causing the current TTY to clear the scrollback buffer.
func TermClearSoft ¶ added in v0.0.12
func TermClearSoft()
Prints `TermEscClearScrollback` to `os.Stdout`, causing the current TTY to push existing content out of view.
func Times ¶
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
Similar to `Times` but instead of creating a new slice, appends to an existing slice.
func ToAny ¶ added in v0.0.19
Converts the argument to `any` and returns it. Sometimes useful in higher-order functions.
func ToBytes ¶
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 ToErrAny ¶
Idempotently converts the input to an error. If the input is nil, the output is nil. If the input implements `error`, it's returned as-is. If the input does not implement `error`, it's converted to `ErrStr` or wrapped with `ErrAny`.
func ToErrTraced ¶
Converts an arbitrary value to an error. Idempotently adds a stack trace. If the input is a non-nil non-error, it's wrapped into `ErrAny`.
func ToString ¶
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 Traced ¶
func Traced()
Must be deferred. Tool for adding a stack trace to an arbitrary panic. Unlike the "rec" functions, this does NOT prevent the panic from propagating. It simply ensures that there's a stack trace, then re-panics.
Caution: due to idiosyncrasies of `recover()`, this works ONLY when deferred directly. Anything other than `defer gg.Traced()` will NOT work.
func Trans ¶
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
Must be deferred. Similar to `Trans`, but transforms only non-nil errors that satisfy the given predicate. Idempotently adds a stack trace.
func Transing ¶
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 TruncLen ¶ added in v0.0.19
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, idempotently adds a stack trace and panics.
func Try1 ¶
If the error is nil, returns the given value. If the error is non-nil, idempotently adds a stack trace and panics.
func Try2 ¶
If the error is nil, returns the given values. If the error is non-nil, idempotently adds a stack trace and panics.
func Try3 ¶
If the error is nil, returns the given values. If the error is non-nil, idempotently adds a stack trace and panics.
func Type ¶
Returns `reflect.Type` of the given type. Differences from `reflect.TypeOf`:
Avoids spurious heap escape and copying.
Output is always non-nil.
When the given type is an interface, including the empty interface `any`, the output is a non-nil `reflect.Type` describing the given interface.
func TypeDeref ¶
Dereferences the given type, converting `reflect.Pointer` to its element type as many times as necessary. Returns an underlying non-pointer type.
func TypeKind ¶
Nil-safe version of `reflect.Type.Kind`. If the input is nil, returns `reflect.Invalid`.
func TypeOf ¶
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 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. As a special case, if the arguments contain exactly one non-empty slice, it's returned as-is without deduplication. To ensure uniqueness in all cases, call `Uniq`.
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 a newly allocated slice.
func ValidPk ¶
func ValidPk[ Key comparable, Val Pked[Key], ](val Val) Key
Short for "valid primary key". Returns the primary key generated by the given input, asserts that the key is non-zero, and returns the resulting key. Used internally by `Coll`.
func ValueClone ¶ added in v0.0.5
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
Similar to `CloneDeep` but takes and returns `reflect.Value`.
func ValueDeref ¶
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
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
Idempotent set. Calls `reflect.Value.Set` only if the inputs are distinct.
func ValueToString ¶
Reflection-based component of `AnyToString`. For internal use.
func ValueToStringCatch ¶
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 ¶
Reflection-based component of `AnyToText`. For internal use.
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 Wrapf ¶
Wraps the given error, prepending the given message and idempotently adding a stack trace.
func Write ¶ added in v0.0.12
Shortcut for writing the given text to the given `io.Writer`. Automatically converts text to bytes and panics on errors.
Types ¶
type AnyGetter ¶ added in v0.0.10
Used by some 3rd party libraries. Implemented by some of our types for compatibility.
type Appender ¶
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
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
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
Like `.Load` but returns true if anything was previously stored, and false if nothing was previously stored.
type Buf ¶
type Buf []byte
Short for "buffer". Simpler, cleaner, more usable alternative to `strings.Builder` and `bytes.Buffer`.
func (Buf) Append ¶
Implement `Appender`. Appends its own content to the given buffer. If the given buffer has no capacity, returns itself.
func (*Buf) AppendAny ¶
Appends the text representation of the input, using the `Append` function. Mutates the receiver.
func (*Buf) AppendAnys ¶ added in v0.0.15
Like `(*Buf).AppendAny` but variadic. TODO better name.
func (*Buf) AppendAnysln ¶ added in v0.0.15
Like `(*Buf).AppendAnys` but ensures a trailing newline, similarly to `fmt.Println`. If the last value provides a newline, an additional newline is not appended. TODO better name.
func (*Buf) AppendBool ¶
Appends text representation of the input, using "strconv". Mutates the receiver.
func (*Buf) AppendByte ¶
Appends the given byte. Mutates the receiver.
func (*Buf) AppendByteN ¶
Appends the given byte N times. Mutates the receiver.
func (*Buf) AppendBytes ¶
Appends the given bytes. Mutates the receiver.
func (*Buf) AppendError ¶
Appends the string representation of the given error. If the input is nil, this is a nop. Mutates the receiver.
func (*Buf) AppendFloat32 ¶
Appends text representation of the input, using "strconv". Mutates the receiver.
func (*Buf) AppendFloat64 ¶
Appends text representation of the input, using "strconv". Mutates the receiver.
func (*Buf) AppendGoString ¶
Appends the text representation of the input, using the `AppendGoString` function. Mutates the receiver.
func (*Buf) AppendIndents ¶
Appends `Indent` N times. Mutates the receiver.
func (*Buf) AppendInt ¶
Appends text representation of the input, using "strconv". Mutates the receiver.
func (*Buf) AppendInt64 ¶
Appends text representation of the input, using "strconv". Mutates the receiver.
func (*Buf) AppendNewline ¶
func (self *Buf) AppendNewline()
Appends `Newline`. Mutates the receiver.
func (*Buf) AppendNewlines ¶
Appends `Newline` N times. Mutates the receiver.
func (*Buf) AppendRune ¶
Appends the given rune. Mutates the receiver.
func (*Buf) AppendRuneN ¶ added in v0.0.19
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 ¶
Appends a space N times. Mutates the receiver.
func (*Buf) AppendString ¶
Appends the given string. Mutates the receiver.
func (*Buf) AppendStringN ¶
Appends the given string N times. Mutates the receiver.
func (*Buf) AppendUint ¶ added in v0.0.2
Appends text representation of the input, using "strconv". Mutates the receiver.
func (*Buf) AppendUint64 ¶ added in v0.0.2
Appends text representation of the input, using "strconv". Mutates the receiver.
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) Fprintlnf ¶
Shortcut for appending a formatted string with an idempotent trailing newline.
func (*Buf) GrowCap ¶
Increases the buffer's capacity sufficiently to accommodate N additional elements. Mutates the receiver.
func (Buf) String ¶
Free cast to a string. Mutation of the original buffer affects the resulting string.
func (*Buf) TruncLen ¶ added in v0.0.19
Reduces the current length to the given size. If the current length is already shorter, it's unaffected.
type BytesReadCloser ¶
Variant of `bytes.Reader` that also implements nop `io.Closer`.
func (*BytesReadCloser) Close ¶
func (*BytesReadCloser) Close() error
Implement `io.Closer`. This is a nop. The error is always nil.
func (*BytesReadCloser) Reset ¶
func (self *BytesReadCloser) Reset(src []byte) *BytesReadCloser
Calls `(*bytes.Reader).Reset`.
type Cache ¶
type Cache[ Key comparable, Val any, Ptr Initer1[Val, Key], ] struct { Lock sync.RWMutex Map map[Key]Ptr }
type Caller ¶
type Caller uintptr
Represents an entry in a call stack. Used for formatting.
func (Caller) AppendNewlineIndent ¶
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]) 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 ¶
Used by some utility functions.
type Coll ¶
type Coll[ Key comparable, Val Pked[Key], ] struct { Slice []Val `role:"ref"` Index map[Key]int }
Short for "collection". Represents an ordered map where keys are automatically derived from values, and must be non-zero.
func (*Coll[Key, Val]) Calc ¶
func (self *Coll[Key, Val]) Calc()
Reindexes the collection. Must be invoked after appending elements to the slice through external means. Note that all built-in methods of this type perform indexing automatically. This method must be invoked if the collection is modified by directly accessing `.Slice` and/or `.Index`.
func (Coll[Key, Val]) Get ¶
func (self Coll[Key, Val]) Get(key Key) Val
Returns the value indexed on the given key, or the zero value of that type.
func (Coll[Key, Val]) Got ¶
Returns the value indexed on the given key and a boolean indicating if the value was actually present.
func (Coll[Key, _]) Has ¶
True if the index has the given key. Doesn't check if the index is within the bounds of the inner slice.
func (Coll[_, _]) MarshalJSON ¶
Implement `json.Marshaler`. Encodes the inner slice, ignoring the index.
func (Coll[Key, Val]) Ptr ¶ added in v0.0.3
func (self Coll[Key, Val]) Ptr(key Key) *Val
Find the value indexed on the given key and returns the pointer to its position in the slice. If the value is not found, returns nil.
func (*Coll[_, _]) UnmarshalJSON ¶
Unmarshals the input into the inner slice and rebuilds the index.
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`.
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.
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
func (*DbNameToJsonName) Init ¶ added in v0.0.7
func (self *DbNameToJsonName) Init(src r.Type)
type Decoder ¶
Combination of interfaces related to text decoding implemented by some types in this package.
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.
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, _]) Keys ¶ added in v0.0.5
func (self Dict[Key, _]) Keys() []Key
Self as global `MapKeys`.
func (Dict[Key, Val]) Set ¶ added in v0.0.5
func (self Dict[Key, Val]) Set(key Key, val Val)
Self as global `MapSet`.
type Dur ¶ added in v0.0.2
Interface for values which are convertible to `time.Duration` or can specify a lifetime for other values. Used by `Mem`.
type DurHour ¶ added in v0.0.2
type DurHour struct{}
Implements `Dur` by returning `time.Hour`. This type is zero-sized, and can be embedded in other types, like a mixin, at no additional cost.
type DurMinute ¶ added in v0.0.2
type DurMinute struct{}
Implements `Dur` by returning `time.Minute`. This type is zero-sized, and can be embedded in other types, like a mixin, at no additional cost.
type DurSecond ¶ added in v0.0.2
type DurSecond struct{}
Implements `Dur` by returning `time.Second`. This type is zero-sized, and can be embedded in other types, like a mixin, at no additional cost.
type Encoder ¶
Combination of interfaces related to text encoding implemented by some types in this package.
type Equaler ¶ added in v0.0.5
Implemented by some types such as `time.Time`, and invoked automatically by our function `Equal`.
type Err ¶
Superior alternative to standard library errors. Supports stack traces and error wrapping. Provides a convenient builder API.
func Errf ¶
Creates an error where the message is generated by passing the arguments to `fmt.Sprintf`, with a stack trace.
func Errv ¶ added in v0.0.19
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) AppendStack ¶
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) Err ¶ added in v0.0.2
Implement `Errer`. If the receiver is a zero value, returns nil. Otherwise casts the receiver to an error.
func (Err) Msgv ¶ added in v0.0.19
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) Stack ¶
Returns a text representation of the full error message with the stack trace, if any.
func (Err) StackTrace ¶
Implement `StackTraced`, which allows to retrieve stack traces from nested errors.
func (Err) Traced ¶
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.
type ErrAny ¶
type ErrAny struct{ Val any }
Implementation of `error` that wraps an arbitrary value. Useful in panic recovery. Used internally by `Rec`.
type ErrFinder ¶ added in v0.0.10
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.
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`. Avoid casting this to `error`. Instead call the method `Errs.Err`, which will correctly return a nil interface when all errors are nil.
func (Errs) Append ¶
Appends a text representation of the error or errors. The text is the same as returned by `.Error`.
func (Errs) Err ¶ added in v0.0.2
Implement `Errer`. If there are any non-nil errors, returns a non-nil error, unwrapping if possible. Otherwise returns nil.
func (Errs) Find ¶ added in v0.0.10
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) Some ¶ added in v0.0.10
Shortcut for `.Find(fun) != nil`. Returns true if at least one error satisfies the given predicate function, using `ErrFind` to unwrap.
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.
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) 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`.
type FlagParser ¶ added in v0.0.13
* 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 equivalent 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) Defaults ¶ added in v0.0.13
func (self FlagParser) Defaults()
* 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 Frame ¶
Represents a stack frame. Generated by `Caller`. Used for formatting.
func (Frame) Append ¶
Appends a single-line representation of the frame that includes function name, file path, and row.
func (Frame) AppendNewlineIndent ¶
func (*Frame) IsLang ¶
True if the frame represents a "language" frame which is mostly not useful for debugging app code.
type Getter ¶
type Getter[A any] interface{ Get() A }
Implemented by utility types that wrap arbitrary types, such as `Opt`.
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
func (*JsonNameToDbName) Init ¶ added in v0.0.7
func (self *JsonNameToDbName) Init(src r.Type)
type Lesser ¶
Describes arbitrary types that support comparison via `.Less`, similar to "<". Used by various sorting/ordering utilities.
type LesserPrim ¶
Describes all primitive types that support the "<" operator. Counterpart to `Lesser` which describes types that support comparison via the `.Less` method.
type Maker ¶ added in v0.0.2
type Maker[A any] interface{ Make() A }
Very similar to `Getter`, but has different semantics in some contexts. Used by `Mem`.
type Maybe ¶
Contains a value or an error. The JSON tags "value" and "error" are chosen due to their existing popularity in HTTP API.
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[_]) MarshalJSON ¶
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[_]) UnmarshalJSON ¶
Implement `json.Unmarshaler`, decoding into the underlying value.
type Mem ¶ added in v0.0.2
Tool for deduplicating and caching expensive work. All methods are safe for concurrent use.
func (*Mem[A]) Clear ¶ added in v0.0.2
func (self *Mem[A]) Clear()
Clears the inner value and timestamp.
func (*Mem[A]) Dedup ¶ added in v0.0.2
Either reuses the existing value, or calls the given function to regenerate it. The given duration is the allotted lifetime of the previous value, if any.
In addition to reusing previous values, this method deduplicates concurrent work. When called concurrently by multiple goroutines, only 1 goroutine performs work, while the others simply wait for it.
Usage:
type MemExample struct { Mem[string] } func (self *MemExample) Get() string { return self.Dedup(time.Hour, func() string {return `some_value`}) }
type MemHour ¶ added in v0.0.2
Should be embedded in other types. See `Mem.DedupFrom` for an example.
type MemMinute ¶ added in v0.0.2
Should be embedded in other types. See `Mem.DedupFrom` for an example.
type MemSecond ¶ added in v0.0.2
Should be embedded in other types. See `Mem.DedupFrom` for an example.
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 ¶
Used by some utility functions.
type Opt ¶
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 ¶
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 ¶
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 ¶
Short for "optional value". Instantiates an optional with the given val. The result is considered non-null.
func (Opt[A]) Get ¶
func (self Opt[A]) Get() A
Implement `Getter`, returning the underlying value as-is.
func (Opt[A]) MarshalJSON ¶
Implement `json.Marshaler`. If `.IsNull`, returns a representation of JSON null. Otherwise uses `json.Marshal` to encode the underlying value.
func (Opt[A]) MarshalText ¶
Implement `encoding.TextMarshaler`, returning the same representation as `.String`.
func (*Opt[A]) Parse ¶
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 ¶
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 ¶
Implement `fmt.Stringer`. If `.IsNull`, returns an empty string. Otherwise uses the `String` function to encode the inner value.
func (*Opt[A]) UnmarshalJSON ¶
Implement `json.Unmarshaler`. If the input is empty or represents JSON null, clears the receiver via `.Clear`. Otherwise uses `JsonParseCatch` to decode into the underlying value.
func (*Opt[A]) UnmarshalText ¶
Implement `encoding.TextUnmarshaler`, using the same logic as `.Parse`.
type Parser ¶
Interface for types that support parsing from a string. Counterpart to `encoding.TextUnmarshaler`. Implemented by some utility types.
type Pked ¶
type Pked[A comparable] interface{ Pk() A }
Short for "primary keyed". See type `Coll` which acts as an ordered map where each value is indexed on its primary key. Keys must be non-zero. A zero value is considered an invalid key.
type 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 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[ Slice ~[]Elem, Elem any, Val comparable, ](src Slice, fun func(Elem) Val) Set[Val]
Creates a set by "mapping" the elements of a given slice via the provided function. 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]) AddFrom ¶
Set union. Idempotently adds all values from the given source sets to the receiver, which must be non-nil.
func (Set[A]) DelFrom ¶
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
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 ¶
Implement `fmt.GoStringer`, returning valid Go code that constructs the set.
func (*Set[A]) Init ¶
Idempotently inits the map via `make`, making it writable. The output pointer must be non-nil.
func (Set[A]) MarshalJSON ¶
JSON-encodes as a list. Order is random.
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 ¶
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 ¶
Describes all built-in signed numeric types and their typedefs, excluding complex numbers.
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, ToSlice(values).Get) grepr.Println(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.ToSlice(values).Get) fmt.Println(gg.GoString(result)) }
Output: []string{"one", "three"}
func ToSlice ¶ added in v0.0.5
Shortcut for converting an arbitrary slice to `Slice`. Workaround for the limitations of type inference in Go generics.
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[A]) AppendVals ¶ added in v0.0.5
func (self *Slice[A]) AppendVals(val ...A)
Same as global `AppendVals`.
func (Slice[_]) CapMissing ¶ added in v0.0.5
Same as global `CapMissing`.
func (Slice[A]) CloneAppend ¶ added in v0.0.5
Same as global `CloneAppend`.
func (Slice[A]) EachPtr ¶ added in v0.0.5
func (self Slice[A]) EachPtr(fun func(*A))
Same as global `EachPtr`.
func (*Slice[A]) FilterAppend ¶ added in v0.0.5
Same as global `FilterAppend`.
func (Slice[A]) FilterIndex ¶ added in v0.0.5
Same as global `FilterIndex`.
func (Slice[A]) GrowCapExact ¶ added in v0.0.5
Same as global `GrowCapExact`.
func (Slice[A]) HeadPtr ¶ added in v0.0.5
func (self Slice[A]) HeadPtr() *A
Same as global `HeadPtr`.
func (Slice[A]) LastPtr ¶ added in v0.0.5
func (self Slice[A]) LastPtr() *A
Same as global `LastPtr`.
func (Slice[A]) NonZeroIndex ¶ added in v0.0.5
Same as global `NonZeroIndex`.
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[A]) RejectAppend ¶ added in v0.0.5
Same as global `RejectAppend`.
func (Slice[A]) Set ¶ added in v0.0.5
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]) TimesAppend ¶ added in v0.0.5
Same as global `TimesAppend`.
type SliceHeader ¶
Memory representation of an arbitrary Go slice. Same as `reflect.SliceHeader` but with `unsafe.Pointer` instead of `uintptr`.
type SliceSnapshot ¶ added in v0.0.13
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[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 `Swap`.
func Snap ¶ added in v0.0.2
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
type Sortable ¶
type Sortable[A Lesser[A]] []A
Implements `sort.Interface`.
type SortablePrim ¶
type SortablePrim[A LesserPrim] []A
Implements `sort.Interface`.
func (SortablePrim[_]) Less ¶
func (self SortablePrim[_]) Less(one, two int) bool
Implement `sort.Interface`.
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 StackTraced ¶
type StackTraced interface{ StackTrace() []uintptr }
Implemented by the `Err` type. Used by `ErrTrace` to retrieve stack traces from arbitrary error types.
type StringReadCloser ¶
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]) LoadAndDelete ¶ added in v0.0.5
Typed version of `sync.Map.LoadAndDelete`.
func (*SyncMap[Key, Val]) LoadOrStore ¶ added in v0.0.5
Typed version of `sync.Map.LoadOrStore`.
type Text ¶
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 ¶
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
Shortcut for parsing text into `TimeMicro`. Panics on error.
func (TimeMicro) Append ¶ added in v0.0.10
Implement `Appender`, 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
Implement `AnyGetter` for compatibility with some 3rd party libraries. If zero, returns `nil`, otherwise creates `time.Time` by calling `TimeMicro.Time`.
func (TimeMicro) MarshalJSON ¶ added in v0.0.10
Implement `json.Marshaler`. If zero, returns bytes representing `null`. Otherwise encodes as a JSON number.
func (TimeMicro) MarshalText ¶ added in v0.0.10
Implement `encoding.TextMarhaler`. If zero, returns nil. Otherwise returns the same representation as `.String`.
func (*TimeMicro) Parse ¶ added in v0.0.10
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
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) SetTime ¶ added in v0.0.10
Sets the receiver to the result of `time.Time.UnixMicro`.
func (TimeMicro) String ¶ added in v0.0.10
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
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
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
Implement `encoding.TextUnmarshaler`, using the same algorithm as `.Parse`.
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
Shortcut for parsing text into `TimeMilli`. Panics on error.
func (TimeMilli) Append ¶ added in v0.0.10
Implement `Appender`, 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
Implement `AnyGetter` for compatibility with some 3rd party libraries. If zero, returns `nil`, otherwise creates `time.Time` by calling `TimeMilli.Time`.
func (TimeMilli) MarshalJSON ¶ added in v0.0.10
Implement `json.Marshaler`. If zero, returns bytes representing `null`. Otherwise encodes as a JSON number.
func (TimeMilli) MarshalText ¶ added in v0.0.10
Implement `encoding.TextMarhaler`. If zero, returns nil. Otherwise returns the same representation as `.String`.
func (*TimeMilli) Parse ¶ added in v0.0.10
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
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) SetTime ¶ added in v0.0.10
Sets the receiver to the result of `time.Time.UnixMilli`.
func (TimeMilli) String ¶ added in v0.0.10
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
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
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
Implement `encoding.TextUnmarshaler`, using the same algorithm as `.Parse`.
type Timed ¶ added in v0.0.2
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
Shortcut for creating a `Timed` with the given value, using the current timestamp.
func (*Timed[A]) Clear ¶ added in v0.0.2
func (self *Timed[A]) 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
True if the timestamp is unset, or if timestamp + duration > now.
func (Timed[A]) MarshalJSON ¶ added in v0.0.2
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[A]) UnmarshalJSON ¶ added in v0.0.2
Implement `json.Unmarshaler`. If the input is empty or represents JSON null, clears the receiver via `.Clear`. Otherwise uses `JsonParseCatch` to decode into the underlying value, and sets the current timestamp on success.
type Trace ¶
type Trace []Caller
Alias of `[]uintptr` with various methods for capturing and printing stack traces.
func AnyTrace ¶
If the input implements `error`, tries to find its stack trace via `ErrTrace`. If no trace is found, generates a new trace, skipping the given amount of frames. Suitable for use on `any` values returned by `recover`.
func CaptureTrace ¶
Shortcut for capturing a trace of the the current call stack, skipping N frames where 1 corresponds to the caller's frame.
func (Trace) Append ¶
Appends a multi-line text representation of the trace, with no leading indentation. See `.AppendIndent`.
func (Trace) AppendIndent ¶
Appends a multi-line text representation of the trace, with the given leading indentation. Used internally by other trace printing methods. Affected by the various "Trace*" variables. If `TraceTable` is true, the trace is formatted as a table, where each frame takes only one line, and names are aligned. Otherwise, the trace is formatted similarly to the default representation used by the Go runtime.
func (Trace) AppendIndentMulti ¶
Appends a representation of the trace similar to the default used by the Go runtime. Used internally by `.AppendIndent` if `TraceTable` is false.
func (Trace) AppendIndentTable ¶
Appends a table-style representation of the trace. Used internally by `.AppendIndent` if `TraceTable` is true.
func (Trace) Capture ¶
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) Prim ¶
Free cast to the underlying type. Useful for `runtime.Callers` and for implementing `StackTraced` in error types.
func (Trace) String ¶
Returns a multi-line text representation of the trace, with no leading indentation. See `.AppendIndent`.
func (Trace) StringIndent ¶
Returns a multi-line text representation of the trace with the given leading indentation. See `.AppendIndent`.
func (Trace) TableIndent ¶
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.
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.
type TypeCache ¶
func TypeCacheOf ¶
Type-inferring shortcut for creating a `TypeCache` of the given type.
type Words ¶
type Words []string
Tool for converting between typographic cases such as `camelCase` and `snake_case`.
func ToWords ¶
Splits arbitrary text into words, Unicode-aware. Suitable for conversion between typographic cases such as `camelCase` and `snake_case`.
func (Words) Camel ¶
Converts the first word to lowercase and each other word to Titlecase. Mutates and returns the receiver.
func (Words) MapHead ¶
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) Sentence ¶
Converts the first word to Titlecase and each other word to lowercase. 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 other encoding or decoding methods, and is intended only for non-scalar values such as "models" / "data classes".
func ZopMap ¶
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 ¶
Short for "zero optional value". Workaround for the lack of type inference in struct literals.
func (Zop[A]) Get ¶
func (self Zop[A]) Get() A
Implement `Getter`, returning the underlying value as-is.
func (Zop[A]) MarshalJSON ¶
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[A]) UnmarshalJSON ¶
Implement `json.Unmarshaler`. If the input is empty or represents JSON null, clears the receiver via `.Clear`. Otherwise uses `JsonParseCatch` to decode into the underlying value.
Source Files ¶
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. |