diff --git a/src/result.go b/src/result.go index 945e272c..433f5750 100644 --- a/src/result.go +++ b/src/result.go @@ -2,6 +2,7 @@ package fzf import ( "math" + "slices" "sort" "unicode" @@ -30,7 +31,7 @@ type Result struct { func buildResult(item *Item, offsets []Offset, score int) Result { if len(offsets) > 1 { - sort.Sort(ByOrder(offsets)) + slices.SortFunc(offsets, compareOffsets) } minBegin := math.MaxUint16 @@ -187,7 +188,7 @@ func (result *Result) colorOffsets(matchOffsets []Offset, nthOffsets []Offset, t } } - // sort.Sort(ByOrder(offsets)) + // slices.SortFunc(offsets, compareOffsets) // Merge offsets // ------------ ---- -- ---- @@ -297,21 +298,20 @@ func (result *Result) colorOffsets(matchOffsets []Offset, nthOffsets []Offset, t return colors } -// ByOrder is for sorting substring offsets -type ByOrder []Offset - -func (a ByOrder) Len() int { - return len(a) -} - -func (a ByOrder) Swap(i, j int) { - a[i], a[j] = a[j], a[i] -} - -func (a ByOrder) Less(i, j int) bool { - ioff := a[i] - joff := a[j] - return (ioff[0] < joff[0]) || (ioff[0] == joff[0]) && (ioff[1] <= joff[1]) +func compareOffsets(a, b Offset) int { + if a[0] < b[0] { + return -1 + } + if a[0] > b[0] { + return 1 + } + if a[1] < b[1] { + return -1 + } + if a[1] > b[1] { + return 1 + } + return 0 } // ByRelevance is for sorting Items diff --git a/src/result_test.go b/src/result_test.go index 8fd61984..a040e118 100644 --- a/src/result_test.go +++ b/src/result_test.go @@ -3,6 +3,7 @@ package fzf import ( "math" "math/rand" + "slices" "sort" "testing" @@ -19,7 +20,7 @@ func TestOffsetSort(t *testing.T) { offsets := []Offset{ {3, 5}, {2, 7}, {1, 3}, {2, 9}} - sort.Sort(ByOrder(offsets)) + slices.SortFunc(offsets, compareOffsets) if offsets[0][0] != 1 || offsets[0][1] != 3 || offsets[1][0] != 2 || offsets[1][1] != 7 || diff --git a/src/terminal.go b/src/terminal.go index f3112a41..723a7827 100644 --- a/src/terminal.go +++ b/src/terminal.go @@ -13,6 +13,7 @@ import ( "os/exec" "os/signal" "regexp" + "slices" "sort" "strconv" "strings" @@ -3751,7 +3752,7 @@ func (t *Terminal) printHighlighted(result Result, colBase tui.ColorPair, colMat offset := Offset{int32(p), int32(p + w)} charOffsets[idx] = offset } - sort.Sort(ByOrder(charOffsets)) + slices.SortFunc(charOffsets, compareOffsets) } // When postTask is nil, we're printing header lines. No need to care about nth. @@ -3788,7 +3789,7 @@ func (t *Terminal) printHighlighted(result Result, colBase tui.ColorPair, colMat end := start + int32(length) nthOffsets[i] = Offset{int32(start), int32(end)} } - sort.Sort(ByOrder(nthOffsets)) + slices.SortFunc(nthOffsets, compareOffsets) } } allOffsets := result.colorOffsets(charOffsets, nthOffsets, t.theme, colBase, colMatch, t.nthAttr, nthOverlay, hidden)