Add a mean to get an index, allowing iterations of the queue.
Antoine Grondin
9 years ago
58 | 58 |
return q.buf[q.head]
|
59 | 59 |
}
|
60 | 60 |
|
|
61 |
// Get returns the element at index i in the queue. If the index is invalid, the
|
|
62 |
// call will panic.
|
|
63 |
func (q *Queue) Get(i int) interface{} {
|
|
64 |
if i >= q.Length() || i < 0 {
|
|
65 |
panic("index out of range")
|
|
66 |
}
|
|
67 |
modi := (q.head + i) % len(q.buf)
|
|
68 |
return q.buf[modi]
|
|
69 |
}
|
|
70 |
|
61 | 71 |
// Remove removes the element from the front of the queue. If you actually want the element,
|
62 | 72 |
// call Peek first. If the queue is empty (Length == 0), Remove will put the queue in a bad
|
63 | 73 |
// state and all further operations will be undefined.
|
11 | 11 |
for i := 0; i < 1000; i++ {
|
12 | 12 |
q.Add(i)
|
13 | 13 |
if q.Length() != i+1 {
|
14 | |
t.Error("adding: queue with", i , "elements has length", q.Length())
|
|
14 |
t.Error("adding: queue with", i, "elements has length", q.Length())
|
15 | 15 |
}
|
16 | 16 |
}
|
17 | 17 |
for i := 0; i < 1000; i++ {
|
18 | 18 |
q.Remove()
|
19 | 19 |
if q.Length() != 1000-i-1 {
|
20 | |
t.Error("removing: queue with", 1000-i-i , "elements has length", q.Length())
|
|
20 |
t.Error("removing: queue with", 1000-i-i, "elements has length", q.Length())
|
21 | 21 |
}
|
22 | 22 |
}
|
|
23 |
}
|
|
24 |
|
|
25 |
func TestQueueGet(t *testing.T) {
|
|
26 |
q := New()
|
|
27 |
|
|
28 |
for i := 0; i < 1000; i++ {
|
|
29 |
q.Add(i)
|
|
30 |
for j := 0; j < q.Length(); j++ {
|
|
31 |
if q.Get(j).(int) != j {
|
|
32 |
t.Errorf("index %d doesn't contain %d", j, j)
|
|
33 |
}
|
|
34 |
}
|
|
35 |
}
|
|
36 |
}
|
|
37 |
|
|
38 |
func TestQueueGetOutOfRangePanics(t *testing.T) {
|
|
39 |
q := New()
|
|
40 |
|
|
41 |
q.Add(1)
|
|
42 |
q.Add(2)
|
|
43 |
q.Add(3)
|
|
44 |
|
|
45 |
func() {
|
|
46 |
defer func() {
|
|
47 |
if r := recover(); r == nil {
|
|
48 |
t.Errorf("should panic when negative index")
|
|
49 |
} else {
|
|
50 |
t.Logf("got panic as expected: %v", r)
|
|
51 |
}
|
|
52 |
}()
|
|
53 |
|
|
54 |
func() {
|
|
55 |
q.Get(-1)
|
|
56 |
}()
|
|
57 |
}()
|
|
58 |
|
|
59 |
func() {
|
|
60 |
defer func() {
|
|
61 |
if r := recover(); r == nil {
|
|
62 |
t.Errorf("should panic when index greater than length")
|
|
63 |
} else {
|
|
64 |
t.Logf("got panic as expected: %v", r)
|
|
65 |
}
|
|
66 |
}()
|
|
67 |
|
|
68 |
func() {
|
|
69 |
q.Get(4)
|
|
70 |
}()
|
|
71 |
}()
|
23 | 72 |
}
|
24 | 73 |
|
25 | 74 |
// General warning: Go's benchmark utility (go test -bench .) increases the number of
|