bencode: Improve support for embedded structs

This commit is contained in:
Matt Joiner 2021-05-24 17:31:52 +10:00
parent 25d2eea12d
commit 047cdbae0d
2 changed files with 20 additions and 7 deletions

View File

@ -253,14 +253,19 @@ func parseStructFields(struct_ reflect.Type, each func(key string, df dictField)
i := _i
f := struct_.Field(i)
if f.Anonymous {
parseStructFields(f.Type.Elem(), func(key string, df dictField) {
t := f.Type
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
parseStructFields(t, func(key string, df dictField) {
innerGet := df.Get
df.Get = func(value reflect.Value) func(reflect.Value) {
anonPtr := value.Field(i)
if anonPtr.IsNil() {
if anonPtr.Kind() == reflect.Ptr && anonPtr.IsNil() {
anonPtr.Set(reflect.New(f.Type.Elem()))
anonPtr = anonPtr.Elem()
}
return innerGet(anonPtr.Elem())
return innerGet(anonPtr)
}
each(key, df)
})

View File

@ -231,16 +231,24 @@ func makeEncodeFields(t reflect.Type) (fs []encodeField) {
continue
}
if f.Anonymous {
anonEFs := makeEncodeFields(f.Type.Elem())
t := f.Type
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
anonEFs := makeEncodeFields(t)
for aefi := range anonEFs {
anonEF := anonEFs[aefi]
bottomField := anonEF
bottomField.i = func(v reflect.Value) reflect.Value {
v = v.Field(i)
if v.IsNil() {
return reflect.Value{}
if v.Kind() == reflect.Ptr {
if v.IsNil() {
// This will skip serializing this value.
return reflect.Value{}
}
v = v.Elem()
}
return anonEF.i(v.Elem())
return anonEF.i(v)
}
fs = append(fs, bottomField)
}