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.

userhost.go 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // written by Daniel Oaks <daniel@danieloaks.net>
  2. // released under the ISC license
  3. package ircmsg
  4. import (
  5. "errors"
  6. "strings"
  7. )
  8. var (
  9. MalformedNUH = errors.New("NUH is malformed")
  10. )
  11. // NUH holds a parsed name!user@host source ("prefix") of an IRC message.
  12. // The Name member will be either a nickname (in the case of a user-initiated
  13. // message) or a server name (in the case of a server-initiated numeric,
  14. // command, or NOTICE).
  15. type NUH struct {
  16. Name string
  17. User string
  18. Host string
  19. }
  20. // ParseNUH parses a NUH source of an IRC message into its constituent parts;
  21. // name (nickname or server name), username, and hostname.
  22. func ParseNUH(in string) (out NUH, err error) {
  23. if len(in) == 0 {
  24. return out, MalformedNUH
  25. }
  26. hostStart := strings.IndexByte(in, '@')
  27. if hostStart != -1 {
  28. out.Host = in[hostStart+1:]
  29. in = in[:hostStart]
  30. }
  31. userStart := strings.IndexByte(in, '!')
  32. if userStart != -1 {
  33. out.User = in[userStart+1:]
  34. in = in[:userStart]
  35. }
  36. out.Name = in
  37. return
  38. }
  39. // Canonical returns the canonical string representation of the NUH.
  40. func (nuh *NUH) Canonical() (result string) {
  41. var out strings.Builder
  42. out.Grow(len(nuh.Name) + len(nuh.User) + len(nuh.Host) + 2)
  43. out.WriteString(nuh.Name)
  44. if len(nuh.User) != 0 {
  45. out.WriteByte('!')
  46. out.WriteString(nuh.User)
  47. }
  48. if len(nuh.Host) != 0 {
  49. out.WriteByte('@')
  50. out.WriteString(nuh.Host)
  51. }
  52. return out.String()
  53. }