snowflake-heap.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. proxyType string
  12. natType string
  13. offerChannel chan *ClientOffer
  14. answerChannel chan string
  15. clients int
  16. index int
  17. }
  18. // Implements heap.Interface, and holds Snowflakes.
  19. type SnowflakeHeap []*Snowflake
  20. func (sh SnowflakeHeap) Len() int { return len(sh) }
  21. func (sh SnowflakeHeap) Less(i, j int) bool {
  22. // Snowflakes serving less clients should sort earlier.
  23. return sh[i].clients < sh[j].clients
  24. }
  25. func (sh SnowflakeHeap) Swap(i, j int) {
  26. sh[i], sh[j] = sh[j], sh[i]
  27. sh[i].index = i
  28. sh[j].index = j
  29. }
  30. func (sh *SnowflakeHeap) Push(s interface{}) {
  31. n := len(*sh)
  32. snowflake := s.(*Snowflake)
  33. snowflake.index = n
  34. *sh = append(*sh, snowflake)
  35. }
  36. // Only valid when Len() > 0.
  37. func (sh *SnowflakeHeap) Pop() interface{} {
  38. flakes := *sh
  39. n := len(flakes)
  40. snowflake := flakes[n-1]
  41. snowflake.index = -1
  42. *sh = flakes[0 : n-1]
  43. return snowflake
  44. }