You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

truncate.go 1.2KB

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