github.com/aporeto-inc/trireme-lib@v10.358.0+incompatible/utils/allocator/allocator.go (about) 1 package allocator 2 3 import ( 4 "strconv" 5 ) 6 7 // allocator 8 type allocator struct { 9 allocate chan int 10 } 11 12 // New provides a new allocator 13 func New(start, size int) Allocator { 14 a := &allocator{ 15 allocate: make(chan int, size), 16 } 17 18 for i := start; i < (start + size); i++ { 19 a.allocate <- i 20 } 21 22 return a 23 } 24 25 // Allocate allocates an item 26 func (p *allocator) Allocate() string { 27 return strconv.Itoa(<-p.allocate) 28 } 29 30 // Release releases an item 31 func (p *allocator) Release(item string) { 32 33 // Do not release when the channel is full. These can happen when we resync 34 // stopped containers. 35 if len(p.allocate) == cap(p.allocate) { 36 return 37 } 38 39 intItem, err := strconv.Atoi(item) 40 if err != nil { 41 return 42 } 43 p.allocate <- intItem 44 } 45 46 // AllocateInt allocates an integer. 47 func (p *allocator) AllocateInt() int { 48 return <-p.allocate 49 } 50 51 // ReleaseInt releases an int. 52 func (p *allocator) ReleaseInt(item int) { 53 if len(p.allocate) == cap(p.allocate) || item == 0 { 54 return 55 } 56 57 p.allocate <- item 58 }