Skip to content

Commit beaec7d

Browse files
authored
fix: a binary field can marshal to a named string (#371)
* fix: a binary field can marshal to a named string * use BinaryData as the test field
1 parent d14c82e commit beaec7d

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

field/binary.go

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,13 @@ func (f *Binary) Unmarshal(v interface{}) error {
131131
}
132132

133133
func (f *Binary) Marshal(v interface{}) error {
134-
if v == nil || reflect.ValueOf(v).IsZero() {
134+
if v == nil {
135+
f.value = nil
136+
return nil
137+
}
138+
139+
rv := reflect.ValueOf(v)
140+
if rv.IsZero() {
135141
f.value = nil
136142
return nil
137143
}
@@ -158,7 +164,24 @@ func (f *Binary) Marshal(v interface{}) error {
158164
case *[]byte:
159165
f.SetBytes(*v)
160166
default:
161-
return fmt.Errorf("data does not match required *Binary or (string, *string, []byte, *[]byte) type")
167+
kind := rv.Kind()
168+
if kind == reflect.Ptr {
169+
rv = rv.Elem()
170+
kind = rv.Kind()
171+
}
172+
173+
//nolint:exhaustive
174+
switch kind {
175+
case reflect.String:
176+
buf, err := hex.DecodeString(rv.String())
177+
if err != nil {
178+
return fmt.Errorf("failed to convert string to byte: %w", err)
179+
}
180+
181+
f.value = buf
182+
default:
183+
return fmt.Errorf("data does not match required *Binary or (string, *string, []byte, *[]byte) type")
184+
}
162185
}
163186

164187
return nil

message_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2279,6 +2279,17 @@ func TestStructWithTypes(t *testing.T) {
22792279
},
22802280
expectedPackedString: "011040000000000000000000000000000000164242424242424242",
22812281
},
2282+
{
2283+
name: "struct with named string type and value set on a binary field",
2284+
input: struct {
2285+
MTI myString `index:"0"`
2286+
BinaryData myString `index:"4"`
2287+
}{
2288+
MTI: "0110",
2289+
BinaryData: myString("313233"), // "123" in Hex
2290+
},
2291+
expectedPackedString: "011010000000000000000000000000000000123",
2292+
},
22822293

22832294
// Tests for *string type
22842295
{

0 commit comments

Comments
 (0)