Debian Codegraph @

pdata/pprofile/string_table_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package pprofile
5
6 import (
7 "strconv"
8 "testing"
9
10 "github.com/stretchr/testify/assert"
11 "github.com/stretchr/testify/require"
12
13 "go.opentelemetry.io/collector/pdata/pcommon"
14 )
15
16 func TestSetString(t *testing.T) {
17 table := pcommon.NewStringSlice()
18 v := "test"
19 v2 := "test2"
20
21 // Put a first value
22 idx, err := SetString(table, v)
23 require.NoError(t, err)
24 assert.Equal(t, 1, table.Len())
25 assert.Equal(t, int32(0), idx)
26
27 // Put the same string
28 // This should be a no-op.
29 idx, err = SetString(table, v)
30 require.NoError(t, err)
31 assert.Equal(t, 1, table.Len())
32 assert.Equal(t, int32(0), idx)
33
34 // Set a new value
35 // This sets the index and adds to the table.
36 idx, err = SetString(table, v2)
37 require.NoError(t, err)
38 assert.Equal(t, 2, table.Len())
39 assert.Equal(t, int32(table.Len()-1), idx)
40
41 // Set an existing value
42 idx, err = SetString(table, v)
43 require.NoError(t, err)
44 assert.Equal(t, 2, table.Len())
45 assert.Equal(t, int32(0), idx)
46 // Set another existing value
47 idx, err = SetString(table, v2)
48 require.NoError(t, err)
49 assert.Equal(t, 2, table.Len())
50 assert.Equal(t, int32(table.Len()-1), idx)
51 }
52
53 func BenchmarkSetString(b *testing.B) {
54 for _, bb := range []struct {
55 name string
56 val string
57
58 runBefore func(*testing.B, pcommon.StringSlice)
59 }{
60 {
61 name: "with a new value",
62 val: "test",
63 },
64 {
65 name: "with an existing value",
66 val: "test",
67
68 runBefore: func(_ *testing.B, table pcommon.StringSlice) {
69 table.Append("test")
70 },
71 },
72 {
73 name: "with a duplicate value",
74 val: "test",
75
76 runBefore: func(_ *testing.B, table pcommon.StringSlice) {
77 _, err := SetString(table, "test")
78 require.NoError(b, err)
79 },
80 },
81 {
82 name: "with a hundred values to loop through",
83 val: "test",
84
85 runBefore: func(_ *testing.B, table pcommon.StringSlice) {
86 for i := range 100 {
87 table.Append(strconv.Itoa(i))
88 }
89 },
90 },
91 } {
92 b.Run(bb.name, func(b *testing.B) {
93 table := pcommon.NewStringSlice()
94
95 if bb.runBefore != nil {
96 bb.runBefore(b, table)
97 }
98
99 b.ResetTimer()
100 b.ReportAllocs()
101
102 for b.Loop() {
103 _, _ = SetString(table, bb.val)
104 }
105 })
106 }
107 }