cache.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Used by MessageInput.searchMember to not overflow the gateway with redundent
  2. // search requests.
  3. package cache
  4. import (
  5. "sync"
  6. )
  7. type Cache struct {
  8. items sync.Map
  9. }
  10. func NewCache() *Cache {
  11. return &Cache{items: sync.Map{}}
  12. }
  13. func (c *Cache) Create(query string, value uint) {
  14. c.items.Store(query, value)
  15. }
  16. func (c *Cache) Exists(query string) (ok bool) {
  17. _, ok = c.items.Load(query)
  18. return
  19. }
  20. func (c *Cache) Get(query string) uint {
  21. i, _ := c.items.Load(query)
  22. return i.(uint)
  23. }
  24. // Invalidate is only needed when a member leaves and the search query reaches
  25. // the search limit.
  26. // "aa", "ab", "ac", ..., "ay" // where length is longer than the limit
  27. // if "ay" leaves, then "az" would not be loaded becaue it would not be
  28. // returned by the search results because of the search limit
  29. func (c *Cache) Invalidate(name string, limit uint) {
  30. for name != "" {
  31. if c.Exists(name) && c.Get(name) >= limit {
  32. for name != "" {
  33. c.items.Delete(name)
  34. name = name[:len(name)-1]
  35. }
  36. }
  37. name = name[:len(name)-1]
  38. }
  39. }