kit

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2018 License: BSD-3-Clause Imports: 18 Imported by: 0

README

kit

Go Report Card GoDoc

Package `kit1 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.

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

This section is empty.

Variables

View Source
var KiT_TestFlags = Enums.AddEnumAltLower(TestFlagsN, false, nil, "Test")
View Source
var ShortTypeNames = true

if ShortTypeNames is true, we just use the standard "base".TypeName instead of the full path that PgkPath returns -- this should work unless there are conflicts but the savings in JSON files etc is probably worth it..

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 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 interface{}) 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 interface{}) 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 interface{}) 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 Embed

func Embed(stru interface{}, embed reflect.Type) interface{}

Embed returns the embedded struct of given type within given struct

func EmbeddedTypeImplements

func EmbeddedTypeImplements(typ, iface reflect.Type) bool

EmbeddedTypeImplements 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()

func EnumIfaceFromInt64

func EnumIfaceFromInt64(ival int64, typ reflect.Type) interface{}

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) interface{}

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 interface{}) 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 interface{}) 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 interface{}) ([]byte, error)

func EnumMarshalText

func EnumMarshalText(eval interface{}) ([]byte, error)

func EnumUnmarshalJSON

func EnumUnmarshalJSON(eval interface{}, b []byte) error

func EnumUnmarshalText

func EnumUnmarshalText(eval interface{}, 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 interface{}, 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 interface{}, nm string) interface{}

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 interface{}) []interface{}

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 interface{}) []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 interface{}, 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 interface{}, fun func(stru interface{}, 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 FullTypeName

func FullTypeName(typ reflect.Type) string

FullTypeName returns the full package-qualified type name -- this is what is used for encoding type names in the registry

func GoSrcDir

func GoSrcDir(dir string) (absDir string, err error)

GoSrcDir tries to locate dir in GOPATH/src/ or GOROOT/src/pkg/ and returns its full path. GOPATH may contain a list of paths. From Robin Elkind github.com/mewkiz/pkg

func IfaceIsNil

func IfaceIsNil(it interface{}) 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

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 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 interface{})

MapAdd adds a new blank entry to the map

func MapDelete

func MapDelete(mv interface{}, key interface{})

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

func MapDeleteValue

func MapDeleteValue(mv interface{}, 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 interface{}) int

MapElsN returns number of elemental fields in given map type

func MapElsValueFun

func MapElsValueFun(mp interface{}, fun func(mp interface{}, 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 interface{}) 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 interface{}, 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 interface{}) int

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

func MapStructElsValueFun

func MapStructElsValueFun(mp interface{}, fun func(mp interface{}, 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 interface{}) 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 interface{}) interface{}

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 interface{}) interface{}

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 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 interface{}) interface{}

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 ...interface{}) []interface{}

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 interface{}, 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 interface{}, 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 StringToTypeName 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 StringToTypeName method

func SetRobust

func SetRobust(to, from interface{}) bool

SetRobust robustly sets the to value from the from value -- to must be a pointer-to -- only for basic field values -- use copier package for more complex cases

func SetTypeProp

func SetTypeProp(props map[string]interface{}, key string, val interface{})

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

func SliceDeleteAt

func SliceDeleteAt(sl interface{}, idx int)

SliceDeleteAt deletes element at given index from slice

func SliceElType

func SliceElType(sl interface{}) 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.

func SliceNewAt

func SliceNewAt(sl interface{}, idx int)

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

func SliceSort

func SliceSort(sl interface{}, 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

stringer interface

func StructSliceSort

func StructSliceSort(struSlice interface{}, 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 interface{}) (bool, bool)

ToBool robustly converts anything to a bool

func ToFloat

func ToFloat(it interface{}) (float64, bool)

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

func ToFloat32

func ToFloat32(it interface{}) (float32, bool)

ToFloat32 robustly converts anything to a Float64 -- uses the floats.Floater Float() interface first if available

func ToInt

func ToInt(it interface{}) (int64, bool)

ToInt robustlys converts anything to an int64 -- uses the ints.Inter ToInt interface first if available

func ToString

func ToString(it interface{}) 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

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 TypeProp

func TypeProp(props map[string]interface{}, key string) (interface{}, 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 foo, 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 EnumRegistry

type EnumRegistry struct {
	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
	Props map[string]map[string]interface{}
	// Vals contains cached EnumValue representations of the enum values -- used by EnumValues 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 -- need to explicitly register each new type by calling AddEnum in the process of creating a new global variable, as in:

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

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

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 interface{}, bitFlag bool, props map[string]interface{}) 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 interface{}, bitFlag bool, props map[string]interface{}, 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) 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 -- 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 type name -- returns nil if not found

func (*EnumRegistry) EnumIfaceToAltString

func (tr *EnumRegistry) EnumIfaceToAltString(eval interface{}) 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 interface{}) int64

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

func (*EnumRegistry) Prop

func (tr *EnumRegistry) Prop(enumName, propKey string) interface{}

Prop safely finds an enum type property from enum type name and property key -- nil if not found

func (*EnumRegistry) Properties

func (tr *EnumRegistry) Properties(enumName string) map[string]interface{}

Props returns properties for this type -- makes props map if not already made

func (*EnumRegistry) SetAnyEnumIfaceFromString

func (tr *EnumRegistry) SetAnyEnumIfaceFromString(eptr interface{}, 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 interface{}, 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 interface{}, 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) 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  string       `desc:"name for this value"`
	Value int64        `desc:"integer value"`
	Type  reflect.Type `desc:"the enum type that this value belongs to"`
}

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)

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

testing

const (
	TestFlagsNil TestFlags = iota
	TestFlag1
	TestFlag2
	TestFlagsN
)

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) FullTypeName

func (k Type) FullTypeName() string

the full name of the type: package name + "." + type name

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) 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 name to reflect.Type
	Types map[string]reflect.Type

	// Props are type properties -- nodes can get default properties from
	// their types and then optionally override them with their own settings
	Props map[string]map[string]interface{}

	// Insts contain an instance of each type (the one passed during AddType)
	Insts map[string]interface{}
}

TypeRegistry is a map from type name (package path + "." + type name) to reflect.Type -- need to explicitly register each new type by calling AddType in the process of creating a new global variable, as in:

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

where TypeName is the name of 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 color objects of different types using the background-color property.

var Types TypeRegistry

Types is master registry of types that embed Ki Nodes

func (*TypeRegistry) AddType

func (tr *TypeRegistry) AddType(obj interface{}, props map[string]interface{}) 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: reflect.TypeOf((*gi.Node2D)(nil)).Elem() -- 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) Init

func (tr *TypeRegistry) Init()

Init initializes the type registry, including adding basic types

func (*TypeRegistry) Inst

func (tr *TypeRegistry) Inst(typ reflect.Type) interface{}

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) interface{}

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

func (*TypeRegistry) Prop

func (tr *TypeRegistry) Prop(typ reflect.Type, propKey string) (interface{}, 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) (interface{}, bool)

PropByName safely finds a type property from type name and property key -- returns false if not found

func (*TypeRegistry) Properties

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

Properties returns properties for given type -- optionally makes props map 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]interface{}

PropsByName returns properties for given type name -- optionally makes props map 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]interface{})

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 name (package path + "." + type name) -- returns nil if not found

Jump to

Keyboard shortcuts

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