vitess.io/vitess@v0.16.2/go/stats/ring.go (about)

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