gtimer_queue_heap.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gtimer
  7. // Len is used to implement the interface of sort.Interface.
  8. func (h *priorityQueueHeap) Len() int {
  9. return len(h.array)
  10. }
  11. // Less is used to implement the interface of sort.Interface.
  12. // The least one is placed to the top of the heap.
  13. func (h *priorityQueueHeap) Less(i, j int) bool {
  14. return h.array[i].priority < h.array[j].priority
  15. }
  16. // Swap is used to implement the interface of sort.Interface.
  17. func (h *priorityQueueHeap) Swap(i, j int) {
  18. if len(h.array) == 0 {
  19. return
  20. }
  21. h.array[i], h.array[j] = h.array[j], h.array[i]
  22. }
  23. // Push pushes an item to the heap.
  24. func (h *priorityQueueHeap) Push(x interface{}) {
  25. h.array = append(h.array, x.(priorityQueueItem))
  26. }
  27. // Pop retrieves, removes and returns the most high priority item from the heap.
  28. func (h *priorityQueueHeap) Pop() interface{} {
  29. length := len(h.array)
  30. if length == 0 {
  31. return nil
  32. }
  33. item := h.array[length-1]
  34. h.array = h.array[0 : length-1]
  35. return item
  36. }