github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/karlseguin/ccache/layeredbucket.go (about)

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