github.com/zerosnake0/jzon@v0.0.9-0.20230801092939-1b135cb83f7f/encoder_config_test.go (about)

     1  package jzon
     2  
     3  import (
     4  	"reflect"
     5  	"testing"
     6  	"unsafe"
     7  
     8  	"github.com/stretchr/testify/require"
     9  )
    10  
    11  type testIntEncoder struct{}
    12  
    13  func (*testIntEncoder) IsEmpty(ptr unsafe.Pointer) bool {
    14  	return *(*int)(ptr) == 1
    15  }
    16  
    17  func (*testIntEncoder) Encode(ptr unsafe.Pointer, s *Streamer, opts *EncOpts) {
    18  	s.Int(*(*int)(ptr) + 1)
    19  }
    20  
    21  func TestEncoderConfig_CustomConfig(t *testing.T) {
    22  	t.Run("int", func(t *testing.T) {
    23  		encCfg := NewEncoderConfig(&EncoderOption{
    24  			ValEncoders: map[reflect.Type]ValEncoder{
    25  				reflect.TypeOf(int(0)): (*testIntEncoder)(nil),
    26  			},
    27  		})
    28  		t.Run("value", func(t *testing.T) {
    29  			b, err := encCfg.Marshal(1)
    30  			require.NoError(t, err)
    31  			require.Equal(t, "2", string(b))
    32  		})
    33  		t.Run("pointer", func(t *testing.T) {
    34  			i := 1
    35  			b, err := encCfg.Marshal(&i)
    36  			require.NoError(t, err)
    37  			require.Equal(t, "2", string(b))
    38  		})
    39  		t.Run("struct", func(t *testing.T) {
    40  			t.Run("value", func(t *testing.T) {
    41  				type st struct {
    42  					I int `json:",omitempty"`
    43  				}
    44  				t.Run("zero", func(t *testing.T) {
    45  					b, err := encCfg.Marshal(st{})
    46  					require.NoError(t, err)
    47  					require.Equal(t, `{"I":1}`, string(b))
    48  				})
    49  				t.Run("empty", func(t *testing.T) {
    50  					b, err := encCfg.Marshal(st{I: 1})
    51  					require.NoError(t, err)
    52  					require.Equal(t, `{}`, string(b))
    53  				})
    54  			})
    55  			t.Run("pointer", func(t *testing.T) {
    56  				type st struct {
    57  					I *int `json:",omitempty"`
    58  				}
    59  				t.Run("nil", func(t *testing.T) {
    60  					b, err := encCfg.Marshal(st{})
    61  					require.NoError(t, err)
    62  					require.Equal(t, `{}`, string(b))
    63  				})
    64  				t.Run("zero", func(t *testing.T) {
    65  					i := 0
    66  					b, err := encCfg.Marshal(st{I: &i})
    67  					require.NoError(t, err)
    68  					require.Equal(t, `{"I":1}`, string(b))
    69  				})
    70  				t.Run("empty", func(t *testing.T) {
    71  					i := 1
    72  					b, err := encCfg.Marshal(st{I: &i})
    73  					require.NoError(t, err)
    74  					// pointer is not nil so it's not considered as empty
    75  					require.Equal(t, `{"I":2}`, string(b))
    76  				})
    77  			})
    78  		})
    79  	})
    80  }