diff --git a/bps.go b/bps.go index f3a7694..3af2adf 100644 --- a/bps.go +++ b/bps.go @@ -127,3 +127,12 @@ func (b *BPS) Close() { close(b.quit) <-b.closed } + +// Data returns an slice of all the buckets, the most recent bucket first. +func (b *BPS) Data() []int { + r := []int{} + for i := len(b.buckets) - 1; i >= 0; i-- { + r = append(r, int(b.buckets[(b.timeI+i)%len(b.buckets)])) + } + return r +} diff --git a/bps_test.go b/bps_test.go index 9245227..2dbbc56 100644 --- a/bps_test.go +++ b/bps_test.go @@ -93,3 +93,106 @@ func TestHumanBytes(t *testing.T) { t.Fatalf("did not get right human rate; got %v, want %v", got, want) } } + +func TestData(t *testing.T) { + tests := []struct { + i int + buckets []int64 + expected []int + }{ + { + i: 0, + buckets: []int64{}, + expected: []int{}, + }, + { + i: 0, + buckets: []int64{0}, + expected: []int{0}, + }, + { + i: 0, + buckets: []int64{0, 1}, + expected: []int{1, 0}, + }, + { + i: 0, + buckets: []int64{0, 1, 2}, + expected: []int{2, 1, 0}, + }, + { + i: 0, + buckets: []int64{0, 1, 2, 3}, + expected: []int{3, 2, 1, 0}, + }, + + { + i: 1, + buckets: []int64{}, + expected: []int{}, + }, + { + i: 1, + buckets: []int64{0}, + expected: []int{0}, + }, + { + i: 1, + buckets: []int64{0, 1}, + expected: []int{0, 1}, + }, + { + i: 1, + buckets: []int64{0, 1, 2}, + expected: []int{0, 2, 1}, + }, + { + i: 1, + buckets: []int64{0, 1, 2, 3}, + expected: []int{0, 3, 2, 1}, + }, + + { + i: 2, + buckets: []int64{0, 1, 2}, + expected: []int{1, 0, 2}, + }, + { + i: 2, + buckets: []int64{0, 1, 2, 3}, + expected: []int{1, 0, 3, 2}, + }, + } + for _, test := range tests { + b := BPS{ + timeI: test.i, + buckets: test.buckets, + } + got := b.Data() + if !equals(got, test.expected) { + t.Errorf("got wrong data:\n\tgot: %v\n\twant: %v", got, test.expected) + } + } +} + +func equals(a, b []int) bool { + if len(a) != len(b) { + return false + } + + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +func TestOddBytes(t *testing.T) { + if got, want := human(1), "1B"; got != want { + t.Errorf("got: %s, want %s", got, want) + } + if got, want := human(1290), "1.3kB"; got != want { + t.Errorf("got: %s, want %s", got, want) + } +}