blob: 10a0c87942dce30693c04cf19c7ff7adb738d066 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
package saturating
type SaturatingInt struct {
max int
value int
saturated bool
}
func NewSaturatingInt(max int) *SaturatingInt {
return &SaturatingInt{max: max, value: 0, saturated: false}
}
func (s *SaturatingInt) Value() int {
if s.saturated {
return s.max
}
return s.value
}
func (s *SaturatingInt) Add(operand int) {
if !s.saturated {
s.value += operand
if s.value >= s.max {
s.saturated = true
}
}
}
|