layeredbucket.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package ccache
  2. import (
  3. "sync"
  4. "time"
  5. )
  6. type layeredBucket struct {
  7. sync.RWMutex
  8. buckets map[string]*bucket
  9. }
  10. func (b *layeredBucket) get(primary, secondary string) *Item {
  11. bucket := b.getSecondaryBucket(primary)
  12. if bucket == nil {
  13. return nil
  14. }
  15. return bucket.get(secondary)
  16. }
  17. func (b *layeredBucket) getSecondaryBucket(primary string) *bucket {
  18. b.RLock()
  19. bucket, exists := b.buckets[primary]
  20. b.RUnlock()
  21. if exists == false {
  22. return nil
  23. }
  24. return bucket
  25. }
  26. func (b *layeredBucket) set(primary, secondary string, value interface{}, duration time.Duration) (*Item, *Item) {
  27. b.Lock()
  28. bkt, exists := b.buckets[primary]
  29. if exists == false {
  30. bkt = &bucket{lookup: make(map[string]*Item)}
  31. b.buckets[primary] = bkt
  32. }
  33. b.Unlock()
  34. item, existing := bkt.set(secondary, value, duration)
  35. item.group = primary
  36. return item, existing
  37. }
  38. func (b *layeredBucket) delete(primary, secondary string) *Item {
  39. b.RLock()
  40. bucket, exists := b.buckets[primary]
  41. b.RUnlock()
  42. if exists == false {
  43. return nil
  44. }
  45. return bucket.delete(secondary)
  46. }
  47. func (b *layeredBucket) deleteAll(primary string, deletables chan *Item) bool {
  48. b.RLock()
  49. bucket, exists := b.buckets[primary]
  50. b.RUnlock()
  51. if exists == false {
  52. return false
  53. }
  54. bucket.Lock()
  55. defer bucket.Unlock()
  56. if l := len(bucket.lookup); l == 0 {
  57. return false
  58. }
  59. for key, item := range bucket.lookup {
  60. delete(bucket.lookup, key)
  61. deletables <- item
  62. }
  63. return true
  64. }
  65. func (b *layeredBucket) clear() {
  66. b.Lock()
  67. defer b.Unlock()
  68. for _, bucket := range b.buckets {
  69. bucket.clear()
  70. }
  71. b.buckets = make(map[string]*bucket)
  72. }