github.com/metacubex/gvisor@v0.0.0-20240320004321-933faba989ec/pkg/pool/pool.go (about) 1 // Copyright 2018 The gVisor Authors. 2 // 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 // Package pool provides a trivial integer pool. 16 package pool 17 18 import ( 19 "github.com/metacubex/gvisor/pkg/sync" 20 ) 21 22 // Pool is a simple allocator. 23 type Pool struct { 24 mu sync.Mutex 25 26 // cache is the set of returned values. 27 cache []uint64 28 29 // Start is the starting value (if needed). 30 Start uint64 31 32 // max is the current maximum issued. 33 max uint64 34 35 // Limit is the upper limit. 36 Limit uint64 37 } 38 39 // Get gets a value from the pool. 40 func (p *Pool) Get() (uint64, bool) { 41 p.mu.Lock() 42 defer p.mu.Unlock() 43 44 // Anything cached? 45 if len(p.cache) > 0 { 46 v := p.cache[len(p.cache)-1] 47 p.cache = p.cache[:len(p.cache)-1] 48 return v, true 49 } 50 51 // Over the limit? 52 if p.Start == p.Limit { 53 return 0, false 54 } 55 56 // Generate a new value. 57 v := p.Start 58 p.Start++ 59 return v, true 60 } 61 62 // Put returns a value to the pool. 63 func (p *Pool) Put(v uint64) { 64 p.mu.Lock() 65 p.cache = append(p.cache, v) 66 p.mu.Unlock() 67 }