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.

whowas.go 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright (c) 2012-2014 Jeremy Latt
  2. // released under the MIT license
  3. package irc
  4. type WhoWasList struct {
  5. buffer []*WhoWas
  6. start int
  7. end int
  8. }
  9. type WhoWas struct {
  10. nickname Name
  11. username Name
  12. hostname Name
  13. realname string
  14. }
  15. func NewWhoWasList(size uint) *WhoWasList {
  16. return &WhoWasList{
  17. buffer: make([]*WhoWas, size),
  18. }
  19. }
  20. func (list *WhoWasList) Append(client *Client) {
  21. list.buffer[list.end] = &WhoWas{
  22. nickname: client.Nick(),
  23. username: client.username,
  24. hostname: client.hostname,
  25. realname: client.realname,
  26. }
  27. list.end = (list.end + 1) % len(list.buffer)
  28. if list.end == list.start {
  29. list.start = (list.end + 1) % len(list.buffer)
  30. }
  31. }
  32. func (list *WhoWasList) Find(nickname Name, limit int64) []*WhoWas {
  33. results := make([]*WhoWas, 0)
  34. for whoWas := range list.Each() {
  35. if nickname != whoWas.nickname {
  36. continue
  37. }
  38. results = append(results, whoWas)
  39. if int64(len(results)) >= limit {
  40. break
  41. }
  42. }
  43. return results
  44. }
  45. func (list *WhoWasList) prev(index int) int {
  46. index -= 1
  47. if index < 0 {
  48. index += len(list.buffer)
  49. }
  50. return index
  51. }
  52. // Iterate the buffer in reverse.
  53. func (list *WhoWasList) Each() <-chan *WhoWas {
  54. ch := make(chan *WhoWas)
  55. go func() {
  56. defer close(ch)
  57. if list.start == list.end {
  58. return
  59. }
  60. start := list.prev(list.end)
  61. end := list.prev(list.start)
  62. for start != end {
  63. ch <- list.buffer[start]
  64. start = list.prev(start)
  65. }
  66. }()
  67. return ch
  68. }