trunc.go 579 B

1234567891011121314151617181920212223242526272829303132333435
  1. package common
  2. import (
  3. "unicode/utf8"
  4. "github.com/labring/aiproxy/core/common/conv"
  5. )
  6. func TruncateByRune[T ~string](s T, length int) T {
  7. total := 0
  8. for _, r := range s {
  9. runeLen := utf8.RuneLen(r)
  10. if runeLen == -1 || total+runeLen > length {
  11. return s[:total]
  12. }
  13. total += runeLen
  14. }
  15. return s[:total]
  16. }
  17. func TruncateBytesByRune(b []byte, length int) []byte {
  18. total := 0
  19. for _, r := range conv.BytesToString(b) {
  20. runeLen := utf8.RuneLen(r)
  21. if runeLen == -1 || total+runeLen > length {
  22. return b[:total]
  23. }
  24. total += runeLen
  25. }
  26. return b[:total]
  27. }