Skip to content

Commit

Permalink
misc
Browse files Browse the repository at this point in the history
  • Loading branch information
gunlee01 committed Feb 20, 2021
1 parent 6af77e8 commit c9c9c23
Showing 1 changed file with 26 additions and 27 deletions.
53 changes: 26 additions & 27 deletions scouterx/common/structure/cacheset/cacheset.go
Original file line number Diff line number Diff line change
@@ -1,78 +1,77 @@
package cacheset

import (
"github.com/emirpasic/gods/lists/singlylinkedlist"
"github.com/emirpasic/gods/sets/linkedhashset"
"strconv"
"sync"
)

var lock sync.RWMutex

type CacheSet struct {
table map[interface{}]struct{}
ordering *singlylinkedlist.List
table *linkedhashset.Set
maxSize int
}

var itemExists = struct{}{}

func New(maxSize int) *CacheSet {
set := &CacheSet{
table: make(map[interface{}]struct{}),
ordering: singlylinkedlist.New(),
maxSize: maxSize,
s := &CacheSet{
table: linkedhashset.New(),
maxSize: maxSize,
}
return set
return s
}

func (set *CacheSet) Add(item interface{}) {
lock.Lock()
defer lock.Unlock()
var contains bool
if _, contains = set.table[item]; !contains {
if !set.table.Contains(item) {
set.removeExceeded()
set.table[item] = itemExists
set.ordering.Append(item)
set.table.Add(item)
}
}

func (set *CacheSet) removeExceeded() {
for set.ordering.Size() >= set.maxSize {
item, exist := set.ordering.Get(0)
if exist {
set.ordering.Remove(0)
delete(set.table, item)
}
removalCount := set.table.Size() - set.maxSize
if removalCount < 0 {
return
}
var removals []interface{}
iterator := set.table.Iterator()

for i := removalCount; i >= 0; i-- {
iterator.Next()
removals = append(removals, iterator.Value())
}
for _, removal := range removals {
set.table.Remove(removal)
}
}

func (set *CacheSet) Contains(item interface{}) bool {
lock.RLock()
defer lock.RUnlock()
if _, contains := set.table[item]; !contains {
return false
}
return true
return set.table.Contains(item)
}

func (set *CacheSet) Empty() bool {
lock.Lock()
defer lock.Unlock()
return set.Size() == 0
return set.table. Size() == 0
}

func (set *CacheSet) Size() int {
return set.ordering.Size()
return set.table.Size()
}

func (set *CacheSet) Clear() {
lock.Lock()
defer lock.Unlock()
set.table = make(map[interface{}]struct{})
set.ordering.Clear()
set.table = linkedhashset.New()
}

func (set *CacheSet) String() string {
return "CacheSet[" + strconv.Itoa(set.ordering.Size()) + "]"
return "CacheSet[" + strconv.Itoa(set.Size()) + "]"
}

0 comments on commit c9c9c23

Please sign in to comment.