Skip to content

Commit

Permalink
Add possibility to use "in" operator with maps and structs.
Browse files Browse the repository at this point in the history
  • Loading branch information
antonmedv committed Aug 21, 2018
1 parent 5404e3f commit 28e2903
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
35 changes: 35 additions & 0 deletions eval_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,26 @@ var evalTests = []evalTest{
nil,
true,
},
{
`"a" in {a:1, b:2}`,
nil,
true,
},
{
`"Bar" in Foo`,
struct{ Foo struct{ Bar bool } }{struct{ Bar bool }{true}},
true,
},
{
`"Bar" in Ptr`,
struct{ Ptr *struct{ Bar bool } }{&struct{ Bar bool }{true}},
true,
},
{
`"Bar" in NilPtr`,
struct{ NilPtr *bool }{nil},
false,
},
{
`0 in nil`,
nil,
Expand Down Expand Up @@ -432,6 +452,21 @@ var evalErrorTests = []evalErrorTest{
nil,
`operator "in" not defined on string`,
},
{
`nil in map`,
map[string]interface{}{"map": map[string]interface{}{"true": "yes"}},
`cannot use <nil> as index to map[string]interface {}`,
},
{
`nil in foo`,
map[string]interface{}{"foo": struct{ Bar bool }{true}},
`cannot use <nil> as field name of struct { Bar bool }`,
},
{
`true in foo`,
map[string]interface{}{"foo": struct{ Bar bool }{true}},
`cannot use bool as field name of struct { Bar bool }`,
},
{
"len()",
nil,
Expand Down
26 changes: 26 additions & 0 deletions runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,32 @@ func contains(needle interface{}, array interface{}) (bool, error) {
}
}
return false, nil
case reflect.Map:
n := reflect.ValueOf(needle)
if !n.IsValid() {
return false, fmt.Errorf("cannot use %T as index to %T", needle, array)
}
value := v.MapIndex(n)
if value.IsValid() {
return true, nil
}
return false, nil
case reflect.Struct:
n := reflect.ValueOf(needle)
if !n.IsValid() || n.Kind() != reflect.String {
return false, fmt.Errorf("cannot use %T as field name of %T", needle, array)
}
value := v.FieldByName(n.String())
if value.IsValid() {
return true, nil
}
return false, nil
case reflect.Ptr:
value := v.Elem()
if value.IsValid() && value.CanInterface() {
return contains(needle, value.Interface())
}
return false, nil
}
return false, fmt.Errorf("operator \"in\" not defined on %T", array)
}
Expand Down

0 comments on commit 28e2903

Please sign in to comment.