github.com/FusionFoundation/efsn/v4@v4.2.0/common/prque/sstack_test.go (about) 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 9 package prque 10 11 import ( 12 "math/rand" 13 "sort" 14 "testing" 15 ) 16 17 func TestSstack(t *testing.T) { 18 // Create some initial data 19 size := 16 * blockSize 20 data := make([]*item, size) 21 for i := 0; i < size; i++ { 22 data[i] = &item{rand.Int(), rand.Int63()} 23 } 24 stack := newSstack(nil, false) 25 for rep := 0; rep < 2; rep++ { 26 // Push all the data into the stack, pop out every second 27 secs := []*item{} 28 for i := 0; i < size; i++ { 29 stack.Push(data[i]) 30 if i%2 == 0 { 31 secs = append(secs, stack.Pop().(*item)) 32 } 33 } 34 rest := []*item{} 35 for stack.Len() > 0 { 36 rest = append(rest, stack.Pop().(*item)) 37 } 38 // Make sure the contents of the resulting slices are ok 39 for i := 0; i < size; i++ { 40 if i%2 == 0 && data[i] != secs[i/2] { 41 t.Errorf("push/pop mismatch: have %v, want %v.", secs[i/2], data[i]) 42 } 43 if i%2 == 1 && data[i] != rest[len(rest)-i/2-1] { 44 t.Errorf("push/pop mismatch: have %v, want %v.", rest[len(rest)-i/2-1], data[i]) 45 } 46 } 47 } 48 } 49 50 func TestSstackSort(t *testing.T) { 51 // Create some initial data 52 size := 16 * blockSize 53 data := make([]*item, size) 54 for i := 0; i < size; i++ { 55 data[i] = &item{rand.Int(), int64(i)} 56 } 57 // Push all the data into the stack 58 stack := newSstack(nil, false) 59 for _, val := range data { 60 stack.Push(val) 61 } 62 // Sort and pop the stack contents (should reverse the order) 63 sort.Sort(stack) 64 for _, val := range data { 65 out := stack.Pop() 66 if out != val { 67 t.Errorf("push/pop mismatch after sort: have %v, want %v.", out, val) 68 } 69 } 70 } 71 72 func TestSstackReset(t *testing.T) { 73 // Create some initial data 74 size := 16 * blockSize 75 data := make([]*item, size) 76 for i := 0; i < size; i++ { 77 data[i] = &item{rand.Int(), rand.Int63()} 78 } 79 stack := newSstack(nil, false) 80 for rep := 0; rep < 2; rep++ { 81 // Push all the data into the stack, pop out every second 82 secs := []*item{} 83 for i := 0; i < size; i++ { 84 stack.Push(data[i]) 85 if i%2 == 0 { 86 secs = append(secs, stack.Pop().(*item)) 87 } 88 } 89 // Reset and verify both pulled and stack contents 90 stack.Reset() 91 if stack.Len() != 0 { 92 t.Errorf("stack not empty after reset: %v", stack) 93 } 94 for i := 0; i < size; i++ { 95 if i%2 == 0 && data[i] != secs[i/2] { 96 t.Errorf("push/pop mismatch: have %v, want %v.", secs[i/2], data[i]) 97 } 98 } 99 } 100 }