github.com/samuelkuklis/utils@v1.0.0/buffer/ring_growing.go (about)

     1  /*
     2  Copyright 2017 The Kubernetes Authors.
     3  
     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
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    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.
    15  */
    16  
    17  package buffer
    18  
    19  // RingGrowing is a growing ring buffer.
    20  // Not thread safe.
    21  type RingGrowing struct {
    22  	data     []interface{}
    23  	n        int // Size of Data
    24  	beg      int // First available element
    25  	readable int // Number of data items available
    26  }
    27  
    28  // NewRingGrowing constructs a new RingGrowing instance with provided parameters.
    29  func NewRingGrowing(initialSize int) *RingGrowing {
    30  	return &RingGrowing{
    31  		data: make([]interface{}, initialSize),
    32  		n:    initialSize,
    33  	}
    34  }
    35  
    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) {
    38  	if r.readable == 0 {
    39  		return nil, false
    40  	}
    41  	r.readable--
    42  	element := r.data[r.beg]
    43  	r.data[r.beg] = nil // Remove reference to the object to help GC
    44  	if r.beg == r.n-1 {
    45  		// Was the last element
    46  		r.beg = 0
    47  	} else {
    48  		r.beg++
    49  	}
    50  	return element, true
    51  }
    52  
    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 {
    56  		// Time to grow
    57  		newN := r.n * 2
    58  		newData := make([]interface{}, newN)
    59  		to := r.beg + r.readable
    60  		if to <= r.n {
    61  			copy(newData, r.data[r.beg:to])
    62  		} else {
    63  			copied := copy(newData, r.data[r.beg:])
    64  			copy(newData[copied:], r.data[:(to%r.n)])
    65  		}
    66  		r.beg = 0
    67  		r.data = newData
    68  		r.n = newN
    69  	}
    70  	r.data[(r.readable+r.beg)%r.n] = data
    71  	r.readable++
    72  }