Skip to content

Commit

Permalink
reflect utils
Browse files Browse the repository at this point in the history
Signed-off-by: Charles-Edouard Brétéché <[email protected]>
  • Loading branch information
eddycharly committed Oct 1, 2023
1 parent 2cbdde9 commit 21b0251
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 0 deletions.
12 changes: 12 additions & 0 deletions pkg/utils/reflect/kind.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package reflect

import (
"reflect"
)

func GetKind(value interface{}) reflect.Kind {
if value == nil {
return reflect.Invalid
}
return reflect.TypeOf(value).Kind()
}
42 changes: 42 additions & 0 deletions pkg/utils/reflect/match.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package reflect

import (
"fmt"
"reflect"
)

func MatchScalar(expected, actual interface{}) (bool, error) {
if actual == nil && expected == nil {
return true, nil
}
if actual == expected {
return true, nil
}
// if they are the same type we can use reflect.DeepEqual
if reflect.TypeOf(expected) == reflect.TypeOf(actual) {
return reflect.DeepEqual(expected, actual), nil
}
e := reflect.ValueOf(expected)
a := reflect.ValueOf(actual)
if !a.IsValid() && !e.IsValid() {
return true, nil
}
if a.CanComplex() && e.CanComplex() {
return a.Complex() == e.Complex(), nil
}
if a.CanFloat() && e.CanFloat() {
return a.Float() == e.Float(), nil
}
if a.CanInt() && e.CanInt() {
return a.Int() == e.Int(), nil
}
if a.CanUint() && e.CanUint() {
return a.Uint() == e.Uint(), nil
}
if a, ok := ToNumber(a); ok {
if e, ok := ToNumber(e); ok {
return a == e, nil
}
}
return false, fmt.Errorf("types are not comparable, %s - %s", GetKind(expected), GetKind(actual))
}
18 changes: 18 additions & 0 deletions pkg/utils/reflect/number.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package reflect

import (
"reflect"
)

func ToNumber(value reflect.Value) (float64, bool) {
if value.CanFloat() {
return value.Float(), true
}
if value.CanInt() {
return float64(value.Int()), true
}
if value.CanUint() {
return float64(value.Uint()), true
}
return 0, false
}

0 comments on commit 21b0251

Please sign in to comment.