snowflake-heap.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. Keeping track of pending available snowflake proxies.
  3. */
  4. package main
  5. /*
  6. The Snowflake struct contains a single interaction
  7. over the offer and answer channels.
  8. */
  9. type Snowflake struct {
  10. id string
  11. offerChannel chan []byte
  12. answerChannel chan []byte
  13. clients int
  14. index int
  15. }
  16. // Implements heap.Interface, and holds Snowflakes.
  17. type SnowflakeHeap []*Snowflake
  18. func (sh SnowflakeHeap) Len() int { return len(sh) }
  19. func (sh SnowflakeHeap) Less(i, j int) bool {
  20. // Snowflakes serving less clients should sort earlier.
  21. return sh[i].clients < sh[j].clients
  22. }
  23. func (sh SnowflakeHeap) Swap(i, j int) {
  24. sh[i], sh[j] = sh[j], sh[i]
  25. sh[i].index = i
  26. sh[j].index = j
  27. }
  28. func (sh *SnowflakeHeap) Push(s interface{}) {
  29. n := len(*sh)
  30. snowflake := s.(*Snowflake)
  31. snowflake.index = n
  32. *sh = append(*sh, snowflake)
  33. }
  34. // Only valid when Len() > 0.
  35. func (sh *SnowflakeHeap) Pop() interface{} {
  36. flakes := *sh
  37. n := len(flakes)
  38. snowflake := flakes[n-1]
  39. snowflake.index = -1
  40. *sh = flakes[0 : n-1]
  41. return snowflake
  42. }