瀏覽代碼

Add a mean to get an index, allowing iterations of the queue.

Antoine Grondin 11 年之前
父節點
當前提交
c58145c54b
共有 2 個文件被更改,包括 61 次插入2 次删除
  1. 10 0
      queue.go
  2. 51 2
      queue_test.go

+ 10 - 0
queue.go

@@ -59,6 +59,16 @@ func (q *Queue) Peek() interface{} {
 	return q.buf[q.head]
 }
 
+// Get returns the element at index i in the queue. If the index is invalid, the
+// call will panic.
+func (q *Queue) Get(i int) interface{} {
+	if i >= q.Length() || i < 0 {
+		panic("index out of range")
+	}
+	modi := (q.head + i) % len(q.buf)
+	return q.buf[modi]
+}
+
 // Remove removes the element from the front of the queue. If you actually want the element,
 // call Peek first. If the queue is empty (Length == 0), Remove will put the queue in a bad
 // state and all further operations will be undefined.

+ 51 - 2
queue_test.go

@@ -12,17 +12,66 @@ func TestQueueLength(t *testing.T) {
 	for i := 0; i < 1000; i++ {
 		q.Add(i)
 		if q.Length() != i+1 {
-			t.Error("adding: queue with", i , "elements has length", q.Length())
+			t.Error("adding: queue with", i, "elements has length", q.Length())
 		}
 	}
 	for i := 0; i < 1000; i++ {
 		q.Remove()
 		if q.Length() != 1000-i-1 {
-			t.Error("removing: queue with", 1000-i-i , "elements has length", q.Length())
+			t.Error("removing: queue with", 1000-i-i, "elements has length", q.Length())
 		}
 	}
 }
 
+func TestQueueGet(t *testing.T) {
+	q := New()
+
+	for i := 0; i < 1000; i++ {
+		q.Add(i)
+		for j := 0; j < q.Length(); j++ {
+			if q.Get(j).(int) != j {
+				t.Errorf("index %d doesn't contain %d", j, j)
+			}
+		}
+	}
+}
+
+func TestQueueGetOutOfRangePanics(t *testing.T) {
+	q := New()
+
+	q.Add(1)
+	q.Add(2)
+	q.Add(3)
+
+	func() {
+		defer func() {
+			if r := recover(); r == nil {
+				t.Errorf("should panic when negative index")
+			} else {
+				t.Logf("got panic as expected: %v", r)
+			}
+		}()
+
+		func() {
+			q.Get(-1)
+		}()
+	}()
+
+	func() {
+		defer func() {
+			if r := recover(); r == nil {
+				t.Errorf("should panic when index greater than length")
+			} else {
+				t.Logf("got panic as expected: %v", r)
+			}
+		}()
+
+		func() {
+			q.Get(4)
+		}()
+	}()
+}
+
 // General warning: Go's benchmark utility (go test -bench .) increases the number of
 // iterations until the benchmarks take a reasonable amount of time to run; memory usage
 // is *NOT* considered. On my machine, these benchmarks hit around ~1GB before they've had