Debian Codegraph @

windowedmin.go

raw
1 // SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
2 // SPDX-License-Identifier: MIT
3
4 package sctp
5
6 import (
7 "sort"
8 "time"
9 )
10
11 // windowedMin maintains a monotonic deque of (time,value) to answer
12 // the minimum over a sliding window efficiently.
13 // Not thread-safe; caller must synchronize (Association already does).
14 type windowedMin struct {
15 rackMinRTTWnd time.Duration
16 deque []entry
17 }
18
19 type entry struct {
20 t time.Time
21 v time.Duration
22 }
23
24 func newWindowedMin(window time.Duration) *windowedMin {
25 if window <= 0 {
26 window = 30 * time.Second
27 }
28
29 return &windowedMin{rackMinRTTWnd: window}
30 }
31
32 // prune removes elements older than (now - wnd).
33 func (window *windowedMin) prune(now time.Time) {
34 if len(window.deque) == 0 {
35 return
36 }
37
38 cutoff := now.Add(-window.rackMinRTTWnd)
39
40 firstValidTSAfterCutoff := sort.Search(len(window.deque), func(i int) bool {
41 return !window.deque[i].t.Before(cutoff) // no builtin func for >= cutoff time
42 })
43
44 if firstValidTSAfterCutoff > 0 {
45 window.deque = window.deque[firstValidTSAfterCutoff:]
46 }
47 }
48
49 // Push inserts a new sample and preserves monotonic non-increasing values.
50 // It maintains minimum values by removing larger entries.
51 func (window *windowedMin) Push(now time.Time, v time.Duration) {
52 window.prune(now)
53
54 for i := len(window.deque); i > 0 && window.deque[i-1].v >= v; i-- {
55 window.deque = window.deque[:i-1]
56 }
57
58 window.deque = append(
59 window.deque,
60 entry{
61 t: now,
62 v: v,
63 },
64 )
65 }
66
67 // Min returns the minimum value in the current window or 0 if empty.
68 func (window *windowedMin) Min(now time.Time) time.Duration {
69 window.prune(now)
70
71 if len(window.deque) == 0 {
72 return 0
73 }
74
75 return window.deque[0].v
76 }
77
78 // Len is only for tests/diagnostics.
79 func (window *windowedMin) Len() int {
80 return len(window.deque)
81 }