slice.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package heap
  2. type sliceInterface[T any] struct {
  3. slice *[]T
  4. less func(T, T) bool
  5. }
  6. // This is for use by the heap package's global functions, you probably don't mean to call this
  7. // directly.
  8. func (me sliceInterface[T]) Less(i, j int) bool {
  9. return me.less((*me.slice)[i], (*me.slice)[j])
  10. }
  11. // This is for use by the heap package's global functions, you probably don't mean to call this
  12. // directly.
  13. func (me sliceInterface[T]) Swap(i, j int) {
  14. s := *me.slice
  15. s[i], s[j] = s[j], s[i]
  16. *me.slice = s
  17. }
  18. // This is for use by the heap package's global functions, you probably don't mean to call this
  19. // directly.
  20. func (me sliceInterface[T]) Push(x T) {
  21. *me.slice = append(*me.slice, x)
  22. }
  23. // This is for use by the heap package's global functions, you probably don't mean to call this
  24. // directly.
  25. func (me sliceInterface[T]) Pop() T {
  26. s := *me.slice
  27. n := len(s)
  28. ret := s[n-1]
  29. *me.slice = s[:n-1]
  30. return ret
  31. }
  32. func (me sliceInterface[T]) Len() int {
  33. return len(*me.slice)
  34. }
  35. // Creates an Interface that operates on a slice in place. The Interface should be used with the
  36. // heap package's global functions just like you would with a manual implementation of Interface for
  37. // a slice. i.e. don't call Interface.{Push,Pop}, call heap.{Push,Pop} and pass the return value
  38. // from this function.
  39. func InterfaceForSlice[T any](sl *[]T, less func(l T, r T) bool) Interface[T] {
  40. return sliceInterface[T]{
  41. slice: sl,
  42. less: less,
  43. }
  44. }