Skip to content

Commit 516356a

Browse files
committed
loadbalancer: Use ServiceName.Bytes() in BackedInstanceKey.Key
This is more compact than the String() representation and it does need to match the longer form with non-zero source. Add a test case to verify. Signed-off-by: Jussi Maki <jussi@isovalent.com>
1 parent 07f45a2 commit 516356a

2 files changed

Lines changed: 30 additions & 6 deletions

File tree

pkg/loadbalancer/backend.go

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
package loadbalancer
55

66
import (
7-
"bytes"
87
"fmt"
98
"iter"
109
"strings"
@@ -87,11 +86,10 @@ func (k BackendInstanceKey) Key() []byte {
8786
if k.SourcePriority == 0 {
8887
return k.ServiceName.Key()
8988
}
90-
var buf bytes.Buffer
91-
buf.WriteString(k.ServiceName.String())
92-
buf.WriteByte(' ')
93-
buf.WriteByte(k.SourcePriority)
94-
return buf.Bytes()
89+
sk := k.ServiceName.Key()
90+
buf := make([]byte, 0, 2+len(sk))
91+
buf = append(buf, sk...)
92+
return append(buf, ' ', k.SourcePriority)
9593
}
9694

9795
func (be *Backend) GetInstance(name ServiceName) *BackendParams {

pkg/loadbalancer/backend_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// SPDX-License-Identifier: Apache-2.0
2+
// Copyright Authors of Cilium
3+
4+
package loadbalancer
5+
6+
import (
7+
"bytes"
8+
"testing"
9+
10+
"github.com/stretchr/testify/assert"
11+
)
12+
13+
func TestBackendInstanceKey(t *testing.T) {
14+
name := NewServiceNameInCluster("foo", "bar", "baz")
15+
key := BackendInstanceKey{
16+
ServiceName: name,
17+
SourcePriority: 0,
18+
}
19+
assert.True(t, bytes.Equal(key.Key(), name.Key()), "BackendInstanceKey with prio 0 is the ServiceName key")
20+
key.SourcePriority = 1
21+
assert.True(t, bytes.HasPrefix(key.Key(), name.Key()), "BackendInstanceKey with prio 1 has ServiceName key as prefix")
22+
23+
keyBytes := key.Key()
24+
suffix := keyBytes[len(name.Key()):]
25+
assert.Equal(t, []byte{' ', 1}, suffix, "suffix should be space + priority")
26+
}

0 commit comments

Comments
 (0)