github.com/songzhibin97/gkit@v1.2.13/watching/ring.go (about) 1 package watching 2 3 type ring struct { 4 data []int 5 idx int 6 sum int 7 maxLen int 8 } 9 10 func newRing(maxLen int) ring { 11 return ring{ 12 data: make([]int, 0, maxLen), 13 idx: 0, 14 maxLen: maxLen, 15 } 16 } 17 18 func (r *ring) push(i int) { 19 if r.maxLen == 0 { 20 return 21 } 22 23 // the first round 24 if len(r.data) < r.maxLen { 25 r.sum += i 26 r.data = append(r.data, i) 27 return 28 } 29 30 r.sum += i - r.data[r.idx] 31 32 // the ring is expanded, just write to the position 33 r.data[r.idx] = i 34 r.idx = (r.idx + 1) % r.maxLen 35 } 36 37 func (r *ring) avg() int { 38 // Check if the len(r.data) is zero before dividing 39 if r.maxLen == 0 || len(r.data) == 0 { 40 return 0 41 } 42 return r.sum / len(r.data) 43 }