github.com/metaworking/channeld@v0.7.3/pkg/channeld/util_test.go (about) 1 package channeld 2 3 import ( 4 "fmt" 5 "reflect" 6 "sync" 7 "testing" 8 "unsafe" 9 10 "github.com/metaworking/channeld/pkg/common" 11 "github.com/stretchr/testify/assert" 12 ) 13 14 //go:linkname typelinks reflect.typelinks 15 func typelinks() (sections []unsafe.Pointer, offset [][]int32) 16 17 //go:linkname add reflect.add 18 func add(p unsafe.Pointer, x uintptr, whySafe string) unsafe.Pointer 19 20 func TestReflectionTypes(t *testing.T) { 21 22 sections, offsets := typelinks() 23 for i, base := range sections { 24 for _, offset := range offsets[i] { 25 typeAddr := add(base, uintptr(offset), "") 26 typ := reflect.TypeOf(*(*interface{})(unsafe.Pointer(&typeAddr))) 27 fmt.Println(typ) 28 } 29 } 30 } 31 32 func TestGetNextId(t *testing.T) { 33 m := make(map[uint32]interface{}) 34 var index uint32 = 1 35 var ok bool 36 37 index, _ = GetNextId(&m, index, 1, 3) 38 assert.EqualValues(t, 1, index) 39 m[index] = "aaa" 40 41 index, _ = GetNextId(&m, index, 1, 3) 42 assert.EqualValues(t, 2, index) 43 m[index] = "bbb" 44 45 index, _ = GetNextId(&m, index, 1, 3) 46 assert.EqualValues(t, 3, index) 47 m[index] = "ccc" 48 49 _, ok = GetNextId(&m, index, 1, 3) 50 assert.False(t, ok) 51 } 52 53 func BenchmarkGetNextId(b *testing.B) { 54 m := make(map[uint32]interface{}) 55 var index uint32 = 1 56 var ok bool 57 58 for i := 0; i < b.N; i++ { 59 index, ok = GetNextId(&m, index, 1, 65535) 60 if ok { 61 m[index] = i 62 } else { 63 break 64 } 65 } 66 } 67 68 func TestGetNextIdSync(t *testing.T) { 69 m := sync.Map{} 70 var index common.ChannelId = 1 71 var ok bool 72 73 index, _ = GetNextIdSync(&m, index, 1, 3) 74 assert.EqualValues(t, 1, index) 75 m.Store(index, "aaa") 76 77 index, _ = GetNextIdSync(&m, index, 1, 3) 78 assert.EqualValues(t, 2, index) 79 m.Store(index, "bbb") 80 81 index, _ = GetNextIdSync(&m, index, 1, 3) 82 assert.EqualValues(t, 3, index) 83 m.Store(index, "ccc") 84 85 _, ok = GetNextIdSync(&m, index, 1, 3) 86 assert.False(t, ok) 87 88 } 89 90 // 3x slower as of BenchmarkGetNextId 91 func BenchmarkGetNextIdSync(b *testing.B) { 92 m := sync.Map{} 93 var index common.ChannelId = 1 94 var ok bool 95 96 for i := 0; i < b.N; i++ { 97 index, ok = GetNextIdSync(&m, index, 1, 65535) 98 if ok { 99 m.Store(index, i) 100 } else { 101 break 102 } 103 } 104 }