From a5645d50a70a5663d0671ec5677af3ce392c3ddb Mon Sep 17 00:00:00 2001
From: chrislu <chris.lu@gmail.com>
Date: Sun, 5 May 2024 12:20:08 -0700
Subject: [PATCH] ensure head index is within range

---
 weed/util/buffered_queue/buffered_queue.go | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)

diff --git a/weed/util/buffered_queue/buffered_queue.go b/weed/util/buffered_queue/buffered_queue.go
index 042561cdd..9c65899e9 100644
--- a/weed/util/buffered_queue/buffered_queue.go
+++ b/weed/util/buffered_queue/buffered_queue.go
@@ -95,10 +95,16 @@ func (q *BufferedQueue[T]) Dequeue() (T, bool) {
 		return a, false
 	}
 
+	q.maybeAdjustHeadIndex()
+
 	job := q.head.items[q.head.headIndex]
 	q.head.headIndex++
 	q.count--
 
+	return job, true
+}
+
+func (q *BufferedQueue[T]) maybeAdjustHeadIndex() {
 	if q.head.headIndex == q.chunkSize {
 		q.last.next = q.head
 		q.head = q.head.next
@@ -113,8 +119,6 @@ func (q *BufferedQueue[T]) Dequeue() (T, bool) {
 		//	fmt.Printf("Node: %+v\n", p)
 		//}
 	}
-
-	return job, true
 }
 
 func (q *BufferedQueue[T]) PeekHead() (T, bool) {
@@ -126,6 +130,8 @@ func (q *BufferedQueue[T]) PeekHead() (T, bool) {
 		return a, false
 	}
 
+	q.maybeAdjustHeadIndex()
+
 	job := q.head.items[q.head.headIndex]
 	return job, true
 }