github.com/zuoyebang/bitalostable@v1.0.1-0.20240229032404-e3b99a834294/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 "github.com/stretchr/testify/require" 16 "golang.org/x/exp/rand" 17 ) 18 19 func TestGetBytes(t *testing.T) { 20 const size = (1 << 31) - 1 21 block := make([]byte, size) 22 data := getBytes(unsafe.Pointer(&block[0]), size) 23 require.EqualValues(t, len(block), len(data)) 24 } 25 26 func TestDecodeVarint(t *testing.T) { 27 vals := []uint32{ 28 0, 29 1, 30 1 << 7, 31 1 << 8, 32 1 << 14, 33 1 << 15, 34 1 << 20, 35 1 << 21, 36 1 << 28, 37 1 << 29, 38 1 << 31, 39 } 40 buf := make([]byte, 5) 41 for _, v := range vals { 42 binary.PutUvarint(buf, uint64(v)) 43 u, _ := decodeVarint(unsafe.Pointer(&buf[0])) 44 if v != u { 45 fmt.Printf("%d %d\n", v, u) 46 } 47 } 48 } 49 50 func BenchmarkDecodeVarint(b *testing.B) { 51 rng := rand.New(rand.NewSource(uint64(time.Now().UnixNano()))) 52 vals := make([]unsafe.Pointer, 10000) 53 for i := range vals { 54 buf := make([]byte, 5) 55 binary.PutUvarint(buf, uint64(rng.Uint32())) 56 vals[i] = unsafe.Pointer(&buf[0]) 57 } 58 59 b.ResetTimer() 60 var ptr unsafe.Pointer 61 for i, n := 0, 0; i < b.N; i += n { 62 n = len(vals) 63 if n > b.N-i { 64 n = b.N - i 65 } 66 for j := 0; j < n; j++ { 67 _, ptr = decodeVarint(vals[j]) 68 } 69 } 70 if testing.Verbose() { 71 fmt.Fprint(ioutil.Discard, ptr) 72 } 73 }