ring_growing.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package buffer
  14. // RingGrowing is a growing ring buffer.
  15. // Not thread safe.
  16. type RingGrowing struct {
  17. data []interface{}
  18. n int // Size of Data
  19. beg int // First available element
  20. readable int // Number of data items available
  21. }
  22. // NewRingGrowing constructs a new RingGrowing instance with provided parameters.
  23. func NewRingGrowing(initialSize int) *RingGrowing {
  24. return &RingGrowing{
  25. data: make([]interface{}, initialSize),
  26. n: initialSize,
  27. }
  28. }
  29. // ReadOne reads (consumes) first item from the buffer if it is available, otherwise returns false.
  30. func (r *RingGrowing) ReadOne() (data interface{}, ok bool) {
  31. if r.readable == 0 {
  32. return nil, false
  33. }
  34. r.readable--
  35. element := r.data[r.beg]
  36. r.data[r.beg] = nil // Remove reference to the object to help GC
  37. if r.beg == r.n-1 {
  38. // Was the last element
  39. r.beg = 0
  40. } else {
  41. r.beg++
  42. }
  43. return element, true
  44. }
  45. // WriteOne adds an item to the end of the buffer, growing it if it is full.
  46. func (r *RingGrowing) WriteOne(data interface{}) {
  47. if r.readable == r.n {
  48. // Time to grow
  49. newN := r.n * 2
  50. newData := make([]interface{}, newN)
  51. to := r.beg + r.readable
  52. if to <= r.n {
  53. copy(newData, r.data[r.beg:to])
  54. } else {
  55. copied := copy(newData, r.data[r.beg:])
  56. copy(newData[copied:], r.data[:(to%r.n)])
  57. }
  58. r.beg = 0
  59. r.data = newData
  60. r.n = newN
  61. }
  62. r.data[(r.readable+r.beg)%r.n] = data
  63. r.readable++
  64. }