Skip to content

Commit

Permalink
text/template: indirect interfaces before slicing
Browse files Browse the repository at this point in the history
The recently added slice function used indirectInterface, but then
forgot to actually call reflect.Value.Slice on its result. Calling the
Slice method on the original Value without indirectInterface would
result in a panic, if our slice was indeed behind an interface.

Fix that, and add test cases for all three built-in functions that work
with slices.

Fixes #36199.

Change-Id: I9a18f4f604a3b29967eefeb573f8960000936b88
Reviewed-on: https://go-review.googlesource.com/c/go/+/211877
Run-TryBot: Daniel Martí <[email protected]>
TryBot-Result: Gobot Gobot <[email protected]>
Reviewed-by: Rob Pike <[email protected]>
  • Loading branch information
mvdan committed Dec 19, 2019
1 parent ba66797 commit 5481a97
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 2 deletions.
3 changes: 3 additions & 0 deletions src/text/template/exec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,7 @@ var execTests = []execTest{
{"map MUI64S", "{{index .MUI64S 3}}", "ui643", tVal, true},
{"map MI8S", "{{index .MI8S 3}}", "i83", tVal, true},
{"map MUI8S", "{{index .MUI8S 2}}", "u82", tVal, true},
{"index of an interface field", "{{index .Empty3 0}}", "7", tVal, true},

// Slicing.
{"slice[:]", "{{slice .SI}}", "[3 4 5]", tVal, true},
Expand All @@ -527,12 +528,14 @@ var execTests = []execTest{
{"string[1:2]", "{{slice .S 1 2}}", "y", tVal, true},
{"out of range", "{{slice .S 1 5}}", "", tVal, false},
{"3-index slice of string", "{{slice .S 1 2 2}}", "", tVal, false},
{"slice of an interface field", "{{slice .Empty3 0 1}}", "[7]", tVal, true},

// Len.
{"slice", "{{len .SI}}", "3", tVal, true},
{"map", "{{len .MSI }}", "3", tVal, true},
{"len of int", "{{len 3}}", "", tVal, false},
{"len of nothing", "{{len .Empty0}}", "", tVal, false},
{"len of an interface field", "{{len .Empty3}}", "2", tVal, true},

// With.
{"with true", "{{with true}}{{.}}{{end}}", "true", tVal, true},
Expand Down
4 changes: 2 additions & 2 deletions src/text/template/funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,13 +264,13 @@ func slice(item reflect.Value, indexes ...reflect.Value) (reflect.Value, error)
return reflect.Value{}, fmt.Errorf("invalid slice index: %d > %d", idx[0], idx[1])
}
if len(indexes) < 3 {
return item.Slice(idx[0], idx[1]), nil
return v.Slice(idx[0], idx[1]), nil
}
// given item[i:j:k], make sure i <= j <= k.
if idx[1] > idx[2] {
return reflect.Value{}, fmt.Errorf("invalid slice index: %d > %d", idx[1], idx[2])
}
return item.Slice3(idx[0], idx[1], idx[2]), nil
return v.Slice3(idx[0], idx[1], idx[2]), nil
}

// Length
Expand Down

0 comments on commit 5481a97

Please sign in to comment.