queue_test.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // CookieJar - A contestant's algorithm toolbox
  2. // Copyright (c) 2013 Peter Szilagyi. All rights reserved.
  3. //
  4. // CookieJar is dual licensed: use of this source code is governed by a BSD
  5. // license that can be found in the LICENSE file. Alternatively, the CookieJar
  6. // toolbox may be used in accordance with the terms and conditions contained
  7. // in a signed written agreement between you and the author(s).
  8. package queue
  9. import (
  10. "math/rand"
  11. "testing"
  12. )
  13. func TestQueue(t *testing.T) {
  14. // Create some initial data
  15. size := 16 * blockSize
  16. data := make([]int, size)
  17. for i := 0; i < size; i++ {
  18. data[i] = rand.Int()
  19. }
  20. queue := New()
  21. for rep := 0; rep < 2; rep++ {
  22. // Push all the data into the queue, pop out every second, then the rest
  23. outs := []int{}
  24. for i := 0; i < size; i++ {
  25. queue.Push(data[i])
  26. if i%2 == 0 {
  27. outs = append(outs, queue.Pop().(int))
  28. if i > 0 && queue.Front() != data[len(outs)] {
  29. t.Errorf("pop/front mismatch: have %v, want %v.", queue.Front(), data[len(outs)])
  30. }
  31. }
  32. if queue.Size() != (i+1)/2 {
  33. t.Errorf("size mismatch: have %v, want %v.", queue.Size(), (i+1)/2)
  34. }
  35. }
  36. for !queue.Empty() {
  37. outs = append(outs, queue.Pop().(int))
  38. }
  39. // Make sure the contents of the resulting slices are ok
  40. for i := 0; i < size; i++ {
  41. if data[i] != outs[i] {
  42. t.Errorf("push/pop mismatch: have %v, want %v.", outs[i], data[i])
  43. }
  44. }
  45. }
  46. }
  47. func TestReset(t *testing.T) {
  48. size := 16 * blockSize
  49. queue := New()
  50. for rep := 0; rep < 2; rep++ {
  51. // Push some stuff into the queue
  52. for i := 0; i < size; i++ {
  53. queue.Push(i)
  54. }
  55. // Clear and verify
  56. queue.Reset()
  57. if !queue.Empty() {
  58. t.Errorf("queue not empty after reset: %v", queue)
  59. }
  60. // Push some stuff into the queue and verify
  61. for i := 0; i < size; i++ {
  62. queue.Push(i)
  63. }
  64. for i := 0; i < size; i++ {
  65. if queue.Front() != i {
  66. t.Errorf("corrupt state after reset: have %v, want %v.", queue.Front(), i)
  67. }
  68. queue.Pop()
  69. }
  70. }
  71. }
  72. func BenchmarkPush(b *testing.B) {
  73. queue := New()
  74. for i := 0; i < b.N; i++ {
  75. queue.Push(i)
  76. }
  77. }
  78. func BenchmarkPop(b *testing.B) {
  79. queue := New()
  80. for i := 0; i < b.N; i++ {
  81. queue.Push(i)
  82. }
  83. b.ResetTimer()
  84. for !queue.Empty() {
  85. queue.Pop()
  86. }
  87. }