ring.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /*
  2. Copyright 2019 The Vitess 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 stats
  14. // Ring of int64 values
  15. // Not thread safe
  16. type RingInt64 struct {
  17. position int
  18. values []int64
  19. }
  20. func NewRingInt64(capacity int) *RingInt64 {
  21. return &RingInt64{values: make([]int64, 0, capacity)}
  22. }
  23. func (ri *RingInt64) Add(val int64) {
  24. if len(ri.values) == cap(ri.values) {
  25. ri.values[ri.position] = val
  26. ri.position = (ri.position + 1) % cap(ri.values)
  27. } else {
  28. ri.values = append(ri.values, val)
  29. }
  30. }
  31. func (ri *RingInt64) Values() (values []int64) {
  32. values = make([]int64, len(ri.values))
  33. for i := 0; i < len(ri.values); i++ {
  34. values[i] = ri.values[(ri.position+i)%cap(ri.values)]
  35. }
  36. return values
  37. }