github.com/goshafaq/sonic@v0.0.0-20231026082336-871835fb94c6/issue_test/issue_recurse_test.go (about)

     1  package issue_test
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"reflect"
     7  	"strconv"
     8  	"testing"
     9  	"time"
    10  
    11  	"github.com/davecgh/go-spew/spew"
    12  	"github.com/goshafaq/sonic"
    13  	"github.com/stretchr/testify/require"
    14  )
    15  
    16  func TestPointerValueRecurseMarshal(t *testing.T) {
    17  	info := &TestStruct1{
    18  		StartTime: JSONTime(time.Now()),
    19  	}
    20  	infos := &[]*TestStruct1{info}
    21  
    22  	bytes, err1 := json.Marshal(infos)
    23  	fmt.Printf("%+v\n", string(bytes))
    24  	spew.Dump(bytes, err1)
    25  
    26  	jbytes, err2 := sonic.Marshal(infos)
    27  	fmt.Printf("%+v\n", string(jbytes))
    28  	spew.Dump(jbytes, err2)
    29  	require.Equal(t, bytes, jbytes)
    30  }
    31  
    32  func TestPointerValueRecursePretouch(t *testing.T) {
    33  	info := &TestStruct2{
    34  		StartTime: JSONTime(time.Now()),
    35  	}
    36  	infos := &[]*TestStruct2{info}
    37  
    38  	bytes, err1 := json.Marshal(infos)
    39  	fmt.Printf("%+v\n", string(bytes))
    40  	spew.Dump(bytes, err1)
    41  
    42  	sonic.Pretouch(reflect.TypeOf(infos))
    43  	jbytes, err2 := sonic.Marshal(infos)
    44  	fmt.Printf("%+v\n", string(jbytes))
    45  	spew.Dump(jbytes, err2)
    46  	require.Equal(t, bytes, jbytes)
    47  }
    48  
    49  type TestStruct1 struct {
    50  	StartTime JSONTime
    51  }
    52  
    53  type TestStruct2 struct {
    54  	StartTime JSONTime
    55  }
    56  
    57  type JSONTime time.Time
    58  
    59  func (t *JSONTime) MarshalJSON() ([]byte, error) {
    60  	return []byte(strconv.FormatInt(time.Time(*t).Unix(), 10)), nil
    61  }