sort.go 986 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package shared
  2. import "slices"
  3. type SortCol int8
  4. const (
  5. SortID SortCol = iota
  6. SortRecords
  7. SortBytes
  8. )
  9. func (s SortCol) Next() SortCol { return (s + 1) % 3 }
  10. func (s SortCol) String() string { return [...]string{"id", "records", "bytes"}[s] }
  11. // SortBy sorts components in-place, preserving kind grouping order.
  12. func SortBy(cs []ComponentMetrics, col SortCol, asc bool) {
  13. less := map[SortCol]func(a, b ComponentMetrics) int{
  14. SortID: func(a, b ComponentMetrics) int { return cmp(a.ID, b.ID) },
  15. SortRecords: func(a, b ComponentMetrics) int { return cmp(a.Records(), b.Records()) },
  16. SortBytes: func(a, b ComponentMetrics) int { return cmp(a.Bytes(), b.Bytes()) },
  17. }[col]
  18. slices.SortStableFunc(cs, func(a, b ComponentMetrics) int {
  19. if a.Kind != b.Kind {
  20. return int(a.Kind - b.Kind)
  21. }
  22. c := less(a, b)
  23. if !asc {
  24. return -c
  25. }
  26. return c
  27. })
  28. }
  29. func cmp[T ~string | ~int64](a, b T) int {
  30. if a < b {
  31. return -1
  32. }
  33. if a > b {
  34. return 1
  35. }
  36. return 0
  37. }