summaryrefslogtreecommitdiff
path: root/engine/pool
diff options
context:
space:
mode:
Diffstat (limited to 'engine/pool')
-rw-r--r--engine/pool/pool.go58
-rw-r--r--engine/pool/pool_test.go76
2 files changed, 134 insertions, 0 deletions
diff --git a/engine/pool/pool.go b/engine/pool/pool.go
new file mode 100644
index 0000000..2179a12
--- /dev/null
+++ b/engine/pool/pool.go
@@ -0,0 +1,58 @@
+package pool
+
+const Infinite = -1
+const Empty = 0
+
+type Pool struct {
+ OverflowsTo *Pool
+ SubtractsTo *Pool
+ 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
+ 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,
+ }
+}
diff --git a/engine/pool/pool_test.go b/engine/pool/pool_test.go
new file mode 100644
index 0000000..4dd0ea5
--- /dev/null
+++ b/engine/pool/pool_test.go
@@ -0,0 +1,76 @@
+package pool
+
+import (
+ "github.com/stretchr/testify/assert"
+ "testing"
+)
+
+func TestPool_Add(t *testing.T) {
+ p := &Pool{
+ Max: 10,
+ Value: 3,
+ }
+ p.Add(4)
+}
+
+func TestPool_Add_Overflows(t *testing.T) {
+ shad := &Pool{
+ Max: 5,
+ Value: 0,
+ }
+ dist := &Pool{
+ OverflowsTo: shad,
+ Max: 5,
+ Value: 0,
+ }
+ dist.Add(8)
+ assert.Equal(t, shad.Value, 3)
+}
+
+func TestPool_Subtract(t *testing.T) {
+ p := &Pool{
+ Max: 10,
+ Value: 8,
+ }
+ p.Subtract(6)
+ assert.Equal(t, 2, p.Value)
+}
+
+func TestPool_Subtract_Empties(t *testing.T) {
+ p := &Pool{
+ Max: 10,
+ Value: 4,
+ }
+ p.Subtract(8)
+ assert.Equal(t, 0, p.Value)
+}
+
+func TestPool_Subtract_Flows(t *testing.T) {
+ dest := &Pool{
+ Value: 0,
+ Max: Infinite,
+ }
+ p := &Pool{
+ SubtractsTo: dest,
+ Max: Infinite,
+ Value: 10,
+ }
+ p.Subtract(8)
+ assert.Equal(t, 8, dest.Value)
+ assert.Equal(t, 2, p.Value)
+}
+
+func TestPool_Subtract_Flows_Empties(t *testing.T) {
+ dest := &Pool{
+ Value: 0,
+ Max: Infinite,
+ }
+ p := &Pool{
+ SubtractsTo: dest,
+ Max: Infinite,
+ Value: 5,
+ }
+ p.Subtract(8)
+ assert.Equal(t, 5, dest.Value)
+ assert.Equal(t, 0, p.Value)
+}