Skip to content

Commit

Permalink
Use context instead of channels for cancellation. (#17)
Browse files Browse the repository at this point in the history
In v1, raw channels are used. Not really a problem, but a new idiom has become popular since this library was originally authored, and this makes the muscle memory easier.

Fixes #7
  • Loading branch information
marstr authored Dec 20, 2021
1 parent ef1382d commit 2ee3f54
Show file tree
Hide file tree
Showing 19 changed files with 130 additions and 145 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Converting between slices and a queryable structure is as trivial as it should b
original := []interface{}{"a", "b", "c"}
subject := collection.AsEnumerable(original...)

for entry := range subject.Enumerate(nil) {
for entry := range subject.Enumerate(context.Background()) {
fmt.Println(entry)
}
// Output:
Expand All @@ -28,7 +28,7 @@ subject := collection.AsEnumerable(1, 2, 3, 4, 5, 6)
filtered := collection.Where(subject, func(num interface{}) bool{
return num.(int) > 3
})
for entry := range filtered.Enumerate(nil) {
for entry := range filtered.Enumerate(context.Background()) {
fmt.Println(entry)
}
// Output:
Expand All @@ -42,7 +42,7 @@ subject := collection.AsEnumerable(1, 2, 3, 4, 5, 6)
updated := collection.Select(subject, func(num interface{}) interface{}{
return num.(int) + 10
})
for entry := range updated.Enumerate(nil) {
for entry := range updated.Enumerate(context.Background()) {
fmt.Println(entry)
}
// Output:
Expand Down
11 changes: 6 additions & 5 deletions dictionary.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package collection

import (
"context"
"sort"
)

Expand Down Expand Up @@ -130,14 +131,14 @@ func (dict Dictionary) Size() int64 {
}

// Enumerate lists each word in the Dictionary alphabetically.
func (dict Dictionary) Enumerate(cancel <-chan struct{}) Enumerator {
func (dict Dictionary) Enumerate(ctx context.Context) Enumerator {
if dict.root == nil {
return Empty.Enumerate(cancel)
return Empty.Enumerate(ctx)
}
return dict.root.Enumerate(cancel)
return dict.root.Enumerate(ctx)
}

func (node trieNode) Enumerate(cancel <-chan struct{}) Enumerator {
func (node trieNode) Enumerate(ctx context.Context) Enumerator {
var enumerateHelper func(trieNode, string)

results := make(chan interface{})
Expand All @@ -146,7 +147,7 @@ func (node trieNode) Enumerate(cancel <-chan struct{}) Enumerator {
if subject.IsWord {
select {
case results <- prefix:
case <-cancel:
case <-ctx.Done():
return
}
}
Expand Down
5 changes: 3 additions & 2 deletions dictionary_examples_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package collection_test

import (
"context"
"fmt"
"strings"

Expand Down Expand Up @@ -54,11 +55,11 @@ func ExampleDictionary_Enumerate() {
return strings.ToUpper(x.(string))
})

for word := range subject.Enumerate(nil) {
for word := range subject.Enumerate(context.Background()) {
fmt.Println(word)
}

for word := range upperCase.Enumerate(nil) {
for word := range upperCase.Enumerate(context.Background()) {
fmt.Println(word)
}

Expand Down
3 changes: 2 additions & 1 deletion dictionary_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package collection

import (
"context"
"strings"
"testing"
)
Expand Down Expand Up @@ -38,7 +39,7 @@ func TestDictionary_Enumerate(t *testing.T) {
}

prev := ""
for result := range subject.Enumerate(nil) {
for result := range subject.Enumerate(context.Background()) {
t.Logf(result.(string))
if alreadySeen, ok := expected[result.(string)]; !ok {
t.Logf("An unadded value was returned")
Expand Down
2 changes: 1 addition & 1 deletion doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
// Location: "./",
// }
//
// results := myDir.Enumerate(nil).Where(func(x interface{}) bool {
// results := myDir.Enumerate(context.Background()).Where(func(x interface{}) bool {
// return strings.HasSuffix(x.(string), ".go")
// })
//
Expand Down
6 changes: 4 additions & 2 deletions fibonacci.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package collection

import "context"

type fibonacciGenerator struct{}

// Fibonacci is an Enumerable which will dynamically generate the fibonacci sequence.
var Fibonacci Enumerable = fibonacciGenerator{}

func (gen fibonacciGenerator) Enumerate(cancel <-chan struct{}) Enumerator {
func (gen fibonacciGenerator) Enumerate(ctx context.Context) Enumerator {
retval := make(chan interface{})

go func() {
Expand All @@ -16,7 +18,7 @@ func (gen fibonacciGenerator) Enumerate(cancel <-chan struct{}) Enumerator {
select {
case retval <- a:
a, b = b, a+b
case <-cancel:
case <-ctx.Done():
return
}
}
Expand Down
8 changes: 4 additions & 4 deletions filesystem.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package collection

import (
"errors"
"context"
"os"
"path/filepath"
)
Expand Down Expand Up @@ -40,7 +40,7 @@ func (d Directory) applyOptions(loc string, info os.FileInfo) bool {
}

// Enumerate lists the items in a `Directory`
func (d Directory) Enumerate(cancel <-chan struct{}) Enumerator {
func (d Directory) Enumerate(ctx context.Context) Enumerator {
results := make(chan interface{})

go func() {
Expand All @@ -64,8 +64,8 @@ func (d Directory) Enumerate(cancel <-chan struct{}) Enumerator {
select {
case results <- currentLocation:
// Intentionally Left Blank
case <-cancel:
err = errors.New("directory enumeration cancelled")
case <-ctx.Done():
err = ctx.Err()
}
}

Expand Down
8 changes: 3 additions & 5 deletions filesystem_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package collection

import (
"context"
"fmt"
"math"
"path"
Expand Down Expand Up @@ -54,9 +55,7 @@ func ExampleDirectory_Enumerate() {
Options: DirectoryOptionsExcludeDirectories,
}

done := make(chan struct{})

filesOfInterest := traverser.Enumerate(done).Select(func(subject interface{}) (result interface{}) {
filesOfInterest := traverser.Enumerate(context.Background()).Select(func(subject interface{}) (result interface{}) {
cast, ok := subject.(string)
if ok {
result = path.Base(cast)
Expand All @@ -75,7 +74,6 @@ func ExampleDirectory_Enumerate() {
for entry := range filesOfInterest {
fmt.Println(entry.(string))
}
close(done)

// Output: filesystem_test.go
}
Expand Down Expand Up @@ -146,7 +144,7 @@ func TestDirectory_Enumerate(t *testing.T) {
for _, tc := range testCases {
subject.Options = tc.options
t.Run(fmt.Sprintf("%d", uint(tc.options)), func(t *testing.T) {
for entry := range subject.Enumerate(nil) {
for entry := range subject.Enumerate(context.Background()) {
cast := entry.(string)
if _, ok := tc.expected[cast]; !ok {
t.Logf("unexpected result: %q", cast)
Expand Down
7 changes: 4 additions & 3 deletions linkedlist.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package collection

import (
"bytes"
"context"
"errors"
"fmt"
"strings"
Expand Down Expand Up @@ -98,7 +99,7 @@ func (list *LinkedList) addNodeFront(node *llNode) {
}

// Enumerate creates a new instance of Enumerable which can be executed on.
func (list *LinkedList) Enumerate(cancel <-chan struct{}) Enumerator {
func (list *LinkedList) Enumerate(ctx context.Context) Enumerator {
retval := make(chan interface{})

go func() {
Expand All @@ -111,7 +112,7 @@ func (list *LinkedList) Enumerate(cancel <-chan struct{}) Enumerator {
select {
case retval <- current.payload:
break
case <-cancel:
case <-ctx.Done():
return
}
current = current.next
Expand Down Expand Up @@ -356,7 +357,7 @@ func (list *LinkedList) moveToFront(node *llNode) {

// ToSlice converts the contents of the LinkedList into a slice.
func (list *LinkedList) ToSlice() []interface{} {
return list.Enumerate(nil).ToSlice()
return list.Enumerate(context.Background()).ToSlice()
}

func findLast(head *llNode) *llNode {
Expand Down
3 changes: 2 additions & 1 deletion linkedlist_examples_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package collection_test

import (
"context"
"fmt"

"github.com/marstr/collection/v2"
Expand All @@ -27,7 +28,7 @@ func ExampleLinkedList_AddBack() {

func ExampleLinkedList_Enumerate() {
subject := collection.NewLinkedList(2, 3, 5, 8)
results := subject.Enumerate(nil).Select(func(a interface{}) interface{} {
results := subject.Enumerate(context.Background()).Select(func(a interface{}) interface{} {
return -1 * a.(int)
})
for entry := range results {
Expand Down
9 changes: 6 additions & 3 deletions linkedlist_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package collection

import "testing"
import (
"context"
"testing"
)

func TestLinkedList_findLast_empty(t *testing.T) {
if result := findLast(nil); result != nil {
Expand Down Expand Up @@ -101,7 +104,7 @@ func TestLinkedList_mergeSort_repair(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.String(), func(t *testing.T) {
originalLength := tc.Length()
originalElements := tc.Enumerate(nil).ToSlice()
originalElements := tc.Enumerate(context.Background()).ToSlice()
originalContents := tc.String()

if err := tc.Sorti(); err != ErrUnexpectedType {
Expand All @@ -116,7 +119,7 @@ func TestLinkedList_mergeSort_repair(t *testing.T) {
t.Fail()
}

remaining := tc.Enumerate(nil).ToSlice()
remaining := tc.Enumerate(context.Background()).ToSlice()

for _, desired := range originalElements {
found := false
Expand Down
5 changes: 3 additions & 2 deletions list.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package collection

import (
"bytes"
"context"
"fmt"
"sync"
)
Expand Down Expand Up @@ -38,7 +39,7 @@ func (l *List) AddAt(pos uint, entries ...interface{}) {
}

// Enumerate lists each element present in the collection
func (l *List) Enumerate(cancel <-chan struct{}) Enumerator {
func (l *List) Enumerate(ctx context.Context) Enumerator {
retval := make(chan interface{})

go func() {
Expand All @@ -50,7 +51,7 @@ func (l *List) Enumerate(cancel <-chan struct{}) Enumerator {
select {
case retval <- entry:
break
case <-cancel:
case <-ctx.Done():
return
}
}
Expand Down
Loading

0 comments on commit 2ee3f54

Please sign in to comment.