2 Copyright 2017 The Kubernetes Authors.
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
8 http://www.apache.org/licenses/LICENSE-2.0
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
19 // RingGrowing is a growing ring buffer.
21 type RingGrowing struct {
24 beg int // First available element
25 readable int // Number of data items available
28 // NewRingGrowing constructs a new RingGrowing instance with provided parameters.
29 func NewRingGrowing(initialSize int) *RingGrowing {
31 data: make([]interface{}, initialSize),
36 // ReadOne reads (consumes) first item from the buffer if it is available, otherwise returns false.
37 func (r *RingGrowing) ReadOne() (data interface{}, ok bool) {
42 element := r.data[r.beg]
43 r.data[r.beg] = nil // Remove reference to the object to help GC
45 // Was the last element
53 // WriteOne adds an item to the end of the buffer, growing it if it is full.
54 func (r *RingGrowing) WriteOne(data interface{}) {
55 if r.readable == r.n {
58 newData := make([]interface{}, newN)
59 to := r.beg + r.readable
61 copy(newData, r.data[r.beg:to])
63 copied := copy(newData, r.data[r.beg:])
64 copy(newData[copied:], r.data[:(to%r.n)])
70 r.data[(r.readable+r.beg)%r.n] = data