From 0943ed42dd4feb88943f2d8583e009f27820c938 Mon Sep 17 00:00:00 2001 From: Buddy Sandidge Date: Sun, 3 Nov 2019 15:27:19 -0800 Subject: [PATCH] Add methods for Bucket structs --- lib/bucket/bucket.go | 22 ++++++++++++++++++++++ lib/bucket/bucket_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 lib/bucket/bucket_test.go diff --git a/lib/bucket/bucket.go b/lib/bucket/bucket.go index 97e8975..2077fca 100644 --- a/lib/bucket/bucket.go +++ b/lib/bucket/bucket.go @@ -7,3 +7,25 @@ type Bucket struct { // Volume is the current volume of the bucket Volume uint64 } + +// Fill sets the volume to the capacity to fill bucket +func (b *Bucket) Fill() { + b.Volume = b.Capacity +} + +// Empty sets the volume to 0 +func (b *Bucket) Empty() { + b.Volume = 0 +} + +// Pour fills the target bucket to the top +func (b *Bucket) Pour(target *Bucket) { + availableVolume := target.Capacity - target.Volume + if availableVolume > b.Volume { + target.Volume += b.Volume + b.Volume = 0 + } else { + b.Volume -= availableVolume + target.Volume += availableVolume + } +} diff --git a/lib/bucket/bucket_test.go b/lib/bucket/bucket_test.go new file mode 100644 index 0000000..476ab63 --- /dev/null +++ b/lib/bucket/bucket_test.go @@ -0,0 +1,28 @@ +package bucket + +import "testing" + +func TestPour(t *testing.T) { + var testcases = []struct { + source *Bucket + target *Bucket + expectedSrcVol uint64 + expectedTargetVol uint64 + }{ + {&Bucket{Capacity: 5, Volume: 2}, &Bucket{Capacity: 3, Volume: 2}, 1, 3}, + {&Bucket{Capacity: 5, Volume: 1}, &Bucket{Capacity: 3, Volume: 1}, 0, 2}, + {&Bucket{Capacity: 5, Volume: 0}, &Bucket{Capacity: 3, Volume: 0}, 0, 0}, + {&Bucket{Capacity: 5, Volume: 5}, &Bucket{Capacity: 3, Volume: 3}, 5, 3}, + {&Bucket{Capacity: 5, Volume: 4}, &Bucket{Capacity: 3, Volume: 2}, 3, 3}, + } + + for _, tc := range testcases { + tc.source.Pour(tc.target) + if tc.source.Volume != tc.expectedSrcVol { + t.Errorf("expected source volume %d, got = %d", tc.expectedSrcVol, tc.source.Volume) + } + if tc.target.Volume != tc.expectedTargetVol { + t.Errorf("expected target volume %d, got = %d", tc.expectedTargetVol, tc.target.Volume) + } + } +}