github.com/scottcagno/storage@v1.8.0/pkg/hashmap/openaddr/sharded_test.go (about)

     1  package openaddr
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/scottcagno/storage/pkg/util"
     6  	"log"
     7  	"strconv"
     8  	"testing"
     9  )
    10  
    11  func TestShardedHashMap(t *testing.T) {
    12  	count := 1000000
    13  	hm := NewShardedHashMap(128)
    14  	for i := 0; i < count; i++ {
    15  		_, ok := hm.Set(strconv.Itoa(i), nil)
    16  		if ok {
    17  			t.Errorf("error: could not located value for key: %q\n", strconv.Itoa(i))
    18  		}
    19  	}
    20  	if hm.Len() != count {
    21  		t.Errorf("error: incorrect count of entries\n")
    22  	}
    23  	fmt.Printf("v2.hashmap containing %d entries is taking %d bytes (%.2f kb, %.2f mb)\n",
    24  		count, util.Sizeof(hm), float64(util.Sizeof(hm)/1024), float64(util.Sizeof(hm)/1024/1024))
    25  	for i := 0; i < count; i++ {
    26  		_, ok := hm.Get(strconv.Itoa(i))
    27  		if !ok {
    28  			t.Errorf("error: could not located value for key: %q\n", strconv.Itoa(i))
    29  		}
    30  	}
    31  	for i := 0; i < count; i++ {
    32  		_, ok := hm.Del(strconv.Itoa(i))
    33  		if !ok {
    34  			t.Errorf("error: could not remove value for key: %q\n", strconv.Itoa(i))
    35  		}
    36  	}
    37  	if hm.Len() != count-count {
    38  		t.Errorf("error: incorrect count of entries\n")
    39  	}
    40  	hm.Close()
    41  }
    42  
    43  func TestShardedHashMap_SetAndGetBit(t *testing.T) {
    44  	hm := NewShardedHashMap(128)
    45  	hm.SetBit("mykey", 24, 1)
    46  	hm.SetBit("mykey", 3, 1)
    47  	hm.SetBit("mykey", 4, 1)
    48  	b, ok := hm.GetBit("mykey", 3)
    49  	fmt.Printf("hm.GetBit('mykey', 3)=%.32b (%v)\n", b, ok)
    50  	hm.SetBit("mykey", 3, 0)
    51  	b, ok = hm.GetBit("mykey", 3)
    52  	fmt.Printf("hm.GetBit('mykey', 3)=%.32b (%v)\n", b, ok)
    53  	hm.SetBit("mykey", 24, 1)
    54  	b, ok = hm.GetBit("mykey", 24)
    55  	fmt.Printf("hm.GetBit('mykey', 24)=%.32b (%v)\n", b, ok)
    56  	hm.Close()
    57  }
    58  
    59  func TestShardedHashMap_SetAndGetUint(t *testing.T) {
    60  	hm := NewShardedHashMap(128)
    61  
    62  	hm.SetUint("counter", 1)
    63  	n, ok := hm.GetUint("counter")
    64  	fmt.Println(n, ok)
    65  
    66  	n++
    67  	hm.SetUint("counter", n)
    68  	n, ok = hm.GetUint("counter")
    69  	fmt.Println(n, ok)
    70  
    71  	n += 8
    72  	hm.SetUint("counter", n)
    73  	n, ok = hm.GetUint("counter")
    74  	fmt.Println(n, ok)
    75  
    76  	hm.Close()
    77  }
    78  
    79  func PrintBits(b []byte) {
    80  	//var res string = "16" // set this to the "bit resolution" you'd like to see
    81  	var res = strconv.Itoa(8)
    82  	log.Printf("%."+res+"b (%s bits)", b, res)
    83  }