-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(xsync): move all sync utilities to
xsync
- Loading branch information
Showing
3 changed files
with
36 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
// Package xsync contains synchronization utilities. | ||
package xsync |