Skip to content

Commit

Permalink
Fix handling of empty value. (#104)
Browse files Browse the repository at this point in the history
If a value is decoding into a type that implements the
encoding.TextUnmarshaler interface, the decoder should use it's
UnmarshalText method in all instances including an empty value.

Previously, would ignore the method decoding the field as the empty
value of the type.
  • Loading branch information
emil2k authored and kisielk committed Mar 21, 2018
1 parent b0e8c20 commit d0e4c24
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 5 deletions.
10 changes: 5 additions & 5 deletions decoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -283,11 +283,7 @@ func (d *Decoder) decode(v reflect.Value, path string, parts []pathPart, values
val = values[len(values)-1]
}

if val == "" {
if d.zeroEmpty {
v.Set(reflect.Zero(t))
}
} else if conv != nil {
if conv != nil {
if value := conv(val); value.IsValid() {
v.Set(value.Convert(t))
} else {
Expand Down Expand Up @@ -321,6 +317,10 @@ func (d *Decoder) decode(v reflect.Value, path string, parts []pathPart, values
}
}
}
} else if val == "" {
if d.zeroEmpty {
v.Set(reflect.Zero(t))
}
} else if conv := builtinConverters[t.Kind()]; conv != nil {
if value := conv(val); value.IsValid() {
v.Set(value.Convert(t))
Expand Down
30 changes: 30 additions & 0 deletions decoder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1737,3 +1737,33 @@ func TestTextUnmarshalerTypeSliceOfStructs(t *testing.T) {
t.Fatal("Expecting invalid path error", err)
}
}

type S22 string

func (s *S22) UnmarshalText(text []byte) error {
*s = S22("a")
return nil
}

// Test to ensure that when a field that should be decoded into a type
// implementing the encoding.TextUnmarshaler interface is set to an empty value
// that the UnmarshalText method is utilized over other methods of decoding,
// especially including simply setting the zero value.
func TestTextUnmarshalerEmpty(t *testing.T) {
data := map[string][]string{
"Value": []string{""}, // empty value
}
// Implements encoding.TextUnmarshaler, should use the type's
// UnmarshalText method.
s := struct {
Value S22
}{}
decoder := NewDecoder()
if err := decoder.Decode(&s, data); err != nil {
t.Fatal("Error while decoding:", err)
}
expected := S22("a")
if expected != s.Value {
t.Errorf("Expected %v errors, got %v", expected, s.Value)
}
}

0 comments on commit d0e4c24

Please sign in to comment.