Skip to content

Commit

Permalink
feat(message): add UnmarshalText method to CompressionCodec
Browse files Browse the repository at this point in the history
This allows the user to include a CompressionCodec in a structure to
be unmarshaled from a configuration file using YAML/JSON/whatever.
  • Loading branch information
vincentbernat committed Mar 7, 2022
1 parent 3f90bc7 commit 79a4d64
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
16 changes: 16 additions & 0 deletions message.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,22 @@ func (cc CompressionCodec) String() string {
}[int(cc)]
}

func (cc *CompressionCodec) UnmarshalText(text []byte) error {
codecs := map[string]CompressionCodec{
"none": CompressionNone,
"gzip": CompressionGZIP,
"snappy": CompressionSnappy,
"lz4": CompressionLZ4,
"zstd": CompressionZSTD,
}
codec, ok := codecs[string(text)]
if !ok {
return fmt.Errorf("cannot parse %q as a compression codec", string(text))
}
*cc = CompressionCodec(codec)
return nil
}

// Message is a kafka message type
type Message struct {
Codec CompressionCodec // codec used to compress the message contents
Expand Down
29 changes: 29 additions & 0 deletions message_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -244,3 +244,32 @@ func TestMessageDecodingUnknownVersions(t *testing.T) {
t.Error("Decoding an unknown magic byte produced an unknown error ", err)
}
}

func TestCompressionCodecUnmarshal(t *testing.T) {
cases := []struct {
Input string
Expected CompressionCodec
ExpectedError bool
}{
{"none", CompressionNone, false},
{"zstd", CompressionZSTD, false},
{"gzip", CompressionGZIP, false},
{"unknown", CompressionNone, true},
}
for _, c := range cases {
var cc CompressionCodec
err := cc.UnmarshalText([]byte(c.Input))
if err != nil && !c.ExpectedError {
t.Errorf("UnmarshalText(%q) error:\n%+v", c.Input, err)
continue
}
if err == nil && c.ExpectedError {
t.Errorf("UnmarshalText(%q) got %v but expected error", c.Input, cc)
continue
}
if cc != CompressionCodec(c.Expected) {
t.Errorf("UnmarshalText(%q) got %v but expected %v", c.Input, cc, c.Expected)
continue
}
}
}

0 comments on commit 79a4d64

Please sign in to comment.