util.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package cluster
  2. import (
  3. "fmt"
  4. "sort"
  5. "sync"
  6. )
  7. type none struct{}
  8. type topicPartition struct {
  9. Topic string
  10. Partition int32
  11. }
  12. func (tp *topicPartition) String() string {
  13. return fmt.Sprintf("%s-%d", tp.Topic, tp.Partition)
  14. }
  15. type offsetInfo struct {
  16. Offset int64
  17. Metadata string
  18. }
  19. func (i offsetInfo) NextOffset(fallback int64) int64 {
  20. if i.Offset > -1 {
  21. return i.Offset
  22. }
  23. return fallback
  24. }
  25. type int32Slice []int32
  26. func (p int32Slice) Len() int { return len(p) }
  27. func (p int32Slice) Less(i, j int) bool { return p[i] < p[j] }
  28. func (p int32Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  29. func (p int32Slice) Diff(o int32Slice) (res []int32) {
  30. on := len(o)
  31. for _, x := range p {
  32. n := sort.Search(on, func(i int) bool { return o[i] >= x })
  33. if n < on && o[n] == x {
  34. continue
  35. }
  36. res = append(res, x)
  37. }
  38. return
  39. }
  40. // --------------------------------------------------------------------
  41. type loopTomb struct {
  42. c chan none
  43. o sync.Once
  44. w sync.WaitGroup
  45. }
  46. func newLoopTomb() *loopTomb {
  47. return &loopTomb{c: make(chan none)}
  48. }
  49. func (t *loopTomb) stop() { t.o.Do(func() { close(t.c) }) }
  50. func (t *loopTomb) Close() { t.stop(); t.w.Wait() }
  51. func (t *loopTomb) Dying() <-chan none { return t.c }
  52. func (t *loopTomb) Go(f func(<-chan none)) {
  53. t.w.Add(1)
  54. go func() {
  55. defer t.stop()
  56. defer t.w.Done()
  57. f(t.c)
  58. }()
  59. }