github.com/songzhibin97/gkit@v1.2.13/internal/stat/window.go (about)

     1  package stat
     2  
     3  // Bucket 桶对象
     4  type Bucket struct {
     5  	Points []float64
     6  	Count  int64
     7  	next   *Bucket
     8  }
     9  
    10  // Append 将给定值附加到存储桶中
    11  func (b *Bucket) Append(val float64) {
    12  	b.Points = append(b.Points, val)
    13  	b.Count++
    14  }
    15  
    16  // Add 根据偏移量增加val
    17  func (b *Bucket) Add(offset int, val float64) {
    18  	b.Points[offset] += val
    19  	b.Count++
    20  }
    21  
    22  // Reset 清空桶
    23  func (b *Bucket) Reset() {
    24  	b.Points = b.Points[:0]
    25  	b.Count = 0
    26  }
    27  
    28  // Next 返回下一个存储桶
    29  func (b *Bucket) Next() *Bucket {
    30  	return b.next
    31  }
    32  
    33  // Window Window 对象
    34  type Window struct {
    35  	window []Bucket
    36  	size   int
    37  }
    38  
    39  // NewWindow 实例化 Window 对象
    40  func NewWindow(size int) *Window {
    41  	buckets := make([]Bucket, size)
    42  	for offset := range buckets {
    43  		buckets[offset] = Bucket{Points: make([]float64, 0)}
    44  		nextOffset := offset + 1
    45  		if nextOffset == size {
    46  			nextOffset = 0
    47  		}
    48  		buckets[offset].next = &buckets[nextOffset]
    49  	}
    50  	return &Window{window: buckets, size: size}
    51  }
    52  
    53  // ResetWindow 清空窗口中的所有存储桶。
    54  func (w *Window) ResetWindow() {
    55  	for offset := range w.window {
    56  		w.ResetBucket(offset)
    57  	}
    58  }
    59  
    60  // ResetBucket 根据给定的偏移量清空存储桶。
    61  func (w *Window) ResetBucket(offset int) {
    62  	w.window[offset].Reset()
    63  }
    64  
    65  // ResetBuckets 根据给定的偏移量清空存储桶。
    66  func (w *Window) ResetBuckets(offsets []int) {
    67  	for _, offset := range offsets {
    68  		w.ResetBucket(offset)
    69  	}
    70  }
    71  
    72  // Append 将给定值附加到索引等于给定偏移量的存储桶。
    73  func (w *Window) Append(offset int, val float64) {
    74  	w.window[offset].Append(val)
    75  }
    76  
    77  // Add 将给定值添加到存储桶中索引等于给定偏移量的最新点
    78  func (w *Window) Add(offset int, val float64) {
    79  	if w.window[offset].Count == 0 {
    80  		w.window[offset].Append(val)
    81  		return
    82  	}
    83  	w.window[offset].Add(0, val)
    84  }
    85  
    86  // Bucket 返回偏移量的窗口桶
    87  func (w *Window) Bucket(offset int) Bucket {
    88  	return w.window[offset]
    89  }
    90  
    91  // Size 返回窗口小
    92  func (w *Window) Size() int {
    93  	return w.size
    94  }
    95  
    96  // Iterator returns the bucket iterator.
    97  func (w *Window) Iterator(offset int, count int) Iterator {
    98  	return Iterator{
    99  		count: count,
   100  		cur:   &w.window[offset],
   101  	}
   102  }