-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtraverse_test.go
72 lines (64 loc) · 1.41 KB
/
traverse_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Copyright (c) 2023, Roel Schut. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package env
import (
"reflect"
"testing"
"github.com/stretchr/testify/assert"
)
func TestUnderlyingKind(t *testing.T) {
tests := map[string]struct {
value any
wantKind reflect.Kind
}{
"string": {
value: "",
wantKind: reflect.String,
},
"*string": {
value: (*string)(nil),
wantKind: reflect.String,
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
assert.Equal(t, tc.wantKind, underlyingKind(reflect.TypeOf(tc.value)))
})
}
}
func BenchmarkUnderlyingKind(b *testing.B) {
types := []reflect.Type{
reflect.TypeOf(""),
reflect.TypeOf((*string)(nil)),
reflect.TypeOf((*****string)(nil)),
}
for _, typ := range types {
b.Run("loop_"+typ.String(), func(b *testing.B) {
for i := 0; i < b.N; i++ {
loopUnderlyingKind(typ)
}
})
b.Run("recursive_"+typ.String(), func(b *testing.B) {
for i := 0; i < b.N; i++ {
recursiveUnderlyingKind(typ)
}
})
}
}
//go:noinline
func loopUnderlyingKind(rt reflect.Type) reflect.Kind {
k := rt.Kind()
for k == reflect.Ptr {
rt = rt.Elem()
k = rt.Kind()
}
return k
}
//go:noinline
func recursiveUnderlyingKind(rt reflect.Type) reflect.Kind {
if k := rt.Kind(); k != reflect.Ptr {
return k
}
return recursiveUnderlyingKind(rt.Elem())
}