Skip to content

Commit

Permalink
Merge pull request #25 from KyberNetwork:feat/hashset
Browse files Browse the repository at this point in the history
feat(prod): ✨ pkg: hashset
  • Loading branch information
thanhpp authored Mar 8, 2024
2 parents 5624862 + 9e87554 commit 16dd3f0
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 0 deletions.
35 changes: 35 additions & 0 deletions pkg/hashset/hashset.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package hashset

import "golang.org/x/exp/maps"

type HashSet[K comparable] struct {
m map[K]struct{}
}

func New[K comparable]() *HashSet[K] {
return &HashSet[K]{
m: map[K]struct{}{},
}
}

func (h *HashSet[K]) Contains(k K) bool {
_, ok := h.m[k]

return ok
}

func (h *HashSet[K]) Add(k K) {
h.m[k] = struct{}{}
}

func (h *HashSet[K]) Remove(k K) {
delete(h.m, k)
}

func (h *HashSet[K]) Size() int {
return len(h.m)
}

func (h *HashSet[K]) Clear() {
maps.Clear(h.m)
}
62 changes: 62 additions & 0 deletions pkg/hashset/hashset_sync.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package hashset

import "sync"

type SyncHashSet[K comparable] struct {
rw sync.RWMutex
s *HashSet[K]
}

func NewSync[K comparable]() *SyncHashSet[K] {
return &SyncHashSet[K]{
rw: sync.RWMutex{},
s: New[K](),
}
}

func (sh *SyncHashSet[K]) Contains(k K) bool {
sh.rw.RLock()
defer sh.rw.RUnlock()

return sh.s.Contains(k)
}

func (sh *SyncHashSet[K]) ContainsOrAdd(k K) (isContains bool) {
sh.rw.Lock()
defer sh.rw.Unlock()
if sh.s.Contains(k) {
return true
}

sh.s.Add(k)

return false
}

func (sh *SyncHashSet[K]) Add(k K) {
sh.rw.Lock()
defer sh.rw.Unlock()

sh.s.Add(k)
}

func (sh *SyncHashSet[K]) Remove(k K) {
sh.rw.Lock()
defer sh.rw.Unlock()

sh.s.Remove(k)
}

func (sh *SyncHashSet[K]) Size() int {
sh.rw.RLock()
defer sh.rw.RUnlock()

return sh.s.Size()
}

func (sh *SyncHashSet[K]) Clear() {
sh.rw.Lock()
defer sh.rw.Unlock()

sh.s.Clear()
}

0 comments on commit 16dd3f0

Please sign in to comment.