Codebase list golang-gopkg-eapache-queue.v1 / c58145c
Add a mean to get an index, allowing iterations of the queue. Antoine Grondin 9 years ago
2 changed file(s) with 61 addition(s) and 2 deletion(s). Raw diff Collapse all Expand all
5858 return q.buf[q.head]
5959 }
6060
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
6171 // Remove removes the element from the front of the queue. If you actually want the element,
6272 // call Peek first. If the queue is empty (Length == 0), Remove will put the queue in a bad
6373 // state and all further operations will be undefined.
1111 for i := 0; i < 1000; i++ {
1212 q.Add(i)
1313 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())
1515 }
1616 }
1717 for i := 0; i < 1000; i++ {
1818 q.Remove()
1919 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())
2121 }
2222 }
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 }()
2372 }
2473
2574 // General warning: Go's benchmark utility (go test -bench .) increases the number of