From c7232d050f209930b91de6dec75a0c462637b22e Mon Sep 17 00:00:00 2001 From: Andrew Gillis Date: Wed, 15 May 2019 04:19:52 -0400 Subject: [PATCH] set minimum capacity at anytime --- deque.go | 26 +++++++++++++++----------- deque_test.go | 12 +++++++++--- 2 files changed, 24 insertions(+), 14 deletions(-) diff --git a/deque.go b/deque.go index 8e31fbd..bca4ea1 100644 --- a/deque.go +++ b/deque.go @@ -13,17 +13,6 @@ type Deque struct { minCap int } -// New creates a new Deque that has a minimum capacity of 2^minCapacityExp. If -// the value of the minimum capacity is less than or equal to the minimum -// allowed, then New returns the same as new(Deque). -func New(minCapacityExp uint) *Deque { - q := new(Deque) - if 1< minCapacity { - q.minCap = 1 << minCapacityExp - } - return q -} - // Len returns the number of elements currently stored in the queue. func (q *Deque) Len() int { return q.count @@ -190,6 +179,21 @@ func (q *Deque) Rotate(n int) { } } +// SetMinCapacity sets a minimum capacity of 2^minCapacityExp. If the value of +// the minimum capacity is less than or equal to the minimum allowed, then +// capacity is set to the minimum allowed. This may be called at anytime to +// set a new minimum capacity. +// +// Setting a larger minimum capacity may be used to prevent resizing when the +// number of stored items changes frequently across a wide range. +func (q *Deque) SetMinCapacity(minCapacityExp uint) { + if 1< minCapacity { + q.minCap = 1 << minCapacityExp + } else { + q.minCap = minCapacity + } +} + // prev returns the previous buffer position wrapping around buffer. func (q *Deque) prev(i int) int { return (i - 1) & (len(q.buf) - 1) // bitwise modulus diff --git a/deque_test.go b/deque_test.go index 9861497..f26b0d3 100644 --- a/deque_test.go +++ b/deque_test.go @@ -480,9 +480,10 @@ func TestRemoveOutOfRangePanics(t *testing.T) { }) } -func TestNew(t *testing.T) { +func TestSetMinCapacity(t *testing.T) { + var q Deque exp := uint(8) - q := New(8) + q.SetMinCapacity(exp) q.PushBack("A") if q.minCap != 1<