Implement stringutils.Ellipsis()
This patch implements an Ellipsis utility to append an ellipsis (...) when truncating strings in output. It also fixes the existing Truncate() utility to be compatible with unicode/multibyte characters. Signed-off-by: Sebastiaan van Stijn <github@gone.nl> Upstream-commit: 51dc35cf23a5418e93128854bedc2e59d8ca743a Component: engine
This commit is contained in:
@ -32,12 +32,26 @@ func GenerateRandomASCIIString(n int) string {
|
||||
return string(res)
|
||||
}
|
||||
|
||||
// Truncate truncates a string to maxlen.
|
||||
func Truncate(s string, maxlen int) string {
|
||||
if len(s) <= maxlen {
|
||||
// Ellipsis truncates a string to fit within maxlen, and appends ellipsis (...).
|
||||
// For maxlen of 3 and lower, no ellipsis is appended.
|
||||
func Ellipsis(s string, maxlen int) string {
|
||||
r := []rune(s)
|
||||
if len(r) <= maxlen {
|
||||
return s
|
||||
}
|
||||
return s[:maxlen]
|
||||
if maxlen <= 3 {
|
||||
return string(r[:maxlen])
|
||||
}
|
||||
return string(r[:maxlen-3]) + "..."
|
||||
}
|
||||
|
||||
// Truncate truncates a string to maxlen.
|
||||
func Truncate(s string, maxlen int) string {
|
||||
r := []rune(s)
|
||||
if len(r) <= maxlen {
|
||||
return s
|
||||
}
|
||||
return string(r[:maxlen])
|
||||
}
|
||||
|
||||
// InSlice tests whether a string is contained in a slice of strings or not.
|
||||
|
||||
Reference in New Issue
Block a user