-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
slice.go
51 lines (44 loc) · 1.41 KB
/
slice.go
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package heap
type sliceInterface[T any] struct {
slice *[]T
less func(T, T) bool
}
// This is for use by the heap package's global functions, you probably don't mean to call this
// directly.
func (me sliceInterface[T]) Less(i, j int) bool {
return me.less((*me.slice)[i], (*me.slice)[j])
}
// This is for use by the heap package's global functions, you probably don't mean to call this
// directly.
func (me sliceInterface[T]) Swap(i, j int) {
s := *me.slice
s[i], s[j] = s[j], s[i]
*me.slice = s
}
// This is for use by the heap package's global functions, you probably don't mean to call this
// directly.
func (me sliceInterface[T]) Push(x T) {
*me.slice = append(*me.slice, x)
}
// This is for use by the heap package's global functions, you probably don't mean to call this
// directly.
func (me sliceInterface[T]) Pop() T {
s := *me.slice
n := len(s)
ret := s[n-1]
*me.slice = s[:n-1]
return ret
}
func (me sliceInterface[T]) Len() int {
return len(*me.slice)
}
// Creates an Interface that operates on a slice in place. The Interface should be used with the
// heap package's global functions just like you would with a manual implementation of Interface for
// a slice. i.e. don't call Interface.{Push,Pop}, call heap.{Push,Pop} and pass the return value
// from this function.
func InterfaceForSlice[T any](sl *[]T, less func(l T, r T) bool) Interface[T] {
return sliceInterface[T]{
slice: sl,
less: less,
}
}