Skip to content

Commit 804e878

Browse files
committed
encoding: fix duplicate compressor names
1 parent bc9728f commit 804e878

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

encoding/encoding.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,9 @@ var registeredCompressor = make(map[string]Compressor)
7575
// registered with the same name, the one registered last will take effect.
7676
func RegisterCompressor(c Compressor) {
7777
registeredCompressor[c.Name()] = c
78-
grpcutil.RegisteredCompressorNames = append(grpcutil.RegisteredCompressorNames, c.Name())
78+
if !grpcutil.IsCompressorNameRegistered(c.Name()) {
79+
grpcutil.RegisteredCompressorNames = append(grpcutil.RegisteredCompressorNames, c.Name())
80+
}
7981
}
8082

8183
// GetCompressor returns Compressor for the given compressor name.

encoding/encoding_test.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package encoding
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
7+
"google.golang.org/grpc/internal/grpcutil"
8+
)
9+
10+
type mockNamedCompressor struct {
11+
Compressor
12+
}
13+
14+
func (mockNamedCompressor) Name() string {
15+
return "mock-compressor"
16+
}
17+
18+
func TestDuplicateCompressorRegister(t *testing.T) {
19+
defer func(m map[string]Compressor) { registeredCompressor = m }(registeredCompressor)
20+
defer func(c []string) { grpcutil.RegisteredCompressorNames = c }(grpcutil.RegisteredCompressorNames)
21+
registeredCompressor = map[string]Compressor{}
22+
grpcutil.RegisteredCompressorNames = []string{}
23+
24+
RegisterCompressor(&mockNamedCompressor{})
25+
26+
// Register another instance of the same compressor.
27+
mc := &mockNamedCompressor{}
28+
RegisterCompressor(mc)
29+
if got := registeredCompressor["mock-compressor"]; got != mc {
30+
t.Fatalf("Unexpected compressor, got: %+v, want:%+v", got, mc)
31+
}
32+
33+
wantNames := []string{"mock-compressor"}
34+
if !reflect.DeepEqual(wantNames, grpcutil.RegisteredCompressorNames) {
35+
t.Fatalf("Unexpected compressor names, got: %+v, want:%+v", grpcutil.RegisteredCompressorNames, wantNames)
36+
}
37+
}

0 commit comments

Comments
 (0)