Skip to content

Commit dbf175d

Browse files
authored
support marshaling named string types (#344)
1 parent 84ef65b commit dbf175d

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

field/string.go

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,10 @@ func (f *String) Marshal(v interface{}) error {
147147
if v == nil {
148148
f.value = ""
149149
return nil
150-
} else if reflect.ValueOf(v).IsZero() {
150+
}
151+
152+
rv := reflect.ValueOf(v)
153+
if rv.IsZero() {
151154
if !strings.Contains(reflect.ValueOf(v).Type().String(), "int") {
152155
f.value = ""
153156
return nil
@@ -178,7 +181,18 @@ func (f *String) Marshal(v interface{}) error {
178181
f.value = strconv.FormatInt(*v, 10)
179182
}
180183
default:
181-
return fmt.Errorf("data does not match required *String or (string, *string, int, *int) type")
184+
kind := rv.Kind()
185+
if kind == reflect.Ptr {
186+
rv = rv.Elem()
187+
kind = rv.Kind()
188+
}
189+
190+
switch kind {
191+
case reflect.String:
192+
f.value = rv.String()
193+
default:
194+
return fmt.Errorf("data does not match required *String or (string, *string, int, *int) type")
195+
}
182196
}
183197

184198
return nil

message_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2179,6 +2179,8 @@ func TestStructWithTypes(t *testing.T) {
21792179
},
21802180
}
21812181

2182+
type myString string
2183+
21822184
t.Run("pack", func(t *testing.T) {
21832185
panInt := 4242424242424242
21842186
panStr := "4242424242424242"
@@ -2224,6 +2226,19 @@ func TestStructWithTypes(t *testing.T) {
22242226
expectedPackedString: "01104000000000000000000000000000000000",
22252227
},
22262228

2229+
// Tests for named string type
2230+
{
2231+
name: "struct with named string type and value set",
2232+
input: struct {
2233+
MTI myString `index:"0"`
2234+
PrimaryAccountNumber myString `index:"2"`
2235+
}{
2236+
MTI: "0110",
2237+
PrimaryAccountNumber: myString(panStr),
2238+
},
2239+
expectedPackedString: "011040000000000000000000000000000000164242424242424242",
2240+
},
2241+
22272242
// Tests for *string type
22282243
{
22292244
name: "struct with *string type and value set",
@@ -2442,6 +2457,15 @@ func TestStructWithTypes(t *testing.T) {
24422457
}{},
24432458
},
24442459

2460+
// Tests for named string type
2461+
{
2462+
name: "struct with named string type",
2463+
input: &struct {
2464+
MTI myString `index:"0"`
2465+
PrimaryAccountNumber myString `index:"2"`
2466+
}{},
2467+
},
2468+
24452469
// Tests for *string type
24462470
{
24472471
name: "struct with *string type",

0 commit comments

Comments
 (0)