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.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package util
  4. import "unicode/utf8"
  5. // in UTF8 "…" is 3 bytes so doesn't really gain us anything...
  6. const (
  7. utf8Ellipsis = "…"
  8. asciiEllipsis = "..."
  9. )
  10. // SplitStringAtByteN splits a string at byte n accounting for rune boundaries. (Combining characters are not accounted for.)
  11. func SplitStringAtByteN(input string, n int) (left, right string) {
  12. if len(input) <= n {
  13. return input, ""
  14. }
  15. if !utf8.ValidString(input) {
  16. if n-3 < 0 {
  17. return input, ""
  18. }
  19. return input[:n-3] + asciiEllipsis, asciiEllipsis + input[n-3:]
  20. }
  21. end := 0
  22. for end <= n-3 {
  23. _, size := utf8.DecodeRuneInString(input[end:])
  24. if end+size > n-3 {
  25. break
  26. }
  27. end += size
  28. }
  29. return input[:end] + utf8Ellipsis, utf8Ellipsis + input[end:]
  30. }
  31. // SplitStringAtRuneN splits a string at rune n accounting for rune boundaries. (Combining characters are not accounted for.)
  32. func SplitStringAtRuneN(input string, n int) (left, right string) {
  33. if !utf8.ValidString(input) {
  34. if len(input) <= n || n-3 < 0 {
  35. return input, ""
  36. }
  37. return input[:n-3] + asciiEllipsis, asciiEllipsis + input[n-3:]
  38. }
  39. if utf8.RuneCountInString(input) <= n {
  40. return input, ""
  41. }
  42. count := 0
  43. end := 0
  44. for count < n-1 {
  45. _, size := utf8.DecodeRuneInString(input[end:])
  46. end += size
  47. count++
  48. }
  49. return input[:end] + utf8Ellipsis, utf8Ellipsis + input[end:]
  50. }