github.com/network-quality/goresponsiveness@v0.0.0-20240129151524-343954285090/lgc/collection.go (about) 1 /* 2 * This file is part of Go Responsiveness. 3 * 4 * Go Responsiveness is free software: you can redistribute it and/or modify it under 5 * the terms of the GNU General Public License as published by the Free Software Foundation, 6 * either version 2 of the License, or (at your option) any later version. 7 * Go Responsiveness is distributed in the hope that it will be useful, but WITHOUT ANY 8 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 9 * PARTICULAR PURPOSE. See the GNU General Public License for more details. 10 * 11 * You should have received a copy of the GNU General Public License along 12 * with Go Responsiveness. If not, see <https://www.gnu.org/licenses/>. 13 */ 14 15 package lgc 16 17 import ( 18 "fmt" 19 "math/rand" 20 "sync" 21 ) 22 23 type LoadGeneratingConnectionCollection struct { 24 Lock sync.Mutex 25 LGCs *[]LoadGeneratingConnection 26 } 27 28 func NewLoadGeneratingConnectionCollection() LoadGeneratingConnectionCollection { 29 return LoadGeneratingConnectionCollection{LGCs: new([]LoadGeneratingConnection)} 30 } 31 32 func (collection *LoadGeneratingConnectionCollection) Get(idx int) (*LoadGeneratingConnection, error) { 33 if collection.Lock.TryLock() { 34 collection.Lock.Unlock() 35 return nil, fmt.Errorf("collection is unlocked") 36 } 37 return collection.lockedGet(idx) 38 } 39 40 func (collection *LoadGeneratingConnectionCollection) lockedGet(idx int) (*LoadGeneratingConnection, error) { 41 return &(*collection.LGCs)[idx], nil 42 } 43 44 func (collection *LoadGeneratingConnectionCollection) Append(conn LoadGeneratingConnection) error { 45 if collection.Lock.TryLock() { 46 collection.Lock.Unlock() 47 return fmt.Errorf("collection is unlocked") 48 } 49 *collection.LGCs = append(*collection.LGCs, conn) 50 return nil 51 } 52 53 func (collection *LoadGeneratingConnectionCollection) Len() (int, error) { 54 if collection.Lock.TryLock() { 55 collection.Lock.Unlock() 56 return -1, fmt.Errorf("collection is unlocked") 57 } 58 return len(*collection.LGCs), nil 59 } 60 61 func (collection *LoadGeneratingConnectionCollection) GetRandom() (*LoadGeneratingConnection, error) { 62 if collection.Lock.TryLock() { 63 collection.Lock.Unlock() 64 return nil, fmt.Errorf("collection is unlocked") 65 } 66 67 idx := int(rand.Uint32()) 68 idx = idx % len(*collection.LGCs) 69 70 return collection.lockedGet(idx) 71 }