Codebase list golang-gopkg-eapache-queue.v1 / d8809f0
Add bound checks. Add test for bound checks. Antoine Grondin 9 years ago
2 changed file(s) with 64 addition(s) and 25 deletion(s). Raw diff Collapse all Expand all
5555 // Peek returns the element at the head of the queue. If the queue is empty (Length == 0),
5656 // Peek does not panic, it simply returns garbage.
5757 func (q *Queue) Peek() interface{} {
58 if q.Length() <= 0 {
59 panic("queue: empty queue")
60 }
5861 return q.buf[q.head]
5962 }
6063
6265 // call will panic.
6366 func (q *Queue) Get(i int) interface{} {
6467 if i >= q.Length() || i < 0 {
65 panic("index out of range")
68 panic("queue: index out of range")
6669 }
6770 modi := (q.head + i) % len(q.buf)
6871 return q.buf[modi]
7275 // call Peek first. If the queue is empty (Length == 0), Remove will put the queue in a bad
7376 // state and all further operations will be undefined.
7477 func (q *Queue) Remove() {
78 if q.Length() <= 0 {
79 panic("queue: empty queue")
80 }
7581 q.buf[q.head] = nil
7682 q.head = (q.head + 1) % len(q.buf)
7783 q.count--
4242 q.Add(2)
4343 q.Add(3)
4444
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 }()
45 assertPanics(t, "should panic when negative index", func() {
46 q.Get(-1)
47 })
5348
54 func() {
55 q.Get(-1)
56 }()
49 assertPanics(t, "should panic when index greater than length", func() {
50 q.Get(4)
51 })
52 }
53
54 func TestQueuePeekOutOfRangePanics(t *testing.T) {
55 q := New()
56
57 assertPanics(t, "should panic when peeking empty queue", func() {
58 q.Peek()
59 })
60
61 q.Add(1)
62 q.Remove()
63
64 assertPanics(t, "should panic when peeking emptied queue", func() {
65 q.Peek()
66 })
67 }
68
69 func TestQueueRemoveOutOfRangePanics(t *testing.T) {
70 q := New()
71
72 assertPanics(t, "should panic when removing empty queue", func() {
73 q.Remove()
74 })
75
76 q.Add(1)
77 q.Remove()
78
79 assertPanics(t, "should panic when removing emptied queue", func() {
80 q.Remove()
81 })
82 }
83
84 func assertPanics(t *testing.T, name string, f func()) {
85 defer func() {
86 if r := recover(); r == nil {
87 t.Errorf("%s: didn't panic as expected", name)
88 } else {
89 t.Logf("%s: got panic as expected: %v", name, r)
90 }
5791 }()
5892
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 }()
93 f()
7294 }
7395
7496 // General warning: Go's benchmark utility (go test -bench .) increases the number of
86108 }
87109 }
88110
111 func BenchmarkQueueGet(b *testing.B) {
112 q := New()
113 for i := 0; i < b.N; i++ {
114 q.Add(i)
115 }
116 b.ResetTimer()
117 for i := 0; i < b.N; i++ {
118 q.Get(i)
119 }
120 }
121
89122 func BenchmarkQueueTickTock(b *testing.B) {
90123 q := New()
91124 for i := 0; i < b.N; i++ {