queue icon indicating copy to clipboard operation
queue copied to clipboard

[bug] is full?

Open Jcodelove opened this issue 11 months ago • 5 comments

when initialLen equal capacity

t.Run("TestResetQueue", func(t *testing.T) {
		type strInt struct {
			A int
		}
		queue := fifo.NewBlocking([]*strInt{{A: 1}, {A: 2}, {A: 3}, {A: 4}, {A: 5}}, fifo.WithCapacity(5))

		assert.Equal(t, queue.Offer(&strInt{A: 6}), fifo.ErrQueueIsFull)

		_, err := queue.Get()
		assert.Nil(t, err)
		_, err = queue.Get()
		assert.Nil(t, err)

		targets := queue.Clear()
		queue.Reset()
		for _, item := range targets {
			// is full, can't add back
			err = queue.Offer(item)
			assert.Equal(t, err, fifo.ErrQueueIsFull)
		}
	})

Cannot insert new elements after reset because

// isFull returns true if the queue is full.
func (bq *Blocking[T]) isFull() bool {
	if bq.capacity == nil {
		return false
	}

	return len(bq.elements)-bq.elementsIndex >= *bq.capacity
}

5 - 0 >= 5

Jcodelove avatar Dec 18 '24 02:12 Jcodelove

Hello @Jcodelove,

In your test, you reset the queue(queue.Reset()), which reloads all the initial elements back into it. Since the queue’s capacity is set to 5, matching the number of initial elements, this causes the queue to become full.

Are you expecting a different behavior from the Reset function?

adrianbrad avatar Dec 18 '24 06:12 adrianbrad

I understand the meaning of reset now. I think I need a clear function

Jcodelove avatar Dec 18 '24 06:12 Jcodelove

There is a Clear function available, and you are calling it in the test you provided. It clears the queue, returning all elements it contains, leaving the queue empty.

adrianbrad avatar Dec 18 '24 08:12 adrianbrad

But clear will cause an unlimited increase in bq.elements

Jcodelove avatar Dec 18 '24 08:12 Jcodelove

You are right, I will provide a fix for that

adrianbrad avatar Jan 04 '25 16:01 adrianbrad