code.gitea.io/gitea@v1.22.3/modules/util/truncate.go (about) 1 // Copyright 2021 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package util 5 6 import ( 7 "strings" 8 "unicode/utf8" 9 ) 10 11 // in UTF8 "…" is 3 bytes so doesn't really gain us anything... 12 const ( 13 utf8Ellipsis = "…" 14 asciiEllipsis = "..." 15 ) 16 17 // SplitStringAtByteN splits a string at byte n accounting for rune boundaries. (Combining characters are not accounted for.) 18 func SplitStringAtByteN(input string, n int) (left, right string) { 19 if len(input) <= n { 20 return input, "" 21 } 22 23 if !utf8.ValidString(input) { 24 if n-3 < 0 { 25 return input, "" 26 } 27 return input[:n-3] + asciiEllipsis, asciiEllipsis + input[n-3:] 28 } 29 30 end := 0 31 for end <= n-3 { 32 _, size := utf8.DecodeRuneInString(input[end:]) 33 if end+size > n-3 { 34 break 35 } 36 end += size 37 } 38 39 return input[:end] + utf8Ellipsis, utf8Ellipsis + input[end:] 40 } 41 42 // SplitTrimSpace splits the string at given separator and trims leading and trailing space 43 func SplitTrimSpace(input, sep string) []string { 44 // replace CRLF with LF 45 input = strings.ReplaceAll(input, "\r\n", "\n") 46 47 var stringList []string 48 for _, s := range strings.Split(input, sep) { 49 // trim leading and trailing space 50 stringList = append(stringList, strings.TrimSpace(s)) 51 } 52 53 return stringList 54 }