| 1 |
/* |
| 2 |
Copyright The ORAS Authors. |
| 3 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
you may not use this file except in compliance with the License. |
| 5 |
You may obtain a copy of the License at |
| 6 |
|
| 7 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
|
| 9 |
Unless required by applicable law or agreed to in writing, software |
| 10 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
See the License for the specific language governing permissions and |
| 13 |
limitations under the License. |
| 14 |
*/ |
| 15 |
|
| 16 |
package syncutil |
| 17 |
|
| 18 |
import "sync" |
| 19 |
|
| 20 |
// poolItem represents an item in Pool. |
| 21 |
type poolItem[T any] struct { |
| 22 |
value T |
| 23 |
refCount int |
| 24 |
} |
| 25 |
|
| 26 |
// Pool is a scalable pool with items identified by keys. |
| 27 |
type Pool[T any] struct { |
| 28 |
// New optionally specifies a function to generate a value when Get would |
| 29 |
// otherwise return nil. |
| 30 |
// It may not be changed concurrently with calls to Get. |
| 31 |
New func() T |
| 32 |
|
| 33 |
lock sync.Mutex |
| 34 |
items map[any]*poolItem[T] |
| 35 |
} |
| 36 |
|
| 37 |
// Get gets the value identified by key. |
| 38 |
// The caller should invoke the returned function after using the returned item. |
| 39 |
func (p *Pool[T]) Get(key any) (*T, func()) { |
| 40 |
p.lock.Lock() |
| 41 |
defer p.lock.Unlock() |
| 42 |
|
| 43 |
item, ok := p.items[key] |
| 44 |
if !ok { |
| 45 |
if p.items == nil { |
| 46 |
p.items = make(map[any]*poolItem[T]) |
| 47 |
} |
| 48 |
item = &poolItem[T]{} |
| 49 |
if p.New != nil { |
| 50 |
item.value = p.New() |
| 51 |
} |
| 52 |
p.items[key] = item |
| 53 |
} |
| 54 |
item.refCount++ |
| 55 |
|
| 56 |
return &item.value, func() { |
| 57 |
p.lock.Lock() |
| 58 |
defer p.lock.Unlock() |
| 59 |
item.refCount-- |
| 60 |
if item.refCount <= 0 { |
| 61 |
delete(p.items, key) |
| 62 |
} |
| 63 |
} |
| 64 |
} |