github.com/andy2046/gopie@v0.7.0/pkg/skiplist/skiplist_test.go (about)

     1  package skiplist
     2  
     3  import (
     4  	"fmt"
     5  	"strconv"
     6  	"sync"
     7  	"testing"
     8  	"unsafe"
     9  )
    10  
    11  var testList *SkipList
    12  
    13  func init() {
    14  	testList = New()
    15  
    16  	for i := 0; i <= 10000000; i++ {
    17  		testList.Set(strconv.Itoa(i), int64(i))
    18  	}
    19  
    20  	var sl SkipList
    21  	var el Element
    22  	fmt.Printf("Sizeof(SkipList) = %v bytes Sizeof(Element) = %v bytes\n", unsafe.Sizeof(sl), unsafe.Sizeof(el))
    23  	fmt.Printf("Alignof(SkipList) = %v bytes Alignof(Element) = %v bytes\n", unsafe.Alignof(&sl), unsafe.Alignof(el))
    24  }
    25  
    26  func TestGetSet(t *testing.T) {
    27  	list := New()
    28  	n := 1000000
    29  	wg := &sync.WaitGroup{}
    30  	wg.Add(2)
    31  
    32  	go func() {
    33  		for i := 0; i < n; i++ {
    34  			list.Set(strconv.Itoa(i), int64(i))
    35  		}
    36  		wg.Done()
    37  	}()
    38  
    39  	go func() {
    40  		for i := 0; i < n; i++ {
    41  			list.Get(strconv.Itoa(i))
    42  		}
    43  		wg.Done()
    44  	}()
    45  
    46  	wg.Wait()
    47  	if list.Len() != n {
    48  		t.Fail()
    49  	}
    50  }
    51  
    52  func TestCRUD(t *testing.T) {
    53  	list := New()
    54  	list.Set("A", 1)
    55  	list.Set("B", 2)
    56  	list.Set("C", 3)
    57  	list.Set("D", 4)
    58  	list.Set("E", 5)
    59  	list.Set("C", 9)
    60  	list.Remove("X")
    61  	list.Remove("D")
    62  
    63  	a := list.Get("A")
    64  	b := list.Get("B")
    65  	c := list.Get("C")
    66  	d := list.Get("D")
    67  	e := list.Get("E")
    68  	x := list.Get("X")
    69  
    70  	if a == nil || a.Key() != "A" || a.Value() != 1 {
    71  		t.Fatal("wrong value", a)
    72  	}
    73  	if b == nil || b.Key() != "B" || b.Value() != 2 {
    74  		t.Fatal("wrong value", b)
    75  	}
    76  	if c == nil || c.Key() != "C" || c.Value() != 9 {
    77  		t.Fatal("wrong value", c)
    78  	}
    79  	if d != nil {
    80  		t.Fatal("wrong value", d)
    81  	}
    82  	if e == nil || e.Key() != "E" || e.Value() != 5 {
    83  		t.Fatal("wrong value", e)
    84  	}
    85  	if x != nil {
    86  		t.Fatal("wrong value", x)
    87  	}
    88  
    89  }
    90  
    91  func BenchmarkSet(b *testing.B) {
    92  	b.ReportAllocs()
    93  	list := New()
    94  
    95  	for i := 0; i < b.N; i++ {
    96  		list.Set(strconv.Itoa(i), int64(i))
    97  	}
    98  }
    99  
   100  func BenchmarkGet(b *testing.B) {
   101  	b.ReportAllocs()
   102  
   103  	for i := 0; i < b.N; i++ {
   104  		e := testList.Get(strconv.Itoa(i))
   105  		if e == nil {
   106  			b.Fatal("fail to Get")
   107  		}
   108  	}
   109  }