Skip to content

Commit

Permalink
tpl: Fix substr when length parameter is zero
Browse files Browse the repository at this point in the history
When length parameter is zero, always get an empty string.

Updates gohugoio#7993
  • Loading branch information
moorereason committed Nov 28, 2020
1 parent 15ee034 commit 1915571
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
7 changes: 5 additions & 2 deletions tpl/strings/strings.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
5 changes: 4 additions & 1 deletion tpl/strings/strings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"},
Expand Down Expand Up @@ -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")
Expand Down

0 comments on commit 1915571

Please sign in to comment.