Add Set and Copy methods

This commit is contained in:
vejnar 2020-02-19 12:34:13 -05:00
parent 7e84b94275
commit d9f824a398
2 changed files with 61 additions and 0 deletions

View file

@ -117,6 +117,29 @@ func (q *Deque) At(i int) interface{} {
return q.buf[(q.head+i)&(len(q.buf)-1)]
}
// Set puts the element at index i in the queue. Set shares the same purpose
// than At() but perform the opposite operation. The index i is the same
// index defined by At(). If the index is invalid, the call panics.
func (q *Deque) Set(i int, elem interface{}) {
if i < 0 || i >= q.count {
panic("deque: Set() called with index out of range")
}
// bitwise modulus
q.buf[(q.head+i)&(len(q.buf)-1)] = elem
}
// Copy takes the indices of two elements and copies the element at index i
// into index j. Copy is a shortcut for q.Set(j) = q.At(i). The indices i and j
// are the same indices defined by At(). If one of the indices is invalid, the
// call panics.
func (q *Deque) Copy(i int, j int) {
if i < 0 || i >= q.count || j < 0 || j >= q.count {
panic("deque: Copy() called with index out of range")
}
// bitwise modulus
q.buf[(q.head+j)&(len(q.buf)-1)] = q.buf[(q.head+i)&(len(q.buf)-1)]
}
// Clear removes all elements from the queue, but retains the current capacity.
// This is useful when repeatedly reusing the queue at high frequency to avoid
// GC during reuse. The queue will not be resized smaller as long as items are

View file

@ -282,6 +282,44 @@ func TestAt(t *testing.T) {
}
}
func TestSet(t *testing.T) {
var q Deque
for i := 0; i < 1000; i++ {
q.PushBack(i)
q.Set(i, i+50)
}
// Front to back.
for j := 0; j < q.Len(); j++ {
if q.At(j).(int) != j+50 {
t.Errorf("index %d doesn't contain %d", j, j+50)
}
}
}
func TestCopy(t *testing.T) {
var q Deque
for i := 0; i < 1000; i++ {
q.PushBack(i)
}
// Copy first half in last half
for i := 0; i < 500; i++ {
q.Copy(i, i+500)
}
for j := 0; j < 500; j++ {
if q.At(j).(int) != j {
t.Errorf("index %d doesn't contain %d", j, j)
}
if q.At(j+500).(int) != j {
t.Errorf("index %d doesn't contain %d", j+500, j)
}
}
}
func TestClear(t *testing.T) {
var q Deque