Skip to content
Open
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
2 changes: 1 addition & 1 deletion decode_hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ func WeaklyTypedHook(
dataType := dataVal.Type()
elemKind := dataType.Elem().Kind()
if elemKind == reflect.Uint8 {
return string(dataVal.Interface().([]uint8)), nil
return string(dataVal.Bytes()), nil
}
case reflect.Uint:
return strconv.FormatUint(dataVal.Uint(), 10), nil
Expand Down
14 changes: 14 additions & 0 deletions decode_hooks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -824,6 +824,8 @@ func TestStringToIPNetHookFunc(t *testing.T) {
}

func TestWeaklyTypedHook(t *testing.T) {
type octet uint8
type bytes []byte
var f DecodeHookFunc = WeaklyTypedHook

strValue := reflect.ValueOf("")
Expand Down Expand Up @@ -867,6 +869,18 @@ func TestWeaklyTypedHook(t *testing.T) {
"foo", // byte slice converts to string
false,
},
{
reflect.ValueOf(bytes("foo")),
strValue,
"foo",
false,
},
{
reflect.ValueOf([]octet{'f', 'o', 'o'}),
strValue,
"foo",
false,
},

{
reflect.ValueOf(uint(7)),
Expand Down
4 changes: 2 additions & 2 deletions mapstructure.go
Original file line number Diff line number Diff line change
Expand Up @@ -756,10 +756,10 @@ func (d *Decoder) decodeString(name string, data any, val reflect.Value) error {
if dataKind == reflect.Array {
uints = make([]uint8, dataVal.Len())
for i := range uints {
uints[i] = dataVal.Index(i).Interface().(uint8)
uints[i] = uint8(dataVal.Index(i).Uint())
}
} else {
uints = dataVal.Interface().([]uint8)
uints = dataVal.Bytes()
}
val.SetString(string(uints))
default:
Expand Down
32 changes: 32 additions & 0 deletions mapstructure_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1524,6 +1524,38 @@ func TestDecode_StructMatch(t *testing.T) {
}
}

func TestWeakDecode_NamedBytesToString(t *testing.T) {
type octet uint8
type bytes []byte
type octets []octet

cases := []struct {
name string
input any
want string
}{
{"named slice", bytes{'f', 'o', 'o'}, "foo"},
{"named element slice", []octet{'f', 'o', 'o'}, "foo"},
{"named slice and elements", octets{'f', 'o', 'o'}, "foo"},
{"named element array", [3]octet{'f', 'o', 'o'}, "foo"},
{"nil slice", octets(nil), ""},
{"empty slice", octets{}, ""},
{"empty array", [0]octet{}, ""},
{"binary bytes", []octet{0, 128, 255}, "\x00\x80\xff"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
var got string
if err := WeakDecode(tc.input, &got); err != nil {
t.Fatal(err)
}
if got != tc.want {
t.Fatalf("expected %q, got %q", tc.want, got)
}
})
}
}

func TestDecode_TypeConversion(t *testing.T) {
input := map[string]any{
"IntToFloat": 42,
Expand Down