Skip to content

Commit

Permalink
Merge pull request #227 from projectdiscovery/add_synclockmap_ctor_func
Browse files Browse the repository at this point in the history
add SyncLockMap ctor func
  • Loading branch information
Mzack9999 committed Jul 31, 2023
2 parents 2f541e0 + 2cec588 commit 008b0e9
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
24 changes: 24 additions & 0 deletions maps/synclock_map.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,30 @@ type SyncLockMap[K, V comparable] struct {
Map Map[K, V]
}

type SyncLockMapOption[K, V comparable] func(slm *SyncLockMap[K, V])

func WithMap[K, V comparable](m Map[K, V]) SyncLockMapOption[K, V] {
return func(slm *SyncLockMap[K, V]) {
slm.Map = m
}
}

// NewSyncLockMap creates a new SyncLockMap.
// If an existing map is provided, it is used; otherwise, a new map is created.
func NewSyncLockMap[K, V comparable](options ...SyncLockMapOption[K, V]) *SyncLockMap[K, V] {
slm := &SyncLockMap[K, V]{}

for _, option := range options {
option(slm)
}

if slm.Map == nil {
slm.Map = make(Map[K, V])
}

return slm
}

// Lock the current map to read-only mode
func (s *SyncLockMap[K, V]) Lock() {
s.ReadOnly.Store(true)
Expand Down
21 changes: 21 additions & 0 deletions maps/synclock_map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,27 @@ func TestSyncLockMap(t *testing.T) {
},
}

t.Run("Test NewSyncLockMap with map ", func(t *testing.T) {
m := NewSyncLockMap[string, string](WithMap(Map[string, string]{
"key1": "value1",
"key2": "value2",
}))

if !m.Has("key1") || !m.Has("key2") {
t.Error("couldn't init SyncLockMap with NewSyncLockMap")
}
})

t.Run("Test NewSyncLockMap without map", func(t *testing.T) {
m := NewSyncLockMap[string, string]()
_ = m.Set("key1", "value1")
_ = m.Set("key2", "value2")

if !m.Has("key1") || !m.Has("key2") {
t.Error("couldn't init SyncLockMap with NewSyncLockMap")
}
})

t.Run("Test lock", func(t *testing.T) {
m.Lock()
if m.ReadOnly.Load() != true {
Expand Down

0 comments on commit 008b0e9

Please sign in to comment.