tpl/strings: Adjust the overflow validation in strings.Repeat

This now matches the validation in the stdlib, but we return an error instead.
This commit is contained in:
Bjørn Erik Pedersen 2018-06-03 10:35:45 +03:00
parent 13435a6f60
commit 90c7749085
No known key found for this signature in database
GPG key ID: 330E6E2BD4859D8F
2 changed files with 5 additions and 5 deletions

View file

@ -17,7 +17,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"html/template" "html/template"
"math"
_strings "strings" _strings "strings"
"unicode/utf8" "unicode/utf8"
@ -420,7 +419,6 @@ func (ns *Namespace) TrimSuffix(suffix, s interface{}) (string, error) {
} }
// Repeat returns a new string consisting of count copies of the string s. // Repeat returns a new string consisting of count copies of the string s.
// The count is limited to an in16 value (up to 32767).
func (ns *Namespace) Repeat(n, s interface{}) (string, error) { func (ns *Namespace) Repeat(n, s interface{}) (string, error) {
ss, err := cast.ToStringE(s) ss, err := cast.ToStringE(s)
if err != nil { if err != nil {
@ -432,8 +430,10 @@ func (ns *Namespace) Repeat(n, s interface{}) (string, error) {
return "", err return "", err
} }
if sn > math.MaxInt16 { if sn < 0 {
return "", fmt.Errorf("Cannot repeat string more than %d times", math.MaxInt16) return "", errors.New("strings: negative Repeat count")
} else if sn > 0 && len(ss)*sn/sn != len(ss) {
return "", errors.New("strings: Repeat count causes overflow")
} }
return _strings.Repeat(ss, sn), nil return _strings.Repeat(ss, sn), nil

View file

@ -730,7 +730,7 @@ func TestRepeat(t *testing.T) {
// errors // errors
{"", tstNoStringer{}, false}, {"", tstNoStringer{}, false},
{tstNoStringer{}, "", false}, {tstNoStringer{}, "", false},
{"hi", math.MaxInt16 + 1, false}, {"ab", math.MaxInt64, false},
} { } {
errMsg := fmt.Sprintf("[%d] %v", i, test) errMsg := fmt.Sprintf("[%d] %v", i, test)