github.com/XiaoMi/Gaea@v1.2.5/stats/ring.go (about)

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