Documentation ¶
Overview ¶
Package vars provides the API to parse variables from various input formats/kinds to common key value pair. Or key value pair sets to Variable collections.
Index ¶
- Constants
- Variables
- func AsVariable[VAR VariableIface[VAL], VAL ValueIface](in Variable) VAR
- func ParseKey(str string) (key string, err error)
- type Form
- type GenericVariable
- func (gvar GenericVariable[V]) Any() any
- func (gvar GenericVariable[V]) Bool() bool
- func (gvar GenericVariable[V]) Complex128() complex128
- func (gvar GenericVariable[V]) Complex64() complex64
- func (gvar GenericVariable[V]) Fields() []string
- func (gvar GenericVariable[V]) Float32() float32
- func (gvar GenericVariable[V]) Float64() float64
- func (gvar GenericVariable[V]) Int() int
- func (gvar GenericVariable[V]) Int16() int16
- func (gvar GenericVariable[V]) Int32() int32
- func (gvar GenericVariable[V]) Int64() int64
- func (gvar GenericVariable[V]) Int8() int8
- func (gvar GenericVariable[V]) Len() int
- func (gvar GenericVariable[V]) Name() string
- func (gvar GenericVariable[V]) ReadOnly() bool
- func (gvar GenericVariable[V]) String() string
- func (gvar GenericVariable[V]) Uint() uint
- func (gvar GenericVariable[V]) Uint16() uint16
- func (gvar GenericVariable[V]) Uint32() uint32
- func (gvar GenericVariable[V]) Uint64() uint64
- func (gvar GenericVariable[V]) Uint8() uint8
- func (gvar GenericVariable[V]) Uintptr() uintptr
- func (gvar GenericVariable[V]) Value() V
- type Iter
- type Kind
- type Map
- func (m *Map) All() (all []Variable)
- func (m *Map) Delete(key string)
- func (m *Map) ExtractWithPrefix(prfx string) *Map
- func (m *Map) Get(key string) (v Variable)
- func (m *Map) Has(key string) bool
- func (m *Map) Len() int
- func (m *Map) Load(key string) (v Variable, ok bool)
- func (m *Map) LoadAndDelete(key string) (v Variable, loaded bool)
- func (m *Map) LoadOrDefault(key string, value any) (v Variable, loaded bool)
- func (m *Map) LoadOrStore(key string, value any) (actual Variable, loaded bool)
- func (m *Map) LoadWithPrefix(prfx string) (set *Map, loaded bool)
- func (m *Map) MarshalJSON() ([]byte, error)
- func (m *Map) Range(f func(v Variable) bool)
- func (m *Map) Store(key string, value any) error
- func (m *Map) StoreReadOnly(key string, value any, ro bool) error
- func (m *Map) ToBytes() []byte
- func (m *Map) ToKeyValSlice() []string
- func (m *Map) UnmarshalJSON(data []byte) error
- type NumError
- type Properties
- type Value
- func (v Value) Any() any
- func (v Value) Bool() (bool, error)
- func (v Value) CloneAs(kind Kind) (Value, error)
- func (v Value) Complex128() (complex128, error)
- func (v Value) Complex64() (complex64, error)
- func (v Value) Empty() bool
- func (v Value) Fields() []string
- func (v Value) Float32() (float32, error)
- func (v Value) Float64() (float64, error)
- func (v Value) FormatFloat(fmt byte, prec, bitSize int) string
- func (v Value) FormatInt(base int) string
- func (v Value) FormatUint(base int) string
- func (v Value) Int() (int, error)
- func (v Value) Int16() (int16, error)
- func (v Value) Int32() (int32, error)
- func (v Value) Int64() (int64, error)
- func (v Value) Int8() (int8, error)
- func (v Value) Kind() Kind
- func (v Value) Len() int
- func (v Value) String() string
- func (v Value) Uint() (uint, error)
- func (v Value) Uint16() (uint16, error)
- func (v Value) Uint32() (uint32, error)
- func (v Value) Uint64() (uint64, error)
- func (v Value) Uint8() (uint8, error)
- func (v Value) Uintptr() (uintptr, error)
- type ValueIface
- type Variable
- func EmptyNamedVariable(name string) (Variable, error)
- func New(name string, val any, ro bool) (Variable, error)
- func NewAs(name string, val any, ro bool, kind Kind) (Variable, error)
- func ParseVariableAs(key, val string, ro bool, kind Kind) (Variable, error)
- func ParseVariableFromString(kv string) (Variable, error)
- func (v Variable) Any() any
- func (v Variable) Bool() bool
- func (v Variable) Complex128() complex128
- func (v Variable) Complex64() complex64
- func (v Variable) Empty() bool
- func (v Variable) Fields() []string
- func (v Variable) Float32() float32
- func (v Variable) Float64() float64
- func (v Variable) Int() int
- func (v Variable) Int16() int16
- func (v Variable) Int32() int32
- func (v Variable) Int64() int64
- func (v Variable) Int8() int8
- func (v Variable) Kind() Kind
- func (v Variable) Len() int
- func (v Variable) Name() string
- func (v Variable) ReadOnly() bool
- func (v Variable) String() string
- func (v Variable) Uint() uint
- func (v Variable) Uint16() uint16
- func (v Variable) Uint32() uint32
- func (v Variable) Uint64() uint64
- func (v Variable) Uint8() uint8
- func (v Variable) Uintptr() uintptr
- func (v Variable) Value() Value
- type VariableIface
Examples ¶
Constants ¶
const ( // Version is the Unicode edition from which the tables are derived. Version = "13.0.0" // MaxTransformChunkSize indicates the maximum number of bytes that Transform // may need to write atomically for any Form. Making a destination buffer at // least this size ensures that Transform can always make progress and that // the user does not need to grow the buffer on an ErrShortDst. MaxTransformChunkSize = 35 + maxNonStarters*4 )
const GraphemeJoiner = "\u034F"
GraphemeJoiner is inserted after maxNonStarters non-starter runes.
const MaxSegmentSize = maxByteBufferSize
MaxSegmentSize is the maximum size of a byte buffer needed to consider any sequence of starter and non-starter runes for the purpose of normalization.
Variables ¶
var ( Letter = _L // Letter/L is the set of Unicode letters, category L. L = _L Mark = _M // Mark/M is the set of Unicode mark characters, category M. M = _M Number = _N // Number/N is the set of Unicode number characters, category N. N = _N Punct = _P // Punct/P is the set of Unicode punctuation characters, category P. P = _P Symbol = _S // Symbol/S is the set of Unicode symbol characters, category S. S = _S )
var ( EmptyVariable = Variable{} EmptyValue = Value{} )
var ( ErrReadOnly = errors.New("readonly") // Key errors ErrKey = errors.New("key error") ErrKeyPrefix = fmt.Errorf("%w: key can not start with [0-9]", ErrKey) ErrKeyIsEmpty = fmt.Errorf("%w: key was empty string", ErrKey) ErrKeyHasIllegalChar = fmt.Errorf("%w: key has illegal characters", ErrKey) ErrKeyHasIllegalStarterByte = fmt.Errorf("%w: key has illegal starter byte", ErrKey) ErrKeyHasControlChar = fmt.Errorf("%w: key contains some of unicode control character(s)", ErrKey) ErrKeyNotValidUTF8 = fmt.Errorf("%w: provided key was not valid UTF-8 string", ErrKey) ErrKeyHasNonPrintChar = fmt.Errorf("%w: key contains some of non print character(s)", ErrKey) ErrKeyOutOfRange = fmt.Errorf("%w: key contained utf8 character out of allowed range", ErrKey) // Value errors ErrValue = errors.New("value error") ErrValueInvalid = fmt.Errorf("%w: invalid value", ErrValue) ErrValueConv = fmt.Errorf("%w: failed to convert value", ErrValue) // ErrRange indicates that a value is out of range for the target type. ErrRange = fmt.Errorf("%w: value out of range", ErrValue) // ErrSyntax indicates that a value does not have the right syntax for the target type. ErrSyntax = fmt.Errorf("%w: invalid syntax", ErrValue) )
Functions ¶
func AsVariable ¶
func AsVariable[VAR VariableIface[VAL], VAL ValueIface](in Variable) VAR
Types ¶
type Form ¶
type Form int
A Form denotes a canonical representation of Unicode code points. The Unicode-defined normalization and equivalence forms are:
NFC Unicode Normalization Form C NFD Unicode Normalization Form D NFKC Unicode Normalization Form KC NFKD Unicode Normalization Form KD
For a Form f, this documentation uses the notation f(x) to mean the bytes or string x converted to the given form. A position n in x is called a boundary if conversion to the form can proceed independently on both sides:
f(x) == append(f(x[0:n]), f(x[n:])...)
References: https://unicode.org/reports/tr15/ and https://unicode.org/notes/tn5/.
func (Form) Properties ¶
func (f Form) Properties(s []byte) Properties
Properties returns properties for the first rune in s.
func (Form) PropertiesString ¶
func (f Form) PropertiesString(s string) Properties
PropertiesString returns properties for the first rune in s.
func (Form) QuickSpanString ¶
QuickSpanString returns a boundary n such that s[0:n] == f(s[0:n]). It is not guaranteed to return the largest such n.
type GenericVariable ¶
type GenericVariable[V ValueIface] struct { // contains filtered or unexported fields }
func (GenericVariable[V]) Any ¶
func (gvar GenericVariable[V]) Any() any
func (GenericVariable[V]) Bool ¶
func (gvar GenericVariable[V]) Bool() bool
func (GenericVariable[V]) Complex128 ¶
func (gvar GenericVariable[V]) Complex128() complex128
func (GenericVariable[V]) Complex64 ¶
func (gvar GenericVariable[V]) Complex64() complex64
func (GenericVariable[V]) Fields ¶
func (gvar GenericVariable[V]) Fields() []string
func (GenericVariable[V]) Float32 ¶
func (gvar GenericVariable[V]) Float32() float32
func (GenericVariable[V]) Float64 ¶
func (gvar GenericVariable[V]) Float64() float64
func (GenericVariable[V]) Int ¶
func (gvar GenericVariable[V]) Int() int
func (GenericVariable[V]) Int16 ¶
func (gvar GenericVariable[V]) Int16() int16
func (GenericVariable[V]) Int32 ¶
func (gvar GenericVariable[V]) Int32() int32
func (GenericVariable[V]) Int64 ¶
func (gvar GenericVariable[V]) Int64() int64
func (GenericVariable[V]) Int8 ¶
func (gvar GenericVariable[V]) Int8() int8
func (GenericVariable[V]) Len ¶
func (gvar GenericVariable[V]) Len() int
Len returns the length of the string representation of the Value.
func (GenericVariable[V]) Name ¶
func (gvar GenericVariable[V]) Name() string
func (GenericVariable[V]) ReadOnly ¶
func (gvar GenericVariable[V]) ReadOnly() bool
func (GenericVariable[V]) String ¶
func (gvar GenericVariable[V]) String() string
func (GenericVariable[V]) Uint ¶
func (gvar GenericVariable[V]) Uint() uint
func (GenericVariable[V]) Uint16 ¶
func (gvar GenericVariable[V]) Uint16() uint16
func (GenericVariable[V]) Uint32 ¶
func (gvar GenericVariable[V]) Uint32() uint32
func (GenericVariable[V]) Uint64 ¶
func (gvar GenericVariable[V]) Uint64() uint64
func (GenericVariable[V]) Uint8 ¶
func (gvar GenericVariable[V]) Uint8() uint8
func (GenericVariable[V]) Uintptr ¶
func (gvar GenericVariable[V]) Uintptr() uintptr
func (GenericVariable[V]) Value ¶
func (gvar GenericVariable[V]) Value() V
type Iter ¶
type Iter struct {
// contains filtered or unexported fields
}
An Iter iterates over a string or byte slice, while normalizing it to a given Form.
func (*Iter) InitString ¶
InitString initializes i to iterate over src after normalizing it to Form f.
func (*Iter) Next ¶
Next returns f(i.input[i.Pos():n]), where n is a boundary of i.input. For any input a and b for which f(a) == f(b), subsequent calls to Next will return the same segments. Modifying runes are grouped together with the preceding starter, if such a starter exists. Although not guaranteed, n will typically be the smallest possible n.
type Kind ¶
type Kind uint
A Kind represents the specific kind of kinde that a Value represents. The zero Kind is not a valid kind.
const ( KindInvalid Kind = iota KindBool KindInt KindInt8 KindInt16 KindInt32 KindInt64 KindUint KindUint8 KindUint16 KindUint32 KindUint64 KindUintptr KindFloat32 KindFloat64 KindComplex64 KindComplex128 KindArray KindChan KindFunc KindInterface KindMap KindPointer KindSlice KindString KindStruct KindUnsafePointer )
type Map ¶
type Map struct {
// contains filtered or unexported fields
}
Collection is collection of Variables safe for concurrent use.
Example ¶
package main import ( "fmt" "sort" "github.com/mkungla/happy/pkg/vars" ) func main() { collection, err := vars.ParseMapFromSlice([]string{ "key1=val1", "key2=2", "_key31=true", "_key32=true", "_key33=true", "_key34=true", }) if err != nil { panic("did not expect error: " + err.Error()) } collection.Store("other4", "1.001") set, _ := collection.LoadWithPrefix("_key3") var keys []string set.Range(func(v vars.Variable) bool { keys = append(keys, v.Name()) return true }) sort.Strings(keys) for _, k := range keys { fmt.Println(k) } fmt.Println(collection.Get("other4").Float64()) }
Output: _key31 _key32 _key33 _key34 1.001
Example (Envfile) ¶
package main import ( "fmt" "os" "github.com/mkungla/happy/pkg/vars" ) func main() { content, err := os.ReadFile("testdata/dot_env") if err != nil { fmt.Println(err) return } collection, err := vars.ParseMapFromBytes(content) if err != nil { panic("did not expect error: " + err.Error()) } goarch := collection.Get("GOARCH") fmt.Printf("GOARCH = %s\n", goarch) }
Output: GOARCH = amd64
func ParseMapFromBytes ¶
ParseFromBytes parses []bytes to string, creates []string by new line and calls ParseFromStrings.
func ParseMapFromSlice ¶
ParseKeyValSlice parses variables from any []"key=val" slice and returns Collection.
func (*Map) ExtractWithPrefix ¶
GetWithPrefix return all variables with prefix if any as new Map and strip prefix from keys.
func (*Map) Get ¶
Get retrieves the value of the variable named by the key. It returns the value, which will be empty string if the variable is not set or value was empty.
func (*Map) Load ¶
Load returns the variable stored in the Collection for a key, or EmptyVar if no value is present. The ok result indicates whether variable was found in the Collection.
func (*Map) LoadAndDelete ¶
LoadAndDelete deletes the value for a key, returning the previous value if any. The loaded result reports whether the key was present.
func (*Map) LoadOrDefault ¶
LoadOrDefault returns the existing value for the key if present. Much like LoadOrStore, but second argument willl be returned as Value whithout being stored into Map.
func (*Map) LoadOrStore ¶
LoadOrStore returns the existing value for the key if present. Otherwise, it stores and returns the given value. The loaded result is true if the value was loaded, false if stored.
func (*Map) LoadWithPrefix ¶
LoadWithPrefix return all variables with prefix if any as new Map.
func (*Map) MarshalJSON ¶
func (*Map) Range ¶
Range calls f sequentially for each key and value present in the map. If f returns false, range stops the iteration.
Range does not necessarily correspond to any consistent snapshot of the Map's contents: no key will be visited more than once, but if the value for any key is stored or deleted concurrently, Range may reflect any mapping for that key from any point during the Range call.
Range may be O(N) with the number of elements in the map even if f returns false after a constant number of calls.
func (*Map) Store ¶
Store sets the value for a key. Error is returned when key or value parsing fails or variable is already set and is readonly.
func (*Map) ToKeyValSlice ¶
ToKeyValSlice produces []string slice of strings in format key = "value".
func (*Map) UnmarshalJSON ¶
type NumError ¶
type NumError struct { Func string // the failing function (ParseBool, ParseInt, ParseUint, ParseFloat, ParseComplex) Num string // the input Err error // the reason the conversion failed (e.g. ErrRange, ErrSyntax, etc.) }
A NumError records a failed conversion.
type Properties ¶
type Properties struct {
// contains filtered or unexported fields
}
Properties provides access to normalization properties of a rune.
func (Properties) BoundaryAfter ¶
func (p Properties) BoundaryAfter() bool
BoundaryAfter returns true if runes cannot combine with or otherwise interact with this or previous runes.
func (Properties) BoundaryBefore ¶
func (p Properties) BoundaryBefore() bool
BoundaryBefore returns true if this rune starts a new segment and cannot combine with any rune on the left.
func (Properties) CCC ¶
func (p Properties) CCC() uint8
CCC returns the canonical combining class of the underlying rune.
func (Properties) Decomposition ¶
func (p Properties) Decomposition() []byte
Decomposition returns the decomposition for the underlying rune or nil if there is none.
func (Properties) LeadCCC ¶
func (p Properties) LeadCCC() uint8
LeadCCC returns the CCC of the first rune in the decomposition. If there is no decomposition, LeadCCC equals CCC.
func (Properties) Size ¶
func (p Properties) Size() int
Size returns the length of UTF-8 encoding of the rune.
func (Properties) TrailCCC ¶
func (p Properties) TrailCCC() uint8
TrailCCC returns the CCC of the last rune in the decomposition. If there is no decomposition, TrailCCC equals CCC.
type Value ¶
type Value struct {
// contains filtered or unexported fields
}
Value describes an arbitrary value. When the Kind of the value is detected or forced during parsing, the Value can be typed. All composite types and type alias values are converted into basic types. The Value holds its raw value and cached string representation. Non-basic types that successfully convert into basic types and implement fmt.Stringer will have their string value set to the value returned by val.String().
The Value is not modifiable after it is created and is safe for concurrent use.
Example ¶
package main import ( "fmt" "github.com/mkungla/happy/pkg/vars" ) func main() { vnil, _ := vars.NewValue(nil) fmt.Printf("%t\n", vnil.Kind() == vars.KindInvalid) fmt.Println(vnil.String()) fmt.Println("") v, _ := vars.New("eg", 123456, false) fmt.Printf("%T %t\n", v.Kind(), v.Kind() == vars.KindInt) fmt.Println(v.String()) fmt.Println(v.Any()) fmt.Println(v.Empty()) fmt.Println(v.Len()) fmt.Println(v.Bool()) fmt.Println(v.Int()) fmt.Println(v.Int8()) fmt.Println(v.Int16()) fmt.Println(v.Int32()) fmt.Println(v.Int64()) fmt.Println(v.Uint()) fmt.Println(v.Uint8()) fmt.Println(v.Uint16()) fmt.Println(v.Uint32()) fmt.Println(v.Uint64()) fmt.Println(v.Float32()) fmt.Println(v.Float64()) fmt.Println(v.Complex64()) fmt.Println(v.Complex128()) fmt.Println(v.Uintptr()) fmt.Println(v.Fields()) }
Output: true <nil> vars.Kind true 123456 123456 false 6 false 123456 127 32767 123456 123456 123456 255 65535 123456 123456 123456 123456 (123456+0i) (123456+0i) 123456 [123456]
func (Value) CloneAs ¶
CloneAs takes argument Kind and tries to create new typed value from this value. Error returned would be same as calling NewTypedValue(v.Underlying())
func (Value) Complex128 ¶
func (v Value) Complex128() (complex128, error)
Complex128 returns complex128 representation of the Value.
func (Value) Fields ¶
Fields is like calling strings.Fields on Value.String(). It returns slice of strings (words) found in Value string representation.
func (Value) FormatFloat ¶
FormatFloat converts the floating-point number f to a string, according to the format fmt and precision prec. It rounds the result assuming that the original was obtained from a floating-point value of bitSize bits (32 for float32, 64 for float64).
The format fmt is one of 'b' (-ddddp±ddd, a binary exponent), 'e' (-d.dddde±dd, a decimal exponent), 'E' (-d.ddddE±dd, a decimal exponent), 'f' (-ddd.dddd, no exponent), 'g' ('e' for large exponents, 'f' otherwise), 'G' ('E' for large exponents, 'f' otherwise), 'x' (-0xd.ddddp±ddd, a hexadecimal fraction and binary exponent), or 'X' (-0Xd.ddddP±ddd, a hexadecimal fraction and binary exponent).
The precision prec controls the number of digits (excluding the exponent) printed by the 'e', 'E', 'f', 'g', 'G', 'x', and 'X' formats. For 'e', 'E', 'f', 'x', and 'X', it is the number of digits after the decimal point. For 'g' and 'G' it is the maximum number of significant digits (trailing zeros are removed). The special precision -1 uses the smallest number of digits
func (Value) FormatInt ¶
FormatInt returns the string representation of i in the given base, for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z' for digit values >= 10.
func (Value) FormatUint ¶
FormatUint returns the string representation of i in the given base, for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z' for digit values >= 10.
func (Value) Kind ¶
Kind of value is reporting current Values Kind and may not reflect original underlying values type.
type ValueIface ¶
type ValueIface interface { // String MUST return string value Value String() string // Underlying MUST return original value from what this // Value was created. Any() any Len() int Bool() (bool, error) Int() (int, error) Int8() (int8, error) Int16() (int16, error) Int32() (int32, error) Int64() (int64, error) Uint() (uint, error) Uint8() (uint8, error) Uint16() (uint16, error) Uint32() (uint32, error) Uint64() (uint64, error) Float32() (float32, error) Float64() (float64, error) Complex64() (complex64, error) Complex128() (complex128, error) Uintptr() (uintptr, error) Fields() []string }
ValueIface is minimal interface for Value to implement by thirtparty libraries.
type Variable ¶
type Variable struct {
// contains filtered or unexported fields
}
Variable is read only representation of key val pair.
func EmptyNamedVariable ¶
func New ¶
New parses key and value into Variable. Error is returned when parsing of key or value fails.
func ParseVariableAs ¶
ParseKinddVariable parses variable and returns parser error for given kind if parsing to requested kind fails.
func ParseVariableFromString ¶
ParseVariableFromString parses variable from single key=val pair and returns a Variable if parsing is successful. EmptyVariable and error is returned when parsing fails.
func (Variable) Complex128 ¶
func (v Variable) Complex128() complex128
Complex128 returns complex128 representation of the Value.
func (Variable) ReadOnly ¶
ReadOnly returns true if variable value was marked as readonly when it was created.
type VariableIface ¶
type VariableIface[V ValueIface] interface { Value() V Name() string Len() int ReadOnly() bool String() string Any() any Bool() bool Int() int Int8() int8 Int16() int16 Int32() int32 Int64() int64 Uint() uint Uint8() uint8 Uint16() uint16 Uint32() uint32 Uint64() uint64 Float32() float32 Float64() float64 Complex64() complex64 Complex128() complex128 Uintptr() uintptr Fields() []string }