Skip to content

Commit

Permalink
fix: prevent the error occurs when omitempty is present in a field of… (
Browse files Browse the repository at this point in the history
#21)

* fix: prevent the error occurs when omitempty is present in a field of an embedded pointer type structure

#20

* test: Creating a test when the embedded struct is a pointer type and all its fields have omitempty
  • Loading branch information
shigetaichi authored Oct 17, 2023
1 parent 821231c commit d128959
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 3 deletions.
20 changes: 20 additions & 0 deletions decode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,26 @@ ff,gg,22,hh,ii,jj`)
}
}

func Test_readTo_embed_ptr_all_omitempty(t *testing.T) {
b := bytes.NewBufferString(`first,last,abc,Omit
aa,dd,ee,`)

var rows []EmbedPtrAllOmitemptySample
if err := NewXsvRead[EmbedPtrAllOmitemptySample]().SetReader(csv.NewReader(b)).ReadTo(&rows); err != nil {
t.Fatalf(err.Error())
}
expected := EmbedPtrAllOmitemptySample{
Qux: "aa",
AllOmitEmpty: &AllOmitEmpty{
Omit: nil,
},
Quux: "dd",
}
if !reflect.DeepEqual(expected, rows[0]) {
t.Fatalf("expected first sample %v, got %+v", expected, rows[0])
}
}

func Test_readTo_slice(t *testing.T) {
b := bytes.NewBufferString(`Slice
[]
Expand Down
14 changes: 14 additions & 0 deletions sample_structs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ type Sample struct {
Omit *string `csv:"Omit,omitempty"`
}

type AllOmitEmpty struct {
Omit *string `csv:"Omit,omitempty"`
Omit2 *string `csv:"Omit2,omitempty"`
Omit3 *string `csv:"Omit3,omitempty"`
}

type SliceSample struct {
Slice []int `csv:"Slice"`
}
Expand Down Expand Up @@ -101,6 +107,14 @@ type EmbedPtrSample struct {
Quux string `csv:"last"`
}

type EmbedPtrAllOmitemptySample struct {
Qux string `csv:"first"`
*AllOmitEmpty
Ignore string `csv:"-"`
Grault float64 `csv:"garply"`
Quux string `csv:"last"`
}

type SkipFieldSample struct {
EmbedSample
MoreIgnore string `csv:"-"`
Expand Down
8 changes: 5 additions & 3 deletions types.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,10 +217,12 @@ func toFloat(in interface{}) (float64, error) {

func setField(field reflect.Value, value string, omitEmpty bool) error {
if field.Kind() == reflect.Ptr {
if omitEmpty && value == "" {
return nil
}
if field.IsNil() {
if omitEmpty && value == "" {
if field.Type().Elem().Kind() != reflect.Struct {
return nil
}
}
field.Set(reflect.New(field.Type().Elem()))
}
field = field.Elem()
Expand Down

0 comments on commit d128959

Please sign in to comment.