Skip to content

Commit

Permalink
fix: Cancellation of slowsort
Browse files Browse the repository at this point in the history
Cancellation signal wasn't propagated from recursive calls of function,
so in most cases cancellation didn't affect slowsort.

The error was detected by <https://github.com/kisielk/errcheck>.
  • Loading branch information
macie committed Sep 8, 2024
1 parent 4d57843 commit 68d5df7
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
12 changes: 9 additions & 3 deletions slowsort.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,19 @@ func slowsort[S ~[]E, E any](ctx context.Context, x S, i int, j int, cmp func(a,
}

mid := int(math.Floor(float64(i+j) / 2))
slowsort(ctx, x, i, mid, cmp)
slowsort(ctx, x, mid+1, j, cmp)
if err := slowsort(ctx, x, i, mid, cmp); err != nil {
return err
}
if err := slowsort(ctx, x, mid+1, j, cmp); err != nil {
return err
}
if cmp(x[j], x[mid]) == -1 {
x[mid], x[j] = x[j], x[mid]
}

slowsort(ctx, x, i, j-1, cmp)
if err := slowsort(ctx, x, i, j-1, cmp); err != nil {
return err
}
}

return nil
Expand Down
18 changes: 18 additions & 0 deletions slowsort_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"math"
"slices"
"testing"
"time"
)

func TestSlowsortFloat(t *testing.T) {
Expand Down Expand Up @@ -87,3 +88,20 @@ func TestSlowsortString(t *testing.T) {
})
}
}

func TestSlowsortCancellation(t *testing.T) {
const testCaseSize = 10000
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel()
tc := make([]int, testCaseSize)
want := make([]int, testCaseSize)
for i := 0; i < testCaseSize; i++ {
tc[i] = testCaseSize - i
want[i] = i
}

err := Slowsort(ctx, tc)
if err != context.DeadlineExceeded {
t.Errorf("Slowsort(ctx, tc) returned unexpected error: %v", err)
}
}

0 comments on commit 68d5df7

Please sign in to comment.