tpl/strings: Adjust the overflow validation in strings.Repeat
authorBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Sun, 3 Jun 2018 07:35:45 +0000 (10:35 +0300)
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Sun, 3 Jun 2018 07:35:45 +0000 (10:35 +0300)
This now matches the validation in the stdlib, but we return an error instead.

tpl/strings/strings.go
tpl/strings/strings_test.go

index 796b8ff62edc2283b883c94b74dd9c614a063d7b..7bd6a9af04c7805f0d0fa77d87f4b5410f3ad57c 100644 (file)
@@ -17,7 +17,6 @@ import (
        "errors"
        "fmt"
        "html/template"
-       "math"
        _strings "strings"
        "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.
-// The count is limited to an in16 value (up to 32767).
 func (ns *Namespace) Repeat(n, s interface{}) (string, error) {
        ss, err := cast.ToStringE(s)
        if err != nil {
@@ -432,8 +430,10 @@ func (ns *Namespace) Repeat(n, s interface{}) (string, error) {
                return "", err
        }
 
-       if sn > math.MaxInt16 {
-               return "", fmt.Errorf("Cannot repeat string more than %d times", math.MaxInt16)
+       if sn < 0 {
+               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
index bf19ad5621cbefa8d0212e771e9fdb01f2d95504..6f714702ce7ecea2b90ebaa562b8d5398ec46a87 100644 (file)
@@ -730,7 +730,7 @@ func TestRepeat(t *testing.T) {
                // errors
                {"", tstNoStringer{}, false},
                {tstNoStringer{}, "", false},
-               {"hi", math.MaxInt16 + 1, false},
+               {"ab", math.MaxInt64, false},
        } {
                errMsg := fmt.Sprintf("[%d] %v", i, test)