Skip to content

Commit

Permalink
tpl: Cast IsSet key to int for indexed types
Browse files Browse the repository at this point in the history
Don't assume that the user sends an int as the key when checking against
indexed types.

Fixes #3681
  • Loading branch information
moorereason authored and bep committed Oct 3, 2018
1 parent d3b81ee commit 0d5110d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 9 deletions.
6 changes: 5 additions & 1 deletion tpl/collections/collections.go
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,11 @@ func (ns *Namespace) IsSet(a interface{}, key interface{}) (bool, error) {

switch av.Kind() {
case reflect.Array, reflect.Chan, reflect.Slice:
if int64(av.Len()) > kv.Int() {
k, err := cast.ToIntE(key)
if err != nil {
return false, fmt.Errorf("isset unable to use key of type %T as index", key)
}
if av.Len() > k {
return true, nil
}
case reflect.Map:
Expand Down
18 changes: 10 additions & 8 deletions tpl/collections/collections_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -438,22 +438,24 @@ func TestIsSet(t *testing.T) {
key interface{}
expect bool
isErr bool
errStr string
}{
{[]interface{}{1, 2, 3, 5}, 2, true, false, ""},
{[]interface{}{1, 2, 3, 5}, 22, false, false, ""},
{[]interface{}{1, 2, 3, 5}, 2, true, false},
{[]interface{}{1, 2, 3, 5}, "2", true, false},
{[]interface{}{1, 2, 3, 5}, 2.0, true, false},

{map[string]interface{}{"a": 1, "b": 2}, "b", true, false, ""},
{map[string]interface{}{"a": 1, "b": 2}, "bc", false, false, ""},
{[]interface{}{1, 2, 3, 5}, 22, false, false},

{time.Now(), "Day", false, false, ""},
{nil, "nil", false, false, ""},
{map[string]interface{}{"a": 1, "b": 2}, "b", true, false},
{map[string]interface{}{"a": 1, "b": 2}, "bc", false, false},

{time.Now(), "Day", false, false},
{nil, "nil", false, false},
{[]interface{}{1, 2, 3, 5}, TstX{}, false, true},
} {
errMsg := fmt.Sprintf("[%d] %v", i, test)

result, err := ns.IsSet(test.a, test.key)
if test.isErr {
assert.EqualError(t, err, test.errStr, errMsg)
continue
}

Expand Down

0 comments on commit 0d5110d

Please sign in to comment.