github.com/petermattis/pebble@v0.0.0-20190905164901-ab51a2166067/sstable/unsafe_test.go (about)

     1  // Copyright 2018 The LevelDB-Go and Pebble Authors. All rights reserved. Use
     2  // of this source code is governed by a BSD-style license that can be found in
     3  // the LICENSE file.
     4  
     5  package sstable
     6  
     7  import (
     8  	"encoding/binary"
     9  	"fmt"
    10  	"io/ioutil"
    11  	"testing"
    12  	"time"
    13  	"unsafe"
    14  
    15  	"golang.org/x/exp/rand"
    16  )
    17  
    18  func TestDecodeVarint(t *testing.T) {
    19  	vals := []uint32{
    20  		0,
    21  		1,
    22  		1 << 7,
    23  		1 << 8,
    24  		1 << 14,
    25  		1 << 15,
    26  		1 << 20,
    27  		1 << 21,
    28  		1 << 28,
    29  		1 << 29,
    30  		1 << 31,
    31  	}
    32  	buf := make([]byte, 5)
    33  	for _, v := range vals {
    34  		binary.PutUvarint(buf, uint64(v))
    35  		u, _ := decodeVarint(unsafe.Pointer(&buf[0]))
    36  		if v != u {
    37  			fmt.Printf("%d %d\n", v, u)
    38  		}
    39  	}
    40  }
    41  
    42  func BenchmarkDecodeVarint(b *testing.B) {
    43  	rng := rand.New(rand.NewSource(uint64(time.Now().UnixNano())))
    44  	vals := make([]unsafe.Pointer, 10000)
    45  	for i := range vals {
    46  		buf := make([]byte, 5)
    47  		binary.PutUvarint(buf, uint64(rng.Uint32()))
    48  		vals[i] = unsafe.Pointer(&buf[0])
    49  	}
    50  
    51  	b.ResetTimer()
    52  	var ptr unsafe.Pointer
    53  	for i, n := 0, 0; i < b.N; i += n {
    54  		n = len(vals)
    55  		if n > b.N-i {
    56  			n = b.N - i
    57  		}
    58  		for j := 0; j < n; j++ {
    59  			_, ptr = decodeVarint(vals[j])
    60  		}
    61  	}
    62  	if testing.Verbose() {
    63  		fmt.Fprint(ioutil.Discard, ptr)
    64  	}
    65  }