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 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright (c) 2012-2014 Jeremy Latt
  2. // Copyright (c) 2016 Daniel Oaks <daniel@danieloaks.net>
  3. // released under the MIT license
  4. package irc
  5. import (
  6. "sync"
  7. )
  8. // WhoWasList holds our list of prior clients (for use with the WHOWAS command).
  9. type WhoWasList struct {
  10. buffer []WhoWas
  11. // three possible states:
  12. // empty: start == end == -1
  13. // partially full: start != end
  14. // full: start == end > 0
  15. // if entries exist, they go from `start` to `(end - 1) % length`
  16. start int
  17. end int
  18. accessMutex sync.RWMutex // tier 1
  19. }
  20. // NewWhoWasList returns a new WhoWasList
  21. func (list *WhoWasList) Initialize(size int) {
  22. list.buffer = make([]WhoWas, size)
  23. list.start = -1
  24. list.end = -1
  25. }
  26. // Append adds an entry to the WhoWasList.
  27. func (list *WhoWasList) Append(whowas WhoWas) {
  28. list.accessMutex.Lock()
  29. defer list.accessMutex.Unlock()
  30. if len(list.buffer) == 0 {
  31. return
  32. }
  33. var pos int
  34. if list.start == -1 { // empty
  35. pos = 0
  36. list.start = 0
  37. list.end = 1
  38. } else if list.start != list.end { // partially full
  39. pos = list.end
  40. list.end = (list.end + 1) % len(list.buffer)
  41. } else if list.start == list.end { // full
  42. pos = list.end
  43. list.end = (list.end + 1) % len(list.buffer)
  44. list.start = list.end // advance start as well, overwriting first entry
  45. }
  46. list.buffer[pos] = whowas
  47. }
  48. // Find tries to find an entry in our WhoWasList with the given details.
  49. func (list *WhoWasList) Find(nickname string, limit int) (results []WhoWas) {
  50. casefoldedNickname, err := CasefoldName(nickname)
  51. if err != nil {
  52. return
  53. }
  54. list.accessMutex.RLock()
  55. defer list.accessMutex.RUnlock()
  56. if list.start == -1 {
  57. return
  58. }
  59. // iterate backwards through the ring buffer
  60. pos := list.prev(list.end)
  61. for limit == 0 || len(results) < limit {
  62. if casefoldedNickname == list.buffer[pos].nickCasefolded {
  63. results = append(results, list.buffer[pos])
  64. }
  65. if pos == list.start {
  66. break
  67. }
  68. pos = list.prev(pos)
  69. }
  70. return
  71. }
  72. func (list *WhoWasList) prev(index int) int {
  73. switch index {
  74. case 0:
  75. return len(list.buffer) - 1
  76. default:
  77. return index - 1
  78. }
  79. }