Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(message): add UnmarshalText method to CompressionCodec #2172

Merged
merged 1 commit into from
Mar 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions message.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,28 @@ func (cc CompressionCodec) String() string {
}[int(cc)]
}

// UnmarshalText returns a CompressionCodec from its string representation.
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 = codec
return nil
}

// MarshalText transforms a CompressionCodec into its string representation.
func (cc CompressionCodec) MarshalText() ([]byte, error) {
return []byte(cc.String()), 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 != c.Expected {
t.Errorf("UnmarshalText(%q) got %v but expected %v", c.Input, cc, c.Expected)
continue
}
}
}