mirror of
https://github.com/caddyserver/caddy.git
synced 2025-01-20 10:43:15 +08:00
templates: .Truncate can truncate from end of string if length is negative
This commit is contained in:
parent
c37ad7f677
commit
2ecc837020
|
@ -132,10 +132,16 @@ func (c Context) PathMatches(pattern string) bool {
|
|||
return Path(c.Req.URL.Path).Matches(pattern)
|
||||
}
|
||||
|
||||
// Truncate truncates the input string to the given length. If
|
||||
// input is shorter than length, the entire string is returned.
|
||||
// Truncate truncates the input string to the given length.
|
||||
// If length is negative, it returns that many characters
|
||||
// starting from the end of the string. If the absolute value
|
||||
// of length is greater than len(input), the whole input is
|
||||
// returned.
|
||||
func (c Context) Truncate(input string, length int) string {
|
||||
if len(input) > length {
|
||||
if length < 0 && len(input)+length > 0 {
|
||||
return input[len(input)+length:]
|
||||
}
|
||||
if length >= 0 && len(input) > length {
|
||||
return input[:length]
|
||||
}
|
||||
return input
|
||||
|
|
|
@ -459,12 +459,36 @@ func TestTruncate(t *testing.T) {
|
|||
inputLength: 10,
|
||||
expected: "string",
|
||||
},
|
||||
// Test 3 - zero length
|
||||
{
|
||||
inputString: "string",
|
||||
inputLength: 0,
|
||||
expected: "",
|
||||
},
|
||||
// Test 4 - negative, smaller length
|
||||
{
|
||||
inputString: "string",
|
||||
inputLength: -5,
|
||||
expected: "tring",
|
||||
},
|
||||
// Test 5 - negative, exact length
|
||||
{
|
||||
inputString: "string",
|
||||
inputLength: -6,
|
||||
expected: "string",
|
||||
},
|
||||
// Test 6 - negative, bigger length
|
||||
{
|
||||
inputString: "string",
|
||||
inputLength: -7,
|
||||
expected: "string",
|
||||
},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
actual := context.Truncate(test.inputString, test.inputLength)
|
||||
if actual != test.expected {
|
||||
t.Errorf(getTestPrefix(i)+"Expected %s, found %s. Input was Truncate(%q, %d)", test.expected, actual, test.inputString, test.inputLength)
|
||||
t.Errorf(getTestPrefix(i)+"Expected '%s', found '%s'. Input was Truncate(%q, %d)", test.expected, actual, test.inputString, test.inputLength)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user