Skip to content

Commit 6a516b2

Browse files
committed
feat(message): add UnmarshalText/MarshalText methods to CompressionCodec
This allows the user to include a CompressionCodec in a structure to be unmarshaled from a configuration file using YAML/JSON/whatever.
1 parent 3f90bc7 commit 6a516b2

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

message.go

+22
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,28 @@ func (cc CompressionCodec) String() string {
4242
}[int(cc)]
4343
}
4444

45+
// UnmarshalText returns a CompressionCodec from its string representation.
46+
func (cc *CompressionCodec) UnmarshalText(text []byte) error {
47+
codecs := map[string]CompressionCodec{
48+
"none": CompressionNone,
49+
"gzip": CompressionGZIP,
50+
"snappy": CompressionSnappy,
51+
"lz4": CompressionLZ4,
52+
"zstd": CompressionZSTD,
53+
}
54+
codec, ok := codecs[string(text)]
55+
if !ok {
56+
return fmt.Errorf("cannot parse %q as a compression codec", string(text))
57+
}
58+
*cc = codec
59+
return nil
60+
}
61+
62+
// MarshalText transforms a CompressionCodec into its string representation.
63+
func (cc CompressionCodec) MarshalText() ([]byte, error) {
64+
return []byte(cc.String()), nil
65+
}
66+
4567
// Message is a kafka message type
4668
type Message struct {
4769
Codec CompressionCodec // codec used to compress the message contents

message_test.go

+29
Original file line numberDiff line numberDiff line change
@@ -244,3 +244,32 @@ func TestMessageDecodingUnknownVersions(t *testing.T) {
244244
t.Error("Decoding an unknown magic byte produced an unknown error ", err)
245245
}
246246
}
247+
248+
func TestCompressionCodecUnmarshal(t *testing.T) {
249+
cases := []struct {
250+
Input string
251+
Expected CompressionCodec
252+
ExpectedError bool
253+
}{
254+
{"none", CompressionNone, false},
255+
{"zstd", CompressionZSTD, false},
256+
{"gzip", CompressionGZIP, false},
257+
{"unknown", CompressionNone, true},
258+
}
259+
for _, c := range cases {
260+
var cc CompressionCodec
261+
err := cc.UnmarshalText([]byte(c.Input))
262+
if err != nil && !c.ExpectedError {
263+
t.Errorf("UnmarshalText(%q) error:\n%+v", c.Input, err)
264+
continue
265+
}
266+
if err == nil && c.ExpectedError {
267+
t.Errorf("UnmarshalText(%q) got %v but expected error", c.Input, cc)
268+
continue
269+
}
270+
if cc != c.Expected {
271+
t.Errorf("UnmarshalText(%q) got %v but expected %v", c.Input, cc, c.Expected)
272+
continue
273+
}
274+
}
275+
}

0 commit comments

Comments
 (0)