File: sort.go

package info (click to toggle)
golang-github-anacrolix-missinggo 2.1.0-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 836 kB
  • sloc: makefile: 4
file content (36 lines) | stat: -rw-r--r-- 831 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package slices

import (
	"container/heap"
	"reflect"
	"sort"
)

// Sorts the slice in place. Returns sl for convenience.
func Sort(sl interface{}, less interface{}) interface{} {
	sorter := sorter{
		sl:   reflect.ValueOf(sl),
		less: reflect.ValueOf(less),
	}
	sort.Sort(&sorter)
	return sorter.sl.Interface()
}

// Creates a modifiable copy of a slice reference. Because you can't modify
// non-pointer types inside an interface{}.
func addressableSlice(slice interface{}) reflect.Value {
	v := reflect.ValueOf(slice)
	p := reflect.New(v.Type())
	p.Elem().Set(v)
	return p.Elem()
}

// Returns a "container/heap".Interface for the provided slice.
func HeapInterface(sl interface{}, less interface{}) heap.Interface {
	ret := &sorter{
		sl:   addressableSlice(sl),
		less: reflect.ValueOf(less),
	}
	heap.Init(ret)
	return ret
}