| 1 | package group |
| 2 | |
| 3 | import ( |
| 4 | "sync" |
| 5 | ) |
| 6 | |
| 7 | // groupRegistry is a concurrent map of named groups with |
| 8 | // automatic creation on first access. |
| 9 | type groupRegistry[G any] struct { |
| 10 | groups map[string]G |
| 11 | mu sync.Mutex |
| 12 | } |
| 13 | |
| 14 | func newGroupRegistry[G any]() groupRegistry[G] { |
| 15 | return groupRegistry[G]{ |
| 16 | groups: make(map[string]G), |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | func (r *groupRegistry[G]) getOrCreate(key string, newFn func() G) G { |
| 21 | r.mu.Lock() |
| 22 | defer r.mu.Unlock() |
| 23 | g, ok := r.groups[key] |
| 24 | if !ok { |
| 25 | g = newFn() |
| 26 | r.groups[key] = g |
| 27 | } |
| 28 | return g |
| 29 | } |
| 30 | |
| 31 | func (r *groupRegistry[G]) get(key string) (G, bool) { |
| 32 | r.mu.Lock() |
| 33 | defer r.mu.Unlock() |
| 34 | g, ok := r.groups[key] |
| 35 | return g, ok |
| 36 | } |
| 37 | |
| 38 | // isCurrent returns true if key exists in the registry and matchFn |
| 39 | // returns true for the stored value. |
| 40 | func (r *groupRegistry[G]) isCurrent(key string, matchFn func(G) bool) bool { |
| 41 | r.mu.Lock() |
| 42 | defer r.mu.Unlock() |
| 43 | g, ok := r.groups[key] |
| 44 | return ok && matchFn(g) |
| 45 | } |
| 46 | |
| 47 | // removeIf atomically looks up the group for key, calls fn on it, |
| 48 | // and removes the entry if fn returns true. |
| 49 | func (r *groupRegistry[G]) removeIf(key string, fn func(G) bool) { |
| 50 | r.mu.Lock() |
| 51 | defer r.mu.Unlock() |
| 52 | g, ok := r.groups[key] |
| 53 | if !ok { |
| 54 | return |
| 55 | } |
| 56 | if fn(g) { |
| 57 | delete(r.groups, key) |
| 58 | } |
| 59 | } |