cache.go 1.0 KB

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