Skip to content

Commit a64c8f0

Browse files
committed
Add support for duplicated items
* Implement 'allowDuplicates' flag, while maintaining backwards compatibility. * Add unit test.
1 parent 684bdac commit a64c8f0

File tree

2 files changed

+28
-8
lines changed

2 files changed

+28
-8
lines changed

queue/priority_queue.go

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -105,12 +105,13 @@ func (items *priorityItems) push(item Item) {
105105
// items that implement the Item interface and adds them
106106
// to the queue in priority order.
107107
type PriorityQueue struct {
108-
waiters waiters
109-
items priorityItems
110-
itemMap map[Item]struct{}
111-
lock sync.Mutex
112-
disposeLock sync.Mutex
113-
disposed bool
108+
waiters waiters
109+
items priorityItems
110+
itemMap map[Item]struct{}
111+
lock sync.Mutex
112+
disposeLock sync.Mutex
113+
disposed bool
114+
allowDuplicates bool
114115
}
115116

116117
// Put adds items to the queue.
@@ -126,7 +127,9 @@ func (pq *PriorityQueue) Put(items ...Item) error {
126127
}
127128

128129
for _, item := range items {
129-
if _, ok := pq.itemMap[item]; !ok {
130+
if pq.allowDuplicates {
131+
pq.items.push(item)
132+
} else if _, ok := pq.itemMap[item]; !ok {
130133
pq.itemMap[item] = struct{}{}
131134
pq.items.push(item)
132135
}
@@ -188,7 +191,9 @@ func (pq *PriorityQueue) Get(number int) ([]Item, error) {
188191
pq.disposeLock.Unlock()
189192

190193
items = pq.items.get(number)
191-
deleteItems(items)
194+
if !pq.allowDuplicates {
195+
deleteItems(items)
196+
}
192197
sema.response.Done()
193198
return items, nil
194199
}
@@ -253,6 +258,12 @@ func (pq *PriorityQueue) Dispose() {
253258
pq.waiters = nil
254259
}
255260

261+
// AllowDuplicates determines whether the queue supports
262+
// duplicated items. This setting is false by default.
263+
func (pq *PriorityQueue) AllowDuplicates(allow bool) {
264+
pq.allowDuplicates = allow
265+
}
266+
256267
// NewPriorityQueue is the constructor for a priority queue.
257268
func NewPriorityQueue(hint int) *PriorityQueue {
258269
return &PriorityQueue{

queue/priority_queue_test.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,3 +245,12 @@ func TestInsertDuplicate(t *testing.T) {
245245

246246
assert.Equal(t, 1, q.Len())
247247
}
248+
249+
func TestAllowDuplicates(t *testing.T) {
250+
q := NewPriorityQueue(2)
251+
q.AllowDuplicates(true)
252+
q.Put(mockItem(1))
253+
q.Put(mockItem(1))
254+
255+
assert.Equal(t, 2, q.Len())
256+
}

0 commit comments

Comments
 (0)