blob: 8256d698ca3d0f9acbfcc4eb05369b1eba6c31f6 (
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
package pool
const Infinite = -1
const Empty = 0
type Pool struct {
OverflowsTo *Pool `json:"-"`
SubtractsTo *Pool `json:"-"`
Max int
Value int
}
func (p *Pool) Add(amount int) {
p.Value += amount
if p.Max == Infinite {
return
}
if p.Value > p.Max {
overflow := p.Value - p.Max
p.Value = p.Max
if p.OverflowsTo != nil {
p.OverflowsTo.Add(overflow)
}
}
}
func (p *Pool) Subtract(amount int) {
if p.SubtractsTo != nil {
forward := amount
if forward > p.Value {
forward = p.Value
}
p.SubtractsTo.Add(forward)
}
if p.Value == Infinite {
return
}
p.Value -= amount
if p.Value < 0 {
p.Value = 0
}
}
func (p *Pool) Fits(amount int) bool {
return p.Value+amount <= p.Max
}
func (p *Pool) Has(amount int) bool {
return p.Value >= amount
}
func New(start, max int) *Pool {
return &Pool{
Max: max,
Value: start,
}
}
|