From 2ecc837020cb215f834cceec0e2d8a01a92a5e7b Mon Sep 17 00:00:00 2001 From: Matthew Holt Date: Wed, 24 Feb 2016 20:32:26 -0700 Subject: [PATCH] templates: .Truncate can truncate from end of string if length is negative --- middleware/context.go | 12 +++++++++--- middleware/context_test.go | 26 +++++++++++++++++++++++++- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/middleware/context.go b/middleware/context.go index 4b61da290..7cea124eb 100644 --- a/middleware/context.go +++ b/middleware/context.go @@ -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 diff --git a/middleware/context_test.go b/middleware/context_test.go index 5c6473e9e..689c47c13 100644 --- a/middleware/context_test.go +++ b/middleware/context_test.go @@ -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) } } }