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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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 NewWhoWasList(size int) *WhoWasList {
  22. return &WhoWasList{
  23. buffer: make([]WhoWas, size),
  24. start: -1,
  25. end: -1,
  26. }
  27. }
  28. // Append adds an entry to the WhoWasList.
  29. func (list *WhoWasList) Append(whowas WhoWas) {
  30. list.accessMutex.Lock()
  31. defer list.accessMutex.Unlock()
  32. if len(list.buffer) == 0 {
  33. return
  34. }
  35. var pos int
  36. if list.start == -1 { // empty
  37. pos = 0
  38. list.start = 0
  39. list.end = 1
  40. } else if list.start != list.end { // partially full
  41. pos = list.end
  42. list.end = (list.end + 1) % len(list.buffer)
  43. } else if list.start == list.end { // full
  44. pos = list.end
  45. list.end = (list.end + 1) % len(list.buffer)
  46. list.start = list.end // advance start as well, overwriting first entry
  47. }
  48. list.buffer[pos] = whowas
  49. }
  50. // Find tries to find an entry in our WhoWasList with the given details.
  51. func (list *WhoWasList) Find(nickname string, limit int) (results []WhoWas) {
  52. casefoldedNickname, err := CasefoldName(nickname)
  53. if err != nil {
  54. return
  55. }
  56. list.accessMutex.RLock()
  57. defer list.accessMutex.RUnlock()
  58. if list.start == -1 {
  59. return
  60. }
  61. // iterate backwards through the ring buffer
  62. pos := list.prev(list.end)
  63. for limit == 0 || len(results) < limit {
  64. if casefoldedNickname == list.buffer[pos].nickCasefolded {
  65. results = append(results, list.buffer[pos])
  66. }
  67. if pos == list.start {
  68. break
  69. }
  70. pos = list.prev(pos)
  71. }
  72. return
  73. }
  74. func (list *WhoWasList) prev(index int) int {
  75. switch index {
  76. case 0:
  77. return len(list.buffer) - 1
  78. default:
  79. return index - 1
  80. }
  81. }