Fix Setter handling on non-pointer fields.

Fixes #8.
This commit is contained in:
Gustavo Niemeyer 2014-05-01 10:47:07 -07:00
Родитель a5844a8f8f
Коммит 41c132e8ac
2 изменённых файлов: 29 добавлений и 5 удалений

Просмотреть файл

@ -212,6 +212,16 @@ func newDecoder() *decoder {
// returned to call SetYAML() with the value of *out once it's defined. // returned to call SetYAML() with the value of *out once it's defined.
// //
func (d *decoder) setter(tag string, out *reflect.Value, good *bool) (set func()) { func (d *decoder) setter(tag string, out *reflect.Value, good *bool) (set func()) {
if (*out).Kind() != reflect.Ptr && (*out).CanAddr() {
setter, _ := (*out).Addr().Interface().(Setter)
if setter != nil {
var arg interface{}
*out = reflect.ValueOf(&arg).Elem()
return func() {
*good = setter.SetYAML(tag, arg)
}
}
}
again := true again := true
for again { for again {
again = false again = false

Просмотреть файл

@ -465,17 +465,31 @@ func (o *typeWithSetter) SetYAML(tag string, value interface{}) (ok bool) {
return true return true
} }
type typeWithSetterField struct { type setterPointerType struct {
Field *typeWithSetter "_" Field *typeWithSetter "_"
} }
func (s *S) TestUnmarshalWithSetter(c *C) { type setterValueType struct {
Field typeWithSetter "_"
}
func (s *S) TestUnmarshalWithPointerSetter(c *C) {
for _, item := range setterTests { for _, item := range setterTests {
obj := &typeWithSetterField{} obj := &setterPointerType{}
err := yaml.Unmarshal([]byte(item.data), obj) err := yaml.Unmarshal([]byte(item.data), obj)
c.Assert(err, IsNil) c.Assert(err, IsNil)
c.Assert(obj.Field, NotNil, c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value))
Commentf("Pointer not initialized (%#v)", item.value)) c.Assert(obj.Field.tag, Equals, item.tag)
c.Assert(obj.Field.value, DeepEquals, item.value)
}
}
func (s *S) TestUnmarshalWithValueSetter(c *C) {
for _, item := range setterTests {
obj := &setterValueType{}
err := yaml.Unmarshal([]byte(item.data), obj)
c.Assert(err, IsNil)
c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value))
c.Assert(obj.Field.tag, Equals, item.tag) c.Assert(obj.Field.tag, Equals, item.tag)
c.Assert(obj.Field.value, DeepEquals, item.value) c.Assert(obj.Field.value, DeepEquals, item.value)
} }