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.

unicode.go 850B

1234567891011121314151617181920212223242526272829
  1. // Copyright (c) 2021 Shivaram Lingamneni
  2. // Released under the MIT License
  3. package ircmsg
  4. import (
  5. "unicode/utf8"
  6. )
  7. // TruncateUTF8Safe truncates a message, respecting UTF8 boundaries. If a message
  8. // was originally valid UTF8, TruncateUTF8Safe will not make it invalid; instead
  9. // it will truncate additional bytes as needed, back to the last valid
  10. // UTF8-encoded codepoint. If a message is not UTF8, TruncateUTF8Safe will truncate
  11. // at most 3 additional bytes before giving up.
  12. func TruncateUTF8Safe(message string, byteLimit int) (result string) {
  13. if len(message) <= byteLimit {
  14. return message
  15. }
  16. message = message[:byteLimit]
  17. for i := 0; i < (utf8.UTFMax - 1); i++ {
  18. r, n := utf8.DecodeLastRuneInString(message)
  19. if r == utf8.RuneError && n <= 1 {
  20. message = message[:len(message)-1]
  21. } else {
  22. break
  23. }
  24. }
  25. return message
  26. }