github.com/igoogolx/clash@v1.19.8/common/queue/queue.go (about) 1 package queue 2 3 import ( 4 "sync" 5 ) 6 7 // Queue is a simple concurrent safe queue 8 type Queue struct { 9 items []any 10 lock sync.RWMutex 11 } 12 13 // Put add the item to the queue. 14 func (q *Queue) Put(items ...any) { 15 if len(items) == 0 { 16 return 17 } 18 19 q.lock.Lock() 20 q.items = append(q.items, items...) 21 q.lock.Unlock() 22 } 23 24 // Pop returns the head of items. 25 func (q *Queue) Pop() any { 26 if len(q.items) == 0 { 27 return nil 28 } 29 30 q.lock.Lock() 31 head := q.items[0] 32 q.items = q.items[1:] 33 q.lock.Unlock() 34 return head 35 } 36 37 // Last returns the last of item. 38 func (q *Queue) Last() any { 39 if len(q.items) == 0 { 40 return nil 41 } 42 43 q.lock.RLock() 44 last := q.items[len(q.items)-1] 45 q.lock.RUnlock() 46 return last 47 } 48 49 // Copy get the copy of queue. 50 func (q *Queue) Copy() []any { 51 items := []any{} 52 q.lock.RLock() 53 items = append(items, q.items...) 54 q.lock.RUnlock() 55 return items 56 } 57 58 // Len returns the number of items in this queue. 59 func (q *Queue) Len() int64 { 60 q.lock.Lock() 61 defer q.lock.Unlock() 62 63 return int64(len(q.items)) 64 } 65 66 // New is a constructor for a new concurrent safe queue. 67 func New(hint int64) *Queue { 68 return &Queue{ 69 items: make([]any, 0, hint), 70 } 71 }