Mirror of github.com/gissleh/irc
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.

65 lines
1.7 KiB

7 years ago
  1. package ircutil
  2. import (
  3. "bytes"
  4. "unicode/utf8"
  5. )
  6. // MessageOverhead calculates the overhead in a `PRIVMSG` sent by a client
  7. // with the given nick, user, host and target name. A `NOTICE` is shorter, so
  8. // it is safe to use the same function for it.
  9. func MessageOverhead(nick, user, host, target string, action bool) int {
  10. template := ":!@ PRIVMSG :"
  11. if action {
  12. template += "\x01ACTION \x01"
  13. }
  14. return len(template) + len(nick) + len(user) + len(host) + len(target)
  15. }
  16. // CutMessage returns cuts of the message with the given overhead. If there
  17. // there are tokens longer than the cutLength, it will call CutMessageNoSpace
  18. // instead.
  19. func CutMessage(text string, overhead int) []string {
  20. tokens := bytes.Split([]byte(text), []byte{' '})
  21. cutLength := 510 - overhead
  22. for _, token := range tokens {
  23. if len(token) >= cutLength {
  24. return CutMessageNoSpace(text, overhead)
  25. }
  26. }
  27. result := make([]string, 0, (len(text)/(cutLength))+1)
  28. current := make([]byte, 0, cutLength)
  29. for _, token := range tokens {
  30. if (len(current) + 1 + len(token)) > cutLength {
  31. result = append(result, string(current))
  32. current = current[:0]
  33. }
  34. if len(current) > 0 {
  35. current = append(current, ' ')
  36. }
  37. current = append(current, token...)
  38. }
  39. return append(result, string(current))
  40. }
  41. // CutMessageNoSpace cuts the messages per utf-8 rune.
  42. func CutMessageNoSpace(text string, overhead int) []string {
  43. cutLength := 510 - overhead
  44. result := make([]string, 0, (len(text)/(cutLength))+1)
  45. current := ""
  46. for _, r := range text {
  47. if len(current)+utf8.RuneLen(r) > cutLength {
  48. result = append(result, current)
  49. current = ""
  50. }
  51. current += string(r)
  52. }
  53. return append(result, current)
  54. }