Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wrap map mutations with mutex lock #81

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions util.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
package posthog

import (
"sync"
)

type SizeLimitedMap struct {
ids map[string][]string
size int
mu sync.Mutex
}

func newSizeLimitedMap(size int) *SizeLimitedMap {
Expand All @@ -15,6 +20,8 @@ func newSizeLimitedMap(size int) *SizeLimitedMap {
}

func (sizeLimitedMap *SizeLimitedMap) add(key string, element string) {
sizeLimitedMap.mu.Lock()
defer sizeLimitedMap.mu.Unlock()

if len(sizeLimitedMap.ids) >= sizeLimitedMap.size {
sizeLimitedMap.ids = map[string][]string{}
Expand All @@ -28,6 +35,9 @@ func (sizeLimitedMap *SizeLimitedMap) add(key string, element string) {
}

func (sizeLimitedMap *SizeLimitedMap) contains(key string, element string) bool {
sizeLimitedMap.mu.Lock()
defer sizeLimitedMap.mu.Unlock()

if val, ok := sizeLimitedMap.ids[key]; ok {
for _, v := range val {
if v == element {
Expand All @@ -40,5 +50,8 @@ func (sizeLimitedMap *SizeLimitedMap) contains(key string, element string) bool
}

func (sizeLimitedMap *SizeLimitedMap) count() int {
sizeLimitedMap.mu.Lock()
defer sizeLimitedMap.mu.Unlock()

return len(sizeLimitedMap.ids)
}