Skip to content

Commit

Permalink
Use github.com/maruel/natural in metrics sorting
Browse files Browse the repository at this point in the history
  • Loading branch information
Felixoid authored and Civil committed Jun 2, 2022
1 parent ac231fd commit 58ebf88
Showing 1 changed file with 2 additions and 16 deletions.
18 changes: 2 additions & 16 deletions expr/helper/sort.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
package helper

import (
"fmt"
"regexp"
"strconv"

"github.com/go-graphite/carbonapi/expr/types"
"github.com/maruel/natural"
)

// ByVals sorts by values
Expand Down Expand Up @@ -45,22 +42,11 @@ func (s ByName) Less(i, j int) bool { return s[i].Name < s[j].Name }
// ByNameNatural sorts metric naturally by name
type ByNameNatural []*types.MetricData

var dre = regexp.MustCompile(`\d+`)

func (s ByNameNatural) pad(str string) string {
f := func(match []byte) []byte {
n, _ := strconv.ParseInt(string(match), 10, 64)
return []byte(fmt.Sprintf("%010d", n))
}

return string(dre.ReplaceAllFunc([]byte(str), f))
}

// Len returns length, required to be sortable
func (s ByNameNatural) Len() int { return len(s) }

// Swap swaps to elements by IDs, required to be sortable
func (s ByNameNatural) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

// Less compares two elements with specified IDs, required to be sortable
func (s ByNameNatural) Less(i, j int) bool { return s.pad(s[i].Name) < s.pad(s[j].Name) }
func (s ByNameNatural) Less(i, j int) bool { return natural.Less(s[i].Name, s[j].Name) }

0 comments on commit 58ebf88

Please sign in to comment.