kit

package
v1.1.17 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2023 License: BSD-3-Clause Imports: 18 Imported by: 266

README

kit

Go Report Card GoDoc

Package kit provides various reflect type functions for GoKi system (KiType = KiT = kit -- also a bit of a "kit" collection of low-level system functions), including:

  • kit.TypeRegistry (types.go) for associating string names with reflect.Type values, to allow dynamic marshaling of structs, and also bidirectional string conversion of const int iota (enum) types. It is used by the GoKi ki system, hence the kit (ki types) name.

To register a new type, add:

var KiT_TypeName = kit.Types.AddType(&TypeName{}, [props|nil])

where the props is a map[string]interface{} of optional properties that can be associated with the type -- this is used in the GoGi graphical interface system for example to color objects of different types using the background-color property. KiT_TypeName variable can be conveniently used wherever a reflect.Type of that type is needed.

  • kit.EnumRegistry (enums.go) that registers constant int iota (aka enum) types, and provides general conversion utilities to / from string, int64, general properties associated with enum types, and deals with bit flags

  • kit.Type (type.go) struct provides JSON and XML Marshal / Unmarshal functions for saving / loading reflect.Type using registrered type names.

  • convert.go: robust interface{}-based type conversion routines that are useful in more lax user-interface contexts where "common sense" conversions between strings, numbers etc are useful

  • embeds.go: various functions for managing embedded struct types, e.g., determining if a given type embeds another type (directly or indirectly), and iterating over fields to flatten the otherwise nested nature of the field encoding in embedded types.

Documentation

Overview

Package kit provides various reflect type functions for GoKi system, including:

* kit.TypeRegistry (types.go) for associating string names with reflect.Type values, to allow dynamic marshaling of structs, and also bidirectional string conversion of const int iota (enum) types. It is used by the GoKi ki system, hence the kit (ki types) name.

To register a new type, add:

var KiT_TypeName = kit.Types.AddType(&TypeName{}, [props|nil])

where the props is a map[string]interface{} of optional properties that can be associated with the type -- this is used in the GoGi graphical interface system for example to color objects of different types using the background-color property. KiT_TypeName variable can be conveniently used wherever a reflect.Type of that type is needed.

* kit.EnumRegistry (enums.go) that registers constant int iota (aka enum) types, and provides general conversion utilities to / from string, int64, general properties associated with enum types, and deals with bit flags

* kit.Type (type.go) struct provides JSON and XML Marshal / Unmarshal functions for saving / loading reflect.Type using registrered type names.

* convert.go: robust interface{}-based type conversion routines that are useful in more lax user-interface contexts where "common sense" conversions between strings, numbers etc are useful

* embeds.go: various functions for managing embedded struct types, e.g., determining if a given type embeds another type (directly or indirectly), and iterating over fields to flatten the otherwise nested nature of the field encoding in embedded types.

Index

Constants

View Source
const (
	// BitFlag is used for AddEnum to indicate that this is a bit flag enum
	BitFlag = true

	// NotBitFlag is used for AddEnum to indicate that this is NOT a bit flag enum
	NotBitFlag = false
)

Variables

View Source
var KiT_TestFlags = Enums.AddEnumAltLower(TestFlagsN, NotBitFlag, nil, "Test")
View Source
var TypesMu sync.RWMutex

TypesMu protects updating of the type registry maps -- main Addtype etc all happens at startup and does not need protection, but property access does. use RLock for read-access to properties, and Lock for write access when adding or changing key / value.

Functions

func AllErrors added in v1.1.14

func AllErrors(errs []error, maxN int) error

AllErrors returns an err as a concatenation of errors (nil if none). no more than maxN are included (typically 10).

func AllFields

func AllFields(typ reflect.Type) []reflect.StructField

AllFields returns a slice list of all the StructField type information for all elemental fields of given type and all embedded types -- returns nil on error (logged)

func AllFieldsN

func AllFieldsN(typ reflect.Type) int

AllFieldsN returns number of elemental fields in given type

func AllFieldsTypeFunc

func AllFieldsTypeFunc(typ reflect.Type, fun func(typ reflect.Type, field reflect.StructField) bool) bool

AllFieldsTypeFunc calls a function on all the fields of a given struct type, including those on *any* embedded structs that this struct has -- if fun returns false then iteration stops -- overall rval is false if iteration was stopped or there was an error (logged), true otherwise.

func BitFlagsFromString

func BitFlagsFromString(bflg *int64, str string, en any) error

BitFlagsFromString sets an int64 of bit flags from a string representation of the bits that are set -- en is the number of defined bits, and also provides the type name for looking up strings

func BitFlagsToString

func BitFlagsToString(bflg int64, en any) string

BitFlagsToString converts an int64 of bit flags into a string representation of the bits that are set -- en is the number of defined bits, and also provides the type name for looking up strings

func BitFlagsTypeFromString

func BitFlagsTypeFromString(bflg *int64, str string, et reflect.Type, n int) error

BitFlagsTypeFromString sets an int64 of bit flags from a string representation of the bits that are set -- gets enum type and n of defined elements directly

func CloneToType

func CloneToType(typ reflect.Type, val any) reflect.Value

CloneToType creates a new object of given type, and uses SetRobust to copy an existing value (of perhaps another type) into it -- only expected to work for basic types

func CopyMapRobust added in v1.1.14

func CopyMapRobust(to, fm any) error

CopyMapRobust robustly copies maps using SetRobust method for the elements.

func CopySliceRobust added in v1.1.12

func CopySliceRobust(to, fm any) error

CopySliceRobust robustly copies slices using SetRobust method for the elements.

func Embed

func Embed(stru any, embed reflect.Type) any

Embed returns the embedded struct of given type within given struct

func EmbedImplements added in v0.9.4

func EmbedImplements(typ, iface reflect.Type) bool

EmbedImplements checks if given type implements given interface, or it embeds a type that does so -- must pass a type constructed like this: reflect.TypeOf((*gi.Node2D)(nil)).Elem() or just reflect.TypeOf(ki.BaseIface())

func EnumBitDepthCheck added in v0.9.12

func EnumBitDepthCheck(typ reflect.Type, n int64) error

EnumBitDepthCheck checks if given type can handle given number of bit flags

func EnumIfaceFromInt64

func EnumIfaceFromInt64(ival int64, typ reflect.Type) any

EnumIfaceFromInt64 returns an interface{} value which is an enum value of given type (not a pointer to it), set to given integer value

func EnumIfaceFromString

func EnumIfaceFromString(str string, typ reflect.Type) any

EnumIfaceFromString returns an interface{} value which is an enum value of given type (not a pointer to it), set to given string value -- requires reflect type of enum

func EnumIfaceToInt64

func EnumIfaceToInt64(eval any) int64

EnumIfaceToInt64 converts an enum interface{} into an int64 using reflect -- just use int64(eval) when you have the enum value in hand -- this is when you just have a generic interface{}

func EnumIfaceToString

func EnumIfaceToString(eval any) string

EnumIfaceToString converts an enum interface{} value to its corresponding string value, using fmt.Stringer interface directly -- same effect as calling fmt.Sprintf("%v") but this is slightly faster

func EnumInt64ToString

func EnumInt64ToString(ival int64, typ reflect.Type) string

EnumInt64ToString first converts an int64 to enum of given type, and then converts that to a string value

func EnumMarshalJSON

func EnumMarshalJSON(eval any) ([]byte, error)

func EnumMarshalText

func EnumMarshalText(eval any) ([]byte, error)

func EnumUnmarshalJSON

func EnumUnmarshalJSON(eval any, b []byte) error

func EnumUnmarshalText

func EnumUnmarshalText(eval any, b []byte) error

func FieldByPath

func FieldByPath(typ reflect.Type, path string) (reflect.StructField, bool)

FieldByPath returns field in type or embedded structs within type, by a dot-separated path -- finds field by name for each level of the path, and recurses.

func FieldValueByPath

func FieldValueByPath(stru any, path string) (reflect.Value, bool)

FieldValueByPath returns field interface in type or embedded structs within type, by a dot-separated path -- finds field by name for each level of the path, and recurses.

func FlatFieldByName

func FlatFieldByName(typ reflect.Type, nm string) (reflect.StructField, bool)

FlatFieldByName returns field in type or embedded structs within type, by name -- native function already does flat version, so this is just for reference and consistency

func FlatFieldInterfaceByName

func FlatFieldInterfaceByName(stru any, nm string) any

FlatFieldInterfaceByName finds field in object and embedded objects, by name, returning interface{} to pointer of field, or nil if not found

func FlatFieldInterfaces

func FlatFieldInterfaces(stru any) []any

FlatFieldInterfaces returns a slice list of all the field interface{} values *as pointers to the field value* (i.e., calling Addr() on the Field Value) for fields of given struct (must pass a pointer to the struct) and any of its embedded structs -- returns nil on error (logged)

func FlatFieldTag

func FlatFieldTag(typ reflect.Type, nm, tag string) string

FlatFieldTag returns given tag value in field in type or embedded structs within type, by name -- empty string if not set or field not found

func FlatFieldVals

func FlatFieldVals(stru any) []reflect.Value

FlatFieldsVals returns a slice list of all the field reflect.Value's for fields of given struct (must pass a pointer to the struct) and any of its embedded structs -- returns nil on error (logged)

func FlatFieldValueByName

func FlatFieldValueByName(stru any, nm string) reflect.Value

FlatFieldValueByName finds field in object and embedded objects, by name, returning reflect.Value of field -- native version of Value function already does flat find, so this just provides a convenient wrapper

func FlatFields

func FlatFields(typ reflect.Type) []reflect.StructField

FlatFields returns a slice list of all the StructField type information for fields of given type and any embedded types -- returns nil on error (logged)

func FlatFieldsTypeFunc

func FlatFieldsTypeFunc(typ reflect.Type, fun func(typ reflect.Type, field reflect.StructField) bool) bool

FlatFieldsTypeFunc calls a function on all the primary fields of a given struct type, including those on anonymous embedded structs that this struct has, passing the current (embedded) type and StructField -- effectively flattens the reflect field list -- if fun returns false then iteration stops -- overall rval is false if iteration was stopped or there was an error (logged), true otherwise

func FlatFieldsValueFunc

func FlatFieldsValueFunc(stru any, fun func(stru any, typ reflect.Type, field reflect.StructField, fieldVal reflect.Value) bool) bool

FlatFieldsValueFunc calls a function on all the primary fields of a given struct value (must pass a pointer to the struct) including those on anonymous embedded structs that this struct has, passing the current (embedded) type and StructField -- effectively flattens the reflect field list

func HasUpperCase added in v0.9.11

func HasUpperCase(str string) bool

HasUpperCase returns true if string has an upper-case letter

func IfaceIsNil

func IfaceIsNil(it any) bool

IfaceIsNil checks if an interface value is nil -- the interface itself could be nil, or the value pointed to by the interface could be nil -- this checks both, safely gopy:interface=handle

func KindIsBasic

func KindIsBasic(vk reflect.Kind) bool

KindIsBasic returns true if the reflect.Kind is a basic type such as Int, Float, etc

func LongTypeName added in v0.9.8

func LongTypeName(typ reflect.Type) string

LongTypeName returns the long, full package-path qualified type name. This is guaranteed to be unique and used for internal storage of several maps to avoid any conflicts. It is also very quick to compute.

func MakeMap

func MakeMap(typ reflect.Type) reflect.Value

MakeMap makes a map that is actually addressable, getting around the hidden interface{} that reflect.MakeMap makes, by calling UnhideIfaceValue (from ptrs.go)

func MakeOfType

func MakeOfType(typ reflect.Type) reflect.Value

MakeOfType creates a new object of given type with appropriate magic foo to make it usable

func MakePtrValue

func MakePtrValue(v reflect.Value) reflect.Value

MakePtrValue makes a new pointer to the given value, adding an extra level of indirection, and then removing that indirection, resulting in something that is now addressable / assignable -- this is necessary for enums..

func MakeSlice

func MakeSlice(typ reflect.Type, len, cap int) reflect.Value

MakeSlice makes a map that is actually addressable, getting around the hidden interface{} that reflect.MakeSlice makes, by calling UnhideIfaceValue (from ptrs.go)

func MapAdd

func MapAdd(mv any)

MapAdd adds a new blank entry to the map

func MapDelete

func MapDelete(mv any, key any)

MapDelete deletes a key-value from the map (set key to a zero value)

func MapDeleteAll added in v1.1.14

func MapDeleteAll(mv any)

MapDeleteAll deletes everything from map

func MapDeleteValue

func MapDeleteValue(mv any, key reflect.Value)

MapDeleteValue deletes a key-value from the map (set key to a zero value) -- key is already a reflect.Value

func MapElsN

func MapElsN(mp any) int

MapElsN returns number of elemental fields in given map type

func MapElsValueFun

func MapElsValueFun(mp any, fun func(mp any, typ reflect.Type, key, val reflect.Value) bool) bool

MapElsValueFun calls a function on all the "basic" elements of given map -- iterates over maps within maps (but not structs, slices within maps).

func MapKeyType

func MapKeyType(mp any) reflect.Type

MapKeyType returns the type of the key for the given map (which can be a pointer to a map or a direct map) -- just Key() of map type, but using this function makes it more explicit what is going on.

func MapSort

func MapSort(mp any, byKey, ascending bool) []reflect.Value

MapSort sorts keys of map either by key or by value, returns those keys as a slice of reflect.Value, as returned by reflect.Value.MapKeys() method

func MapStructElsN

func MapStructElsN(mp any) int

MapStructElsN returns number of elemental fields in given map / struct types

func MapStructElsValueFun

func MapStructElsValueFun(mp any, fun func(mp any, typ reflect.Type, val reflect.Value) bool) bool

MapStructElsValueFun calls a function on all the "basic" elements of given map or struct -- iterates over maps within maps and fields within structs

func MapValueSort

func MapValueSort(mpvnp reflect.Value, keys []reflect.Value, ascending bool) error

MapValueSort sorts keys of map by values

func MapValueType

func MapValueType(mp any) reflect.Type

MapValueType returns the type of the value for the given map (which can be a pointer to a map or a direct map) -- just Elem() of map type, but using this function makes it more explicit what is going on.

func Max32

func Max32(a, b float32) float32

func Min32

func Min32(a, b float32) float32

func MinPos

func MinPos(a, b float64) float64

minimum excluding 0

func MinPos32

func MinPos32(a, b float32) float32

minimum excluding 0

func NonPtrInterface

func NonPtrInterface(el any) any

NonPtrInterface returns the non-pointer value of an interface

func NonPtrType

func NonPtrType(typ reflect.Type) reflect.Type

NonPtrType returns the non-pointer underlying type

func NonPtrValue

func NonPtrValue(v reflect.Value) reflect.Value

NonPtrValue returns the non-pointer underlying value

func OnePtrInterface

func OnePtrInterface(el any) any

OnePtrInterface returns the pointer value of an interface, if it is possible to get one through Addr()

func OnePtrType

func OnePtrType(typ reflect.Type) reflect.Type

OnePtrType returns a type that is exactly one pointer away from a non-pointer type

func OnePtrUnderlyingValue added in v0.9.7

func OnePtrUnderlyingValue(v reflect.Value) reflect.Value

OnePtrUnderlyingValue returns a value that is exactly one pointer away from a non-pointer type, and also goes through an interface to find the actual underlying type behind the interface.

func OnePtrValue

func OnePtrValue(v reflect.Value) reflect.Value

OnePtrValue returns a value that is exactly one pointer away from a non-pointer type

func PtrInterface

func PtrInterface(el any) any

PtrInterface returns the pointer value of an interface, if it is possible to get one through Addr()

func PtrType

func PtrType(typ reflect.Type) reflect.Type

PtrType returns the pointer type for given type, if given type is not already a Ptr

func PtrValue

func PtrValue(v reflect.Value) reflect.Value

PtrValue returns the pointer version (Addr()) of the underlying value if the value is not already a Ptr

func Sel

func Sel(a ...any) []any

Sel implements the "mute" function from here http://blog.vladimirvivien.com/2014/03/hacking-go-filter-values-from-multi.html provides a way to select a particular return value in a single expression, without having a separate assignment in between -- I just call it "Sel" as I'm unlikely to remember how to type a mu

func SetEnumIfaceFromInt64

func SetEnumIfaceFromInt64(eval any, ival int64, typ reflect.Type) error

SetEnumIfaceFromInt64 sets enum interface{} value from int64 value -- must pass a pointer to the enum and also needs raw type of the enum as well -- can't get it from the interface{} reliably

func SetEnumIfaceFromString

func SetEnumIfaceFromString(eptr any, str string) error

SetEnumIfaceFromString sets enum value from string -- must pass a *pointer* to the enum item. IMPORTANT: requires the modified stringer go generate utility that generates a FromString method

func SetEnumValueFromInt64

func SetEnumValueFromInt64(eval reflect.Value, ival int64) error

SetEnumValueFromInt64 sets enum value from int64 value, using a reflect.Value representation of the enum -- does more checking and can get type from value compared to Iface version

func SetEnumValueFromString

func SetEnumValueFromString(eval reflect.Value, str string) error

SetEnumValueFromString sets enum value from string using reflect.Value IMPORTANT: requires the modified stringer go generate utility that generates a FromString method

func SetFromDefaultTags added in v1.1.12

func SetFromDefaultTags(obj any) error

SetFromDefaultTags sets values of fields in given struct based on `def:` default value field tags.

func SetMapRobust added in v0.9.8

func SetMapRobust(mp, ky, val reflect.Value) bool

SetMapRobust robustly sets a map value using reflect.Value representations of the map, key, and value elements, ensuring that the proper types are used for the key and value elements using sensible conversions. map value must be a valid map value -- that is not checked.

func SetRobust

func SetRobust(to, frm any) bool

SetRobust robustly sets the 'to' value from the 'from' value. destination must be a pointer-to. Copies slices and maps robustly, and can set a struct, slice or map from a JSON-formatted string from value. gopy:interface=handle

func SetTypeProp

func SetTypeProp(props map[string]any, key string, val any)

SetTypeProp provides safe (mutex protected) write setting of property map returned by Properties method -- must use this for all Properties access!

func ShortTypeName added in v0.9.8

func ShortTypeName(typ reflect.Type) string

ShortTypeName returns the short version of a package-qualified type name which just has the last element of the path. This is what is used in standard Go programming, and is is used for the key to lookup reflect.Type names -- i.e., this is what you should save in a JSON file. The potential naming conflict is worth the brevity, and typically a given file will only contain mutually-compatible, non-conflicting types. This is cached in ShortNames because the path.Base computation is apparently a bit slow.

func SliceDeleteAt

func SliceDeleteAt(sl any, idx int)

SliceDeleteAt deletes element at given index from slice

func SliceElType

func SliceElType(sl any) reflect.Type

SliceElType returns the type of the elements for the given slice (which can be a pointer to a slice or a direct slice) -- just Elem() of slice type, but using this function makes it more explicit what is going on. And it uses OnePtrUnderlyingValue to get past any interface wrapping.

func SliceNewAt

func SliceNewAt(sl any, idx int)

SliceNewAt inserts a new blank element at given index in the slice -- -1 means the end

func SliceSort

func SliceSort(sl any, ascending bool) error

SliceSort sorts a slice of basic values (see StructSliceSort for sorting a slice-of-struct using a specific field), trying floats.Floater Float(), ints.Inter Int(), interfaces first, and then falling back on reflect.Kind float, int, string conversions (first fmt.Stringer String()) and supporting time.Time directly as well.

func String

func String(k Type) string

String satisfies the stringer interface

func StringJSON added in v1.1.6

func StringJSON(it any) string

StringJSON returns a JSON representation of item, as a string e.g., for printing / debugging etc.

func StructSliceSort

func StructSliceSort(struSlice any, fldIdx []int, ascending bool) error

StructSliceSort sorts a slice of a struct according to the given field indexes and sort direction, trying floats.Floater Float(), ints.Inter Int(), interfaces first, and then falling back on reflect.Kind float, int, string conversions (first fmt.Stringer String()) and supporting time.Time directly as well. There is no direct method for checking the field indexes so those are assumed to be accurate -- will panic if not!

func StructTags

func StructTags(tags reflect.StructTag) map[string]string

StructTags returns a map[string]string of the tag string from a reflect.StructTag value e.g., from StructField.Tag

func ToBool

func ToBool(it any) (bool, bool)

ToBool robustly converts anything to a bool gopy:interface=handle

func ToFloat

func ToFloat(it any) (float64, bool)

ToFloat robustly converts anything to a Float64 -- uses the floats.Floater Float() interface first if available gopy:interface=handle

func ToFloat32

func ToFloat32(it any) (float32, bool)

ToFloat32 robustly converts anything to a Float32 -- uses the floats.Floater Float() interface first if available gopy:interface=handle

func ToInt

func ToInt(it any) (int64, bool)

ToInt robustly converts anything to an int64 -- uses the ints.Inter ToInt interface first if available gopy:interface=handle

func ToString

func ToString(it any) string

ToString robustly converts anything to a String -- because Stringer is so ubiquitous, and we fall back to fmt.Sprintf(%v) in worst case, this should definitely work in all cases, so there is no bool return value gopy:interface=handle

func ToStringPrec added in v0.9.8

func ToStringPrec(it any, prec int) string

ToStringPrec robustly converts anything to a String using given precision for converting floating values -- using a value like 6 truncates the nuisance random imprecision of actual floating point values due to the fact that they are represented with binary bits. See ToString for more info. gopy:interface=handle

func TypeEmbeds

func TypeEmbeds(typ, embed reflect.Type) bool

TypeEmbeds checks if given type embeds another type, at any level of recursive embedding (including being the type itself)

func TypeFor added in v1.1.16

func TypeFor[T any]() reflect.Type

TypeFor returns the reflect.Type that represents the type argument T. It is a copy of reflect.TypeFor, which will likely be added in Go 1.22 (see https://github.com/golang/go/issues/60088)

func TypeProp

func TypeProp(props map[string]any, key string) (any, bool)

TypeProp provides safe (mutex protected) read access to property map returned by Properties method -- must use this for all Properties access!

func UnhideIfaceValue

func UnhideIfaceValue(v reflect.Value) reflect.Value

UnhideIfaceValue returns a reflect.Value for any of the Make* functions that is actually assignable -- even though these functions return a pointer to the new object, it is somehow hidden behind an interface{} and this magic code, posted by someone somewhere that I cannot now find again, un-hides it..

func ValueIsZero

func ValueIsZero(v reflect.Value) bool

ValueIsZero returns true if the reflect.Value is Zero or nil or invalid or otherwise doesn't have a useful value -- from https://github.com/golang/go/issues/7501

func ValueSliceSort

func ValueSliceSort(sl []reflect.Value, ascending bool) error

ValueSliceSort sorts a slice of reflect.Values using basic types where possible

Types

type Describer added in v1.1.16

type Describer interface {
	// Desc returns a description for an item
	Desc() string
}

Describer interface provides a description for an item, typically to be displayed on hover as a tooltip in a GUI

type EnumRegistry

type EnumRegistry struct {
	// Enums is a map from the *short* package-qualified name to reflect.Type
	Enums map[string]reflect.Type

	// Props contains properties that can be associated with each enum type
	// e.g., "BitFlag": true, "AltStrings" : map[int64]string, or other custom settings.
	// The key here is the short package-qualified name
	Props map[string]map[string]any

	// Vals contains cached EnumValue representations of the enum values.
	// Used by Values method.
	Vals map[string][]EnumValue
}

EnumRegistry is a map from an enum-style const int type name to a corresponding reflect.Type and conversion methods generated by (modified) stringer that convert to / from strings.

Each such type must be explicitly registered by calling AddEnum in an expression that also initializes a new global variable that is then useful whenever you need to specify that type:

var KiT_MyEnum = kit.Enums.AddEnum(MyEnumN, bitFlag true/false,
   TypeNameProps (or nil))

where MyEnum is the name of the type, MyEnumN is the enum value representing the number of defined enums (always good practice to define this value, for ease of extension by others), and TypeNameProps is nil or a map[string]interface{} of properties, OR:

var KiT_MyEnum = kit.Enums.AddEnumAltLower(MyEnumN, bitFlag true/false,
   TypeNameProps, "Prefix")

which automatically registers alternative names as lower-case versions of const names with given prefix removed -- often what is used in e.g., json or xml kinds of formats.

The resulting type name is registered using a *short* package-qualified version of the type name, with just the last directory name . Type. This is the usual name used in programming Go. All properties are registered using this same short name.

special properties:

* "N": max value of enum defined -- number of enum entries (assuming ordinal, which is all that is currently supported here)

* "BitFlag": true -- each value represents a bit in a set of bit flags, so the string rep of a value contains an or-list of names for each bit set, separated by "|". Use the bitflag package to set and clear bits while keeping the definition of the flags as a standard ordinal integer value -- much more flexible than pre-compiling the bitmasks. Usually should be an int64 type.

* "AltStrings": map[int64]string -- provides an alternative string mapping for the enum values

* "ParType": reflect.Type -- parent type that this extends.

Also recommend defining JSON I/O functions for each registered enum -- much safer to save enums as strings than using their raw numerical values, which can change over time:

func (ev TestFlags) MarshalJSON() ([]byte, error) { return kit.EnumMarshalJSON(ev) }
func (ev *TestFlags) UnmarshalJSON() ([]byte, error) { return kit.EnumUnmarshalJSON(ev) }

And any value that will be used as a key in a map must define Text versions (which don't use quotes)

func (ev TestFlags) MarshalText() ([]byte, error) { return kit.EnumMarshalText(ev) }
func (ev *TestFlags) UnmarshalText() ([]byte, error) { return kit.EnumUnmarshalText(ev) }
var Enums EnumRegistry

Enums is master registry of enum types -- can also create your own package-specific ones

func (*EnumRegistry) AddEnum

func (tr *EnumRegistry) AddEnum(en any, bitFlag bool, props map[string]any) reflect.Type

AddEnum adds a given type to the registry -- requires the N value to set N from and grab type info from -- if bitFlag then sets BitFlag property, and each value represents a bit in a set of bit flags, so the string rep of a value contains an or-list of names for each bit set, separated by | -- can also add additional properties -- they are copied so can be re-used across enums

func (*EnumRegistry) AddEnumAltLower

func (tr *EnumRegistry) AddEnumAltLower(en any, bitFlag bool, props map[string]any, prefix string) reflect.Type

AddEnumAltLower adds a given type to the registry -- requires the N value to set N from and grab type info from -- automatically initializes AltStrings alternative string map based on the name with given prefix removed (e.g., a type name-based prefix) and lower-cased -- also requires the number of enums -- assumes starts at 0

func (*EnumRegistry) AddEnumExt added in v0.9.9

func (tr *EnumRegistry) AddEnumExt(parTyp reflect.Type, en any, bitFlag bool, props map[string]any) reflect.Type

AddEnumExt adds a given type to the registry that extends an existing parTyp enum. Requires the N value to set N from and grab type info from. if bitFlag then sets BitFlag property, and each value represents a bit in a set of bit flags, so the string rep of a value contains an or-list of names for each bit set, separated by | -- can also add additional properties -- they are copied so can be re-used across enums

func (*EnumRegistry) AddEnumExtAltLower added in v0.9.9

func (tr *EnumRegistry) AddEnumExtAltLower(parTyp reflect.Type, en any, bitFlag bool, props map[string]any, prefix string) reflect.Type

AddEnumExtAltLower adds a given type to the registry that extends an existing parTyp enum. Requires the N value to set N from and grab type info from. Automatically initializes AltStrings alternative string map based on the name with given prefix removed (e.g., a type name-based prefix) and lower-cased. Also requires the number of enums -- assumes starts at end of parent.

func (*EnumRegistry) AllTagged

func (tr *EnumRegistry) AllTagged(key string) []reflect.Type

AllTagged returns a list of all registered enum types that include a given property key value -- does not check for the value of that value -- just its existence

func (*EnumRegistry) AltStrings

func (tr *EnumRegistry) AltStrings(enumName string) map[int64]string

AltStrings returns optional alternative string map for enums -- e.g., lower-case, without prefixes etc -- can put multiple such alt strings in the one string with your own separator, in a predefined order, if necessary, and just call strings.Split on those and get the one you want. Uses short package-qualified name. Returns nil if not set.

func (*EnumRegistry) BitFlagsFromStringAltFirst

func (tr *EnumRegistry) BitFlagsFromStringAltFirst(bflg *int64, str string, et reflect.Type, n int) error

BitFlagsFromStringAltFirst sets an int64 of bit flags from a string representation of the bits that are set, using alt-strings first -- gets enum type and n of defined elements directly

func (*EnumRegistry) Enum

func (tr *EnumRegistry) Enum(name string) reflect.Type

Enum finds an enum type based on its *short* package-qualified type name returns nil if not found.

func (*EnumRegistry) EnumIfaceToAltString

func (tr *EnumRegistry) EnumIfaceToAltString(eval any) string

EnumIfaceToAltString converts an enum interface{} value to its corresponding alternative string value from the enum registry

func (*EnumRegistry) EnumInt64ToAltString

func (tr *EnumRegistry) EnumInt64ToAltString(ival int64, typnm string) string

EnumInt64ToAltString converts an int64 value to the enum of given type, and then into corresponding alternative string value

func (*EnumRegistry) IsBitFlag

func (tr *EnumRegistry) IsBitFlag(typ reflect.Type) bool

IsBitFlag checks if this enum is for bit flags instead of mutually-exclusive int values -- checks BitFlag property -- if true string rep of a value contains an or-list of names for each bit set, separated by |

func (*EnumRegistry) NVals

func (tr *EnumRegistry) NVals(eval any) int64

NVals returns the number of defined enum values for given enum interface

func (*EnumRegistry) ParType added in v0.9.9

func (tr *EnumRegistry) ParType(enumName string) reflect.Type

ParType returns optional parent type that given type extends -- nil if not set.

func (*EnumRegistry) Prop

func (tr *EnumRegistry) Prop(enumName, propKey string) any

Prop safely finds an enum type property from short package-qualified name and property key. Returns nil if not found.

func (*EnumRegistry) Properties

func (tr *EnumRegistry) Properties(enumName string) map[string]any

Props returns properties for this type based on short package-qualified name. Makes props map if not already made.

func (*EnumRegistry) SetAnyEnumIfaceFromString

func (tr *EnumRegistry) SetAnyEnumIfaceFromString(eptr any, str string) error

SetAnyEnumIfaceFromString looks up enum type on registry, and if it is registered as a bitflag, sets bits from string, otherwise tries to set from alt strings if those exist, and finally tries direct set from string -- must pass a *pointer* value to the enum item.

func (*EnumRegistry) SetAnyEnumValueFromString

func (tr *EnumRegistry) SetAnyEnumValueFromString(eval reflect.Value, str string) error

SetAnyEnumValueFromString looks up enum type on registry, and if it is registered as a bitflag, sets bits from string, otherwise tries to set from alt strings if those exist, and finally tries direct set from string -- must pass a *pointer* value to the enum item.

func (*EnumRegistry) SetEnumIfaceFromAltString

func (tr *EnumRegistry) SetEnumIfaceFromAltString(eptr any, str string) error

SetEnumIfaceFromAltString sets from alternative string list using an interface{} to the enum -- must pass a *pointer* to the enum item.

func (*EnumRegistry) SetEnumIfaceFromStringAltFirst

func (tr *EnumRegistry) SetEnumIfaceFromStringAltFirst(eptr any, str string) error

SetEnumIfaceFromStringAltFirst first attempts to set an enum from an alternative string, and if that fails, then it tries to set from the regular string representation func (tr *EnumRegistry)

func (*EnumRegistry) SetEnumValueFromAltString

func (tr *EnumRegistry) SetEnumValueFromAltString(eval reflect.Value, str string) error

SetEnumValueFromAltString sets value from alternative string using a reflect.Value -- must pass a *pointer* value to the enum item.

func (*EnumRegistry) SetEnumValueFromStringAltFirst

func (tr *EnumRegistry) SetEnumValueFromStringAltFirst(eval reflect.Value, str string) error

SetEnumValueFromStringAltFirst first attempts to set an enum from an alternative string, and if that fails, then it tries to set from the regular string representation func (tr *EnumRegistry)

func (*EnumRegistry) SetProp added in v0.9.9

func (tr *EnumRegistry) SetProp(enumName, propKey string, val any)

SetProp safely sets given property for given enum name

func (*EnumRegistry) TypeRegistered

func (tr *EnumRegistry) TypeRegistered(typ reflect.Type) bool

TypeRegistered returns true if the given type is registered as an enum type.

func (*EnumRegistry) TypeValues

func (tr *EnumRegistry) TypeValues(et reflect.Type, alt bool) []EnumValue

TypeValues returns an EnumValue slice for all the values of an enum type -- if alt is true and alt names exist, then those are used

func (*EnumRegistry) Values

func (tr *EnumRegistry) Values(enumName string, alt bool) []EnumValue

Values returns an EnumValue slice for all the values of an enum type -- if alt is true and alt names exist, then those are used

type EnumValue

type EnumValue struct {

	// name for this value
	Name string `desc:"name for this value"`

	// integer value
	Value int64 `desc:"integer value"`

	// the enum type that this value belongs to
	Type reflect.Type `desc:"the enum type that this value belongs to"`

	// the comment description of the enum value
	Desc string `desc:"the comment description of the enum value"`
}

EnumValue represents enum values, in common int64 terms, e.g., for GUI

func (*EnumValue) Set

func (ev *EnumValue) Set(name string, val int64, typ reflect.Type, desc string)

Set sets the values of the EnumValue struct

func (EnumValue) String

func (ev EnumValue) String() string

String satisfies fmt.Stringer and provides a string representation of enum: just the name

type TestFlags

type TestFlags int32

TestFlags are for testing -- need the generated string code, so putting in here

const (
	TestFlagsNil TestFlags = iota
	TestFlag1
	TestFlag2
	TestFlagsN
)

func (TestFlags) Desc added in v1.1.16

func (i TestFlags) Desc() string

func (*TestFlags) FromString

func (i *TestFlags) FromString(s string) error

func (TestFlags) MarshalJSON

func (ev TestFlags) MarshalJSON() ([]byte, error)

func (TestFlags) String

func (i TestFlags) String() string

func (*TestFlags) UnmarshalJSON

func (ev *TestFlags) UnmarshalJSON(b []byte) error

type Type

type Type struct {
	T reflect.Type
}

Type provides JSON, XML marshal / unmarshal with encoding of underlying type name using kit.Types type name registry

func (Type) MarshalJSON

func (k Type) MarshalJSON() ([]byte, error)

MarshalJSON saves only the type name

func (Type) MarshalXML

func (k Type) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML saves only the type name

func (Type) ShortTypeName added in v0.9.8

func (k Type) ShortTypeName() string

ShortTypeName returns short package-qualified name of the type: package dir + "." + type name

func (*Type) UnmarshalJSON

func (k *Type) UnmarshalJSON(b []byte) error

UnmarshalJSON loads the type name and looks it up in the Types registry of type names

func (*Type) UnmarshalXML

func (k *Type) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML loads the type name and looks it up in the Types registry of type names

type TypeAndName

type TypeAndName struct {
	Type reflect.Type
	Name string
}

a type and a name -- useful for specifying configurations of children in Ki nodes, and various other use-cases

type TypeAndNameList

type TypeAndNameList []TypeAndName

list of type-and-names -- can be created from a string spec

func (*TypeAndNameList) Add

func (t *TypeAndNameList) Add(typ reflect.Type, nm string)

func (*TypeAndNameList) SetFromString

func (t *TypeAndNameList) SetFromString(str string) error

construct a type-and-name list from a list of type name pairs, space separated -- can include any json-like { } , [ ] formatting which is all stripped away and just the pairs of names are used

type TypeRegistry

type TypeRegistry struct {
	// Types is a map from the *short* package qualified name to reflect.Type
	Types map[string]reflect.Type

	// ShortNames is a map of short package qualified names keyed by
	// the long, fully unambiguous package path qualified name.
	// It is somewhat expensive to compute this short name, so
	// caching it is faster
	ShortNames map[string]string

	// Props are type properties -- nodes can get default properties from
	// their types and then optionally override them with their own settings.
	// The key here is the long, full type name.
	Props map[string]map[string]any

	// Insts contain an instance of each type (the one passed during AddType)
	// The key here is the long, full type name.
	Insts map[string]any
}

TypeRegistry contains several maps where properties of types are maintained for general usage.

See also EnumRegistry for a version specifically for "enum" types (const int types that associate a name with an int value).

Each type must be explicitly registered by calling AddType in an expression that also initializes a new global variable that is then useful whenever you need to specify that type, e.g., when adding a new Node in the Ki system.

var KiT_MyType = ki.Types.AddType(&MyType{}, [props|nil])

where MyType is the type -- note that it is ESSENTIAL to pass a pointer so that the type is considered addressable, even after we get Elem() of it.

props is a map[string]interface{} of optional properties that can be associated with the type -- this is used in the GoGi graphical interface system for example to configure menus and toolbars for different types.

Once registered, the reflect.Type can be looked up via the usual *short* package-qualified type name that you use in programming (e.g., kit.TypeRegistry) -- this is maintained in the Types map. This lookup enables e.g., saving type name information in JSON files and then using that type name to create an object of that type upon loading.

The Props map stores the properties (which can be updated during runtime as well), and Insts also stores an interface{} pointer to each type that has been registered.

var Types TypeRegistry

Types is master registry of types that embed Ki Nodes

func (*TypeRegistry) AddType

func (tr *TypeRegistry) AddType(obj any, props map[string]any) reflect.Type

AddType adds a given type to the registry -- requires an empty object to grab type info from (which is then stored in Insts) -- must be passed as a pointer to ensure that it is an addressable, settable type -- also optional properties that can be associated with the type and accessible e.g. for view-specific properties etc -- these props MUST be specific to this type as they are used directly, not copied!!

func (*TypeRegistry) AllEmbedsOf

func (tr *TypeRegistry) AllEmbedsOf(embed reflect.Type, inclusive, includeBases bool) []reflect.Type

AllEmbedsOf returns a list of all registered types that embed (inherit from in C++ terminology) the given type -- inclusive determines whether the type itself is included in list -- includeBases indicates whether to include types marked with property of base-type -- typically not useful for user-facing type selection

func (*TypeRegistry) AllImplementersOf

func (tr *TypeRegistry) AllImplementersOf(iface reflect.Type, includeBases bool) []reflect.Type

AllImplementersOf returns a list of all registered types that implement the given interface type at any level of embedding -- must pass a type constructed like this: kit.TypeFor[gi.Node2D]() -- includeBases indicates whether to include types marked with property of base-type -- typically not useful for user-facing type selection

func (*TypeRegistry) AllTagged

func (tr *TypeRegistry) AllTagged(key string) []reflect.Type

AllTagged returns a list of all registered types that include a given property key value -- does not check for the value of that value -- just its existence

func (*TypeRegistry) InheritTypeProps added in v0.9.9

func (tr *TypeRegistry) InheritTypeProps(typ reflect.Type) bool

InheritTypeProps attempts to inherit certain heritable type properties from first embedded type. Returns true if did.

func (*TypeRegistry) Init

func (tr *TypeRegistry) Init()

Init initializes the type registry, including adding basic types

func (*TypeRegistry) Inst

func (tr *TypeRegistry) Inst(typ reflect.Type) any

Inst returns the interface{} instance of given type (it is a pointer to that type). Returns nil if not found.

func (*TypeRegistry) InstByName

func (tr *TypeRegistry) InstByName(typeName string) any

InstByName returns the interface{} instance of given type (it is a pointer to that type) using the long, unambiguous package-qualified name. Returns nil if not found.

func (*TypeRegistry) Prop

func (tr *TypeRegistry) Prop(typ reflect.Type, propKey string) (any, bool)

Prop safely finds a type property from type and property key -- returns false if not found.

func (*TypeRegistry) PropByName

func (tr *TypeRegistry) PropByName(typeName, propKey string) (any, bool)

PropByName safely finds a type property from type name (using the long, unambiguous package-qualified name) and property key. Returns false if not found

func (*TypeRegistry) Properties

func (tr *TypeRegistry) Properties(typ reflect.Type, makeNew bool) *map[string]any

Properties returns properties for given type. It optionally makes props map for this type if not already made. Can use this to register properties for types that are not registered.

func (*TypeRegistry) PropsByName

func (tr *TypeRegistry) PropsByName(typeName string, makeNew bool) *map[string]any

PropsByName returns properties for given type name, using the long, unambiguous package-qualified name. It optionally makes props map for this type if not already made. Can use this to register properties for types that are not registered.

func (*TypeRegistry) SetProps

func (tr *TypeRegistry) SetProps(typ reflect.Type, props map[string]any)

SetProps sets the type props for given type, uses write mutex lock

func (*TypeRegistry) Type

func (tr *TypeRegistry) Type(typeName string) reflect.Type

Type returns the reflect.Type based on its *short* package-qualified name (package directory + "." + type -- the version that you use in programming). Returns nil if not registered.

func (*TypeRegistry) TypeName added in v0.9.8

func (tr *TypeRegistry) TypeName(typ reflect.Type) string

TypeName returns the *short* package-qualified type name for given reflect.Type. This is the version that should be used in saving the type to a file, etc. It uses a map for fast results.

Jump to

Keyboard shortcuts

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