ring.go 760 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package collection
  2. import "sync"
  3. type Ring struct {
  4. elements []interface{}
  5. index int
  6. lock sync.Mutex
  7. }
  8. func NewRing(n int) *Ring {
  9. if n < 1 {
  10. panic("n should be greater than 0")
  11. }
  12. return &Ring{
  13. elements: make([]interface{}, n),
  14. }
  15. }
  16. func (r *Ring) Add(v interface{}) {
  17. r.lock.Lock()
  18. defer r.lock.Unlock()
  19. r.elements[r.index%len(r.elements)] = v
  20. r.index++
  21. }
  22. func (r *Ring) Take() []interface{} {
  23. r.lock.Lock()
  24. defer r.lock.Unlock()
  25. var size int
  26. var start int
  27. if r.index > len(r.elements) {
  28. size = len(r.elements)
  29. start = r.index % len(r.elements)
  30. } else {
  31. size = r.index
  32. }
  33. elements := make([]interface{}, size)
  34. for i := 0; i < size; i++ {
  35. elements[i] = r.elements[(start+i)%len(r.elements)]
  36. }
  37. return elements
  38. }