sort.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package file
  2. import (
  3. "reflect"
  4. "sort"
  5. "sync"
  6. )
  7. // A data structure to hold a key/value pair.
  8. type Pair struct {
  9. key string //sort key
  10. cId int
  11. order string
  12. clientFlow *Flow
  13. }
  14. // A slice of Pairs that implements sort.Interface to sort by Value.
  15. type PairList []*Pair
  16. func (p PairList) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  17. func (p PairList) Len() int { return len(p) }
  18. func (p PairList) Less(i, j int) bool {
  19. if p[i].order == "desc" {
  20. return reflect.ValueOf(*p[i].clientFlow).FieldByName(p[i].key).Int() < reflect.ValueOf(*p[j].clientFlow).FieldByName(p[j].key).Int()
  21. }
  22. return reflect.ValueOf(*p[i].clientFlow).FieldByName(p[i].key).Int() > reflect.ValueOf(*p[j].clientFlow).FieldByName(p[j].key).Int()
  23. }
  24. // A function to turn a map into a PairList, then sort and return it.
  25. func sortClientByKey(m sync.Map, sortKey, order string) (res []int) {
  26. p := make(PairList, 0)
  27. m.Range(func(key, value interface{}) bool {
  28. p = append(p, &Pair{sortKey, value.(*Client).Id, order, value.(*Client).Flow})
  29. return true
  30. })
  31. sort.Sort(p)
  32. for _, v := range p {
  33. res = append(res, v.cId)
  34. }
  35. return
  36. }