tpl: Fix substr when length parameter is zero
authorCameron Moore <moorereason@gmail.com>
Sat, 28 Nov 2020 15:56:49 +0000 (09:56 -0600)
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Tue, 1 Dec 2020 22:20:04 +0000 (23:20 +0100)
When length parameter is zero, always return an empty string.

Updates #7993

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

index 9427d8e8a2dc818bc0eb9ac7b601df885bde34a2..60cb658ba6dc3df10b65baaa0827771d777c8121 100644 (file)
@@ -327,9 +327,12 @@ func (ns *Namespace) Substr(a interface{}, nums ...interface{}) (string, error)
 
        end := rlen
 
-       if length < 0 {
+       switch {
+       case length == 0:
+               return "", nil
+       case length < 0:
                end += length
-       } else if length > 0 {
+       case length > 0:
                end = start + length
        }
 
index bb90200c01dcf8bdd1008d1d1276345fa15858a5..c09bfaf6709f3e3ea3206cd5cc88ac51c15daf0d 100644 (file)
@@ -441,6 +441,9 @@ func TestSubstr(t *testing.T) {
        }{
                {"abc", 1, 2, "bc"},
                {"abc", 0, 1, "a"},
+               {"abcdef", 0, 0, ""},
+               {"abcdef", 1, 0, ""},
+               {"abcdef", -1, 0, ""},
                {"abcdef", -1, 2, "f"},
                {"abcdef", -3, 3, "def"},
                {"abcdef", -1, nil, "f"},
@@ -488,7 +491,7 @@ func TestSubstr(t *testing.T) {
                }
 
                c.Assert(err, qt.IsNil)
-               c.Assert(result, qt.Equals, test.expect, qt.Commentf("%v", test))
+               c.Check(result, qt.Equals, test.expect, qt.Commentf("%v", test))
        }
 
        _, err = ns.Substr("abcdef")