Add iterators for a couple queues.
Some checks failed
Build & Test / Main (push) Failing after 5s

This commit is contained in:
2024-08-22 00:53:48 -07:00
parent d569bb2686
commit 87212466ae
5 changed files with 117 additions and 1 deletions

View File

@@ -24,6 +24,7 @@
package pq
import (
"iter"
"sync"
"gogs.humancabbage.net/sam/priorityq"
@@ -153,3 +154,18 @@ func (s *state[P, T]) TrySend(priority P, value T) error {
s.canRecv.Broadcast()
return nil
}
// Iter returns an iterator that consumes values until the queue is closed.
func (s *state[P, T]) Iter() iter.Seq[T] {
return func(yield func(T) bool) {
for {
_, t, ok := s.Recv()
if !ok {
return
}
if !yield(t) {
return
}
}
}
}

View File

@@ -147,6 +147,30 @@ func TestConcProducerConsumer(t *testing.T) {
wg.Wait()
}
func TestIter(t *testing.T) {
t.Parallel()
q := pq.Make[int, int](4)
q.Send(4, 0)
q.Send(3, 1)
q.Send(2, 2)
q.Send(1, 3)
q.Close()
i := 0
for v := range q.Iter() {
if v != i {
t.Errorf("expected %d, got %d", i, v)
}
i++
}
// to test yield() returning false
q = pq.Make[int, int](4)
q.Send(1, 3)
for _ = range q.Iter() {
break
}
}
func BenchmarkSend(b *testing.B) {
q := pq.Make[int, int](b.N)
// randomize priorities to get amortized cost per op