set minimum capacity at anytime
This commit is contained in:
parent
2ff0cd8822
commit
c7232d050f
26
deque.go
26
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<<minCapacityExp > 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<<minCapacityExp > 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
|
||||
|
|
|
@ -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<<exp {
|
||||
t.Fatal("wrong minimum capacity")
|
||||
|
@ -497,6 +498,10 @@ func TestNew(t *testing.T) {
|
|||
if len(q.buf) != 1<<exp {
|
||||
t.Fatal("wrong buffer size")
|
||||
}
|
||||
q.SetMinCapacity(0)
|
||||
if q.minCap != minCapacity {
|
||||
t.Fatal("wrong minimum capacity")
|
||||
}
|
||||
}
|
||||
|
||||
func assertPanics(t *testing.T, name string, f func()) {
|
||||
|
@ -590,7 +595,8 @@ func BenchmarkYoyo(b *testing.B) {
|
|||
}
|
||||
|
||||
func BenchmarkYoyoFixed(b *testing.B) {
|
||||
q := New(16)
|
||||
var q Deque
|
||||
q.SetMinCapacity(16)
|
||||
for i := 0; i < b.N; i++ {
|
||||
for j := 0; j < 65536; j++ {
|
||||
q.PushBack(j)
|
||||
|
|
Loading…
Reference in a new issue