Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement MarshalJSON for all queues #20

Merged
merged 1 commit into from
Jan 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ repos:
hooks:
- id: commitizen
- repo: https://github.com/golangci/golangci-lint
rev: v1.63.3
rev: v1.63.4
hooks:
- id: golangci-lint
name: golangci-lint
Expand Down
25 changes: 25 additions & 0 deletions blocking.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package queue

import (
"encoding/json"
"fmt"
"sync"
)

Expand Down Expand Up @@ -295,3 +297,26 @@

return elem, nil
}

// MarshalJSON serializes the Blocking queue to JSON.
func (bq *Blocking[T]) MarshalJSON() ([]byte, error) {
bq.lock.RLock()

if bq.IsEmpty() {
bq.lock.RUnlock()
return []byte("[]"), nil
}

Check warning on line 308 in blocking.go

View check run for this annotation

Codecov / codecov/patch

blocking.go#L306-L308

Added lines #L306 - L308 were not covered by tests

// Extract elements from `elements` starting at `elementsIndex`.
elements := bq.elements[bq.elementsIndex:]

bq.lock.RUnlock()

// Marshal the slice of elements into JSON.
data, err := json.Marshal(elements)
if err != nil {
return nil, fmt.Errorf("failed to marshal blocking queue: %w", err)
}

Check warning on line 319 in blocking.go

View check run for this annotation

Codecov / codecov/patch

blocking.go#L318-L319

Added lines #L318 - L319 were not covered by tests

return data, nil
}
20 changes: 20 additions & 0 deletions blocking_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package queue_test

import (
"bytes"
"encoding/json"
"errors"
"fmt"
"reflect"
Expand Down Expand Up @@ -704,6 +706,24 @@ func TestBlocking(t *testing.T) {
}
})
})

t.Run("MarshalJSON", func(t *testing.T) {
t.Parallel()

elems := []int{3, 2, 1}

q := queue.NewBlocking(elems)

marshaled, err := json.Marshal(q)
if err != nil {
t.Fatalf("expected no error, got %v", err)
}

expectedMarshaled := []byte(`[3,2,1]`)
if !bytes.Equal(expectedMarshaled, marshaled) {
t.Fatalf("expected marshaled to be %s, got %s", expectedMarshaled, marshaled)
}
})
}

func testResetOnMultipleRoutinesFunc[T comparable](
Expand Down
23 changes: 23 additions & 0 deletions circular.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package queue

import (
"encoding/json"
"sync"
)

Expand Down Expand Up @@ -231,3 +232,25 @@
func (q *Circular[T]) isEmpty() bool {
return q.size == 0
}

// MarshalJSON serializes the Circular queue to JSON.
func (q *Circular[T]) MarshalJSON() ([]byte, error) {
q.lock.RLock()

if q.isEmpty() {
q.lock.RUnlock()
return []byte("[]"), nil
}

Check warning on line 243 in circular.go

View check run for this annotation

Codecov / codecov/patch

circular.go#L241-L243

Added lines #L241 - L243 were not covered by tests

// Collect elements in logical order from head to tail.
elements := make([]T, 0, q.size)

for i := 0; i < q.size; i++ {
index := (q.head + i) % len(q.elems)
elements = append(elements, q.elems[index])
}

q.lock.RUnlock()

return json.Marshal(elements)
}
20 changes: 20 additions & 0 deletions circular_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package queue_test

import (
"bytes"
"encoding/json"
"errors"
"reflect"
"testing"
Expand Down Expand Up @@ -290,6 +292,24 @@ func TestCircular(t *testing.T) {
t.Fatalf("expected elements to be %v, got %v", elems, iterElems)
}
})

t.Run("MarshalJSON", func(t *testing.T) {
t.Parallel()

elems := []int{3, 2, 1}

q := queue.NewCircular(elems, 4)

marshaled, err := json.Marshal(q)
if err != nil {
t.Fatalf("expected no error, got %v", err)
}

expectedMarshaled := []byte(`[3,2,1]`)
if !bytes.Equal(expectedMarshaled, marshaled) {
t.Fatalf("expected marshaled to be %s, got %s", expectedMarshaled, marshaled)
}
})
}

func BenchmarkCircularQueue(b *testing.B) {
Expand Down
20 changes: 20 additions & 0 deletions linked.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package queue

import (
"encoding/json"
"sync"
)

Expand Down Expand Up @@ -189,3 +190,22 @@ func (lq *Linked[T]) Clear() []T {

return elements
}

// MarshalJSON serializes the Linked queue to JSON.
func (lq *Linked[T]) MarshalJSON() ([]byte, error) {
lq.lock.RLock()
defer lq.lock.RUnlock()

// Traverse the linked list and collect elements.
elements := make([]T, 0, lq.size)

current := lq.head

for current != nil {
elements = append(elements, current.value)
current = current.next
}

// Marshal the elements slice to JSON.
return json.Marshal(elements)
}
20 changes: 20 additions & 0 deletions linked_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package queue_test

import (
"bytes"
"encoding/json"
"errors"
"reflect"
"testing"
Expand Down Expand Up @@ -231,6 +233,24 @@ func TestLinked(t *testing.T) {
t.Fatalf("expected elements to be %v, got %v", elems, iterElems)
}
})

t.Run("MarshalJSON", func(t *testing.T) {
t.Parallel()

elems := []int{3, 2, 1}

q := queue.NewLinked(elems)

marshaled, err := json.Marshal(q)
if err != nil {
t.Fatalf("expected no error, got %v", err)
}

expectedMarshaled := []byte(`[3,2,1]`)
if !bytes.Equal(expectedMarshaled, marshaled) {
t.Fatalf("expected marshaled to be %s, got %s", expectedMarshaled, marshaled)
}
})
}

func BenchmarkLinkedQueue(b *testing.B) {
Expand Down
30 changes: 30 additions & 0 deletions priority.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package queue

import (
"container/heap"
"encoding/json"
"sort"
"sync"
)
Expand Down Expand Up @@ -269,3 +270,32 @@ func (pq *Priority[T]) Size() int {

return pq.elements.Len()
}

// MarshalJSON serializes the Priority queue to JSON.
func (pq *Priority[T]) MarshalJSON() ([]byte, error) {
pq.lock.RLock()

// Create a temporary copy of the heap to extract elements in order.
tempHeap := &priorityHeap[T]{
elems: make([]T, len(pq.elements.elems)),
lessFunc: pq.elements.lessFunc,
}

copy(tempHeap.elems, pq.elements.elems)

pq.lock.RUnlock()

heap.Init(tempHeap)

output := make([]T, len(tempHeap.elems))

i := 0

for tempHeap.Len() > 0 {
// nolint: forcetypeassert, revive
output[i] = tempHeap.Pop().(T)
i++
}

return json.Marshal(output)
}
36 changes: 36 additions & 0 deletions priority_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package queue_test

import (
"bytes"
"encoding/json"
"errors"
"reflect"
"sort"
Expand Down Expand Up @@ -362,6 +364,24 @@ func TestPriority(t *testing.T) {
}
})
})

t.Run("MarshalJSON", func(t *testing.T) {
t.Parallel()

elems := []int{3, 2, 1}

priorityQueue := queue.NewPriority(elems, lessAscending)

marshaled, err := json.Marshal(priorityQueue)
if err != nil {
t.Fatalf("expected no error, got %v", err)
}

expectedMarshaled := []byte(`[3,2,1]`)
if !bytes.Equal(expectedMarshaled, marshaled) {
t.Fatalf("expected marshaled to be %s, got %s", expectedMarshaled, marshaled)
}
})
}

func FuzzPriority(f *testing.F) {
Expand Down Expand Up @@ -411,6 +431,22 @@ func FuzzPriority(f *testing.F) {
}

func BenchmarkPriorityQueue(b *testing.B) {
b.Run("MarshalJSON", func(b *testing.B) {
priorityQueue := queue.NewPriority[int](
[]int{2, 3, 1, 5, 4},
func(elem, otherElem int) bool {
return elem < otherElem
},
)

b.ReportAllocs()
b.ResetTimer()

for i := 0; i <= b.N; i++ {
_, _ = priorityQueue.MarshalJSON()
}
})

b.Run("Peek", func(b *testing.B) {
priorityQueue := queue.NewPriority([]int{1}, func(elem, otherElem int) bool {
return elem < otherElem
Expand Down
Loading