Skip to content

Commit

Permalink
refactor(xsync): move all sync utilities to xsync
Browse files Browse the repository at this point in the history
  • Loading branch information
tdakkota committed Jul 19, 2024
1 parent db78d4b commit 41a1d54
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
33 changes: 33 additions & 0 deletions internal/xsync/key_once.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package xsync

import "sync"

// KeyOnce return function that calls make only once per key.
func KeyOnce[K comparable, V any](do func(K) V) func(K) V {
state := keyOnceState[K, V]{
onces: map[K]V{},
do: do,
}
return state.Do
}

// keyOnceState is map that does call only once per key.
type keyOnceState[K comparable, V any] struct {
onces map[K]V
oncesMux sync.Mutex

do func(K) V
}

// Do calls [KeyOnce.Make] once per key and returns value.
func (k *keyOnceState[K, V]) Do(key K) V {
k.oncesMux.Lock()
defer k.oncesMux.Unlock()

val, ok := k.onces[key]
if !ok {
val = k.do(key)
k.onces[key] = val
}
return val
}
3 changes: 1 addition & 2 deletions internal/typedpool/typedpool.go → internal/xsync/pool.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
// Package typepool contains generic wrapper around [sync.Pool].
package typedpool
package xsync

import "sync"

Expand Down
2 changes: 2 additions & 0 deletions internal/xsync/xsync.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// Package xsync contains synchronization utilities.
package xsync

0 comments on commit 41a1d54

Please sign in to comment.