Skip to content

Commit

Permalink
Merge pull request #2 from fleetspace/priority-queue-delete-item-fix
Browse files Browse the repository at this point in the history
Fix Peek to not put the head past the tail
  • Loading branch information
Psykar authored Nov 16, 2024
2 parents 13f4916 + 8365065 commit 52e2ebc
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 3 deletions.
7 changes: 4 additions & 3 deletions priority_queue.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,6 @@ func (pq *PriorityQueue) DequeueByID(priority uint8, id uint64) (*PriorityItem,
}

return item, nil

}

// DequeueItems dequeue's a slice of items inside a transaction so either
Expand All @@ -254,7 +253,9 @@ func (pq *PriorityQueue) DequeueItems(items []*PriorityItem) error {
return err
}
}
return trans.Commit()
ret := trans.Commit()
_, _ = pq.Peek() // update the head
return ret
}

// Peek returns the next item in the priority queue without removing it.
Expand Down Expand Up @@ -538,7 +539,7 @@ func (pq *PriorityQueue) getNextItem() (*PriorityItem, error) {
return result, nil
}
// If we've iterated the whole way through... we have to give up
if pq.levels[pq.curLevel].head > pq.levels[pq.curLevel].tail {
if pq.levels[pq.curLevel].head >= pq.levels[pq.curLevel].tail {
return result, err
}
// This item was deleted, move on to the next one!
Expand Down
47 changes: 47 additions & 0 deletions priority_queue_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1163,6 +1163,53 @@ func TestDequeueItems(t *testing.T) {
}
}

func TestDequeueItemsAll(t *testing.T) {
type Vector struct {
Data string
}
tmpdir, err := ioutil.TempDir("", "testdb")
if err != nil {
t.Error(err)
}

defer os.RemoveAll(tmpdir)

queue, err := OpenPriorityQueue(tmpdir, ASC)
if err != nil {
t.Error(err)
}

item1 := Vector{Data: "1"}
item2 := Vector{Data: "2"}
item3 := Vector{Data: "3"}

saved1, err := queue.EnqueueObject(1, item1)
if err != nil {
t.Error(err)
}
saved2, err := queue.EnqueueObject(1, item2)
if err != nil {
t.Error(err)
}
saved3, err := queue.EnqueueObject(1, item3)
if err != nil {
t.Error(err)
}

if queue.Length() != 3 {
t.Errorf("Expected queue length of 3, got %d", queue.Length())
}

err = queue.DequeueItems([]*PriorityItem{saved1, saved2, saved3})
if err != nil {
t.Error(err)
}

if queue.Length() != 0 {
t.Errorf("Expected queue length of 0, got %d", queue.Length())
}
}

func TestDequeueItemsEmpty(t *testing.T) {
type Vector struct {
Data string
Expand Down

0 comments on commit 52e2ebc

Please sign in to comment.